idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
100
Object getDataValuesForType ( Entity entity , Attribute attribute ) { String attributeName = attribute . getName ( ) ; switch ( attribute . getDataType ( ) ) { case DATE : return entity . getLocalDate ( attributeName ) ; case DATE_TIME : return entity . getInstant ( attributeName ) ; case BOOL : return entity . getBoolean ( attributeName ) ; case DECIMAL : return entity . getDouble ( attributeName ) ; case LONG : return entity . getLong ( attributeName ) ; case INT : return entity . getInt ( attributeName ) ; case HYPERLINK : case ENUM : case HTML : case TEXT : case SCRIPT : case EMAIL : case STRING : return entity . getString ( attributeName ) ; case CATEGORICAL : case XREF : case FILE : Entity refEntity = entity . getEntity ( attributeName ) ; if ( refEntity != null ) return refEntity . getIdValue ( ) ; else return "" ; case CATEGORICAL_MREF : case MREF : List < String > mrefValues = newArrayList ( ) ; for ( Entity mrefEntity : entity . getEntities ( attributeName ) ) { if ( mrefEntity != null ) { mrefValues . add ( mrefEntity . getIdValue ( ) . toString ( ) ) ; } } return mrefValues ; case COMPOUND : return "" ; default : return "" ; } }
Package - private for testability .
101
private void validate ( Entity entity ) { MailSettingsImpl mailSettings = new MailSettingsImpl ( entity ) ; if ( mailSettings . isTestConnection ( ) && mailSettings . getUsername ( ) != null && mailSettings . getPassword ( ) != null ) { mailSenderFactory . validateConnection ( mailSettings ) ; } }
Validates MailSettings .
102
public boolean upgrade ( ) { int schemaVersion = versionService . getSchemaVersion ( ) ; if ( schemaVersion < 31 ) { throw new UnsupportedOperationException ( "Upgrading from schema version below 31 is not supported" ) ; } if ( schemaVersion < versionService . getAppVersion ( ) ) { LOG . info ( "Metadata version:{}, current version:{} upgrade needed" , schemaVersion , versionService . getAppVersion ( ) ) ; upgrades . stream ( ) . filter ( upgrade -> upgrade . getFromVersion ( ) >= schemaVersion ) . forEach ( this :: runUpgrade ) ; versionService . setSchemaVersion ( versionService . getAppVersion ( ) ) ; LOG . info ( "Metadata upgrade done." ) ; return true ; } else { LOG . debug ( "Metadata version:{}, current version:{} upgrade not needed" , schemaVersion , versionService . getAppVersion ( ) ) ; return false ; } }
Executes MOLGENIS MetaData version upgrades .
103
protected void onStartup ( ServletContext servletContext , Class < ? > appConfig , int maxFileSize ) { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext ( ) ; rootContext . setAllowBeanDefinitionOverriding ( false ) ; rootContext . register ( appConfig ) ; servletContext . addListener ( new ContextLoaderListener ( rootContext ) ) ; DispatcherServlet dispatcherServlet = new DispatcherServlet ( rootContext ) ; dispatcherServlet . setDispatchOptionsRequest ( true ) ; dispatcherServlet . setThrowExceptionIfNoHandlerFound ( true ) ; ServletRegistration . Dynamic dispatcherServletRegistration = servletContext . addServlet ( "dispatcher" , dispatcherServlet ) ; if ( dispatcherServletRegistration == null ) { LOG . warn ( "ServletContext already contains a complete ServletRegistration for servlet 'dispatcher'" ) ; } else { final long maxSize = ( long ) maxFileSize * MB ; dispatcherServletRegistration . addMapping ( "/" ) ; dispatcherServletRegistration . setMultipartConfig ( new MultipartConfigElement ( null , maxSize , maxSize , FILE_SIZE_THRESHOLD ) ) ; dispatcherServletRegistration . setAsyncSupported ( true ) ; } Dynamic browserDetectionFiler = servletContext . addFilter ( "browserDetectionFilter" , BrowserDetectionFilter . class ) ; browserDetectionFiler . setAsyncSupported ( true ) ; browserDetectionFiler . addMappingForUrlPatterns ( EnumSet . of ( DispatcherType . REQUEST , DispatcherType . ASYNC ) , false , "*" ) ; Dynamic etagFilter = servletContext . addFilter ( "etagFilter" , ShallowEtagHeaderFilter . class ) ; etagFilter . setAsyncSupported ( true ) ; etagFilter . addMappingForServletNames ( EnumSet . of ( DispatcherType . REQUEST , DispatcherType . ASYNC ) , true , "dispatcher" ) ; servletContext . addListener ( new RequestContextListener ( ) ) ; servletContext . addListener ( HttpSessionEventPublisher . class ) ; }
A Molgenis common web application initializer
104
Document createDocument ( Entity entity ) { int maxIndexingDepth = entity . getEntityType ( ) . getIndexingDepth ( ) ; XContentBuilder contentBuilder ; try { contentBuilder = XContentFactory . contentBuilder ( JSON ) ; XContentGenerator generator = contentBuilder . generator ( ) ; generator . writeStartObject ( ) ; createRec ( entity , generator , 0 , maxIndexingDepth ) ; generator . writeEndObject ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } String documentId = toElasticsearchId ( entity . getIdValue ( ) ) ; return Document . create ( documentId , contentBuilder ) ; }
Create Elasticsearch document source content from entity
105
@ GetMapping ( "/**" ) public String initView ( Model model ) { super . init ( model , ID ) ; model . addAttribute ( "username" , super . userAccountService . getCurrentUser ( ) . getUsername ( ) ) ; return QUESTIONNAIRE_VIEW ; }
Loads the questionnaire view
106
@ SuppressWarnings ( "squid:S2259" ) public Package getRootPackage ( ) { Package aPackage = this ; while ( aPackage . getParent ( ) != null ) { aPackage = aPackage . getParent ( ) ; } return aPackage ; }
Get the root of this package or itself if this is a root package
107
public void renumberViolationRowIndices ( List < Integer > actualIndices ) { violations . forEach ( v -> v . renumberRowIndex ( actualIndices ) ) ; }
renumber the violation row indices with the actual row numbers
108
public static Style createLocal ( String location ) { String name = location . replaceFirst ( "bootstrap-" , "" ) ; name = name . replaceFirst ( ".min" , "" ) ; name = name . replaceFirst ( ".css" , "" ) ; return new AutoValue_Style ( name , false , location ) ; }
Create new style . The name of the style is based off of the location string the optional boostrap - prefix and . min and . css affixes are removed from the name .
109
public void populate ( ) { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver ( ) ; try { Resource [ ] bootstrap3Themes = resolver . getResources ( LOCAL_CSS_BOOTSTRAP_3_THEME_LOCATION ) ; Resource [ ] bootstrap4Themes = resolver . getResources ( LOCAL_CSS_BOOTSTRAP_4_THEME_LOCATION ) ; List < Resource > newThemes = Arrays . stream ( bootstrap3Themes ) . filter ( theme -> dataService . getRepository ( STYLE_SHEET ) . findOneById ( theme . getFilename ( ) ) == null ) . collect ( Collectors . toList ( ) ) ; newThemes . forEach ( nt -> { try { addNewTheme ( nt , bootstrap4Themes ) ; } catch ( IOException | MolgenisStyleException e ) { LOG . error ( "error adding new bootstrap themes" , e ) ; } } ) ; } catch ( IOException e ) { LOG . error ( "error populating bootstrap themes" , e ) ; } }
Populate the database with the available bootstrap themes found in the jar . This enables the release of the application with a set of predefined bootstrap themes .
110
public static Fetch createDefaultEntityFetch ( EntityType entityType , String languageCode ) { boolean hasRefAttr = false ; Fetch fetch = new Fetch ( ) ; for ( Attribute attr : entityType . getAtomicAttributes ( ) ) { Fetch subFetch = createDefaultAttributeFetch ( attr , languageCode ) ; if ( subFetch != null ) { hasRefAttr = true ; } fetch . field ( attr . getName ( ) , subFetch ) ; } return hasRefAttr ? fetch : null ; }
Create default entity fetch that fetches all attributes .
111
public static Fetch createDefaultAttributeFetch ( Attribute attr , String languageCode ) { Fetch fetch ; if ( isReferenceType ( attr ) ) { fetch = new Fetch ( ) ; EntityType refEntityType = attr . getRefEntity ( ) ; String idAttrName = refEntityType . getIdAttribute ( ) . getName ( ) ; fetch . field ( idAttrName ) ; String labelAttrName = refEntityType . getLabelAttribute ( languageCode ) . getName ( ) ; if ( ! labelAttrName . equals ( idAttrName ) ) { fetch . field ( labelAttrName ) ; } if ( attr . getDataType ( ) == FILE ) { fetch . field ( FileMetaMetadata . URL ) ; } } else { fetch = null ; } return fetch ; }
Create default fetch for the given attribute . For attributes referencing entities the id and label value are fetched . Additionally for file entities the URL is fetched . For other attributes the default fetch is null ;
112
public void renumberRowIndex ( List < Integer > indices ) { this . rowNr = this . rowNr != null ? Long . valueOf ( indices . get ( toIntExact ( this . rowNr - 1 ) ) ) : null ; }
Renumber the violation row number from a list of actual row numbers The list of indices is 0 - indexed and the rownnr are 1 - indexed
113
public static String generateScript ( Script script , Map < String , Object > parameterValues ) { StringWriter stringWriter = new StringWriter ( ) ; try { Template template = new Template ( null , new StringReader ( script . getContent ( ) ) , new Configuration ( VERSION ) ) ; template . process ( parameterValues , stringWriter ) ; } catch ( TemplateException | IOException e ) { throw new GenerateScriptException ( "Error processing parameters for script [" + script . getName ( ) + "]. " + e . getMessage ( ) ) ; } return stringWriter . toString ( ) ; }
Render a script using the given parameter values
114
@ Transactional ( readOnly = true ) public UserDetails findUserByToken ( String token ) { Token molgenisToken = getMolgenisToken ( token ) ; return userDetailsService . loadUserByUsername ( molgenisToken . getUser ( ) . getUsername ( ) ) ; }
Find a user by a security token
115
public String generateAndStoreToken ( String username , String description ) { User user = dataService . query ( USER , User . class ) . eq ( USERNAME , username ) . findOne ( ) ; if ( user == null ) { throw new IllegalArgumentException ( format ( "Unknown username [%s]" , username ) ) ; } String token = tokenGenerator . generateToken ( ) ; Token molgenisToken = tokenFactory . create ( ) ; molgenisToken . setUser ( user ) ; molgenisToken . setToken ( token ) ; molgenisToken . setDescription ( description ) ; molgenisToken . setExpirationDate ( now ( ) . plus ( 2 , HOURS ) ) ; dataService . add ( TOKEN , molgenisToken ) ; return token ; }
Generates a token and associates it with a user .
116
static String generateUniqueLabel ( String label , Set < String > existingLabels ) { StringBuilder newLabel = new StringBuilder ( label ) ; while ( existingLabels . contains ( newLabel . toString ( ) ) ) { newLabel . append ( POSTFIX ) ; } return newLabel . toString ( ) ; }
Makes sure that a given label will be unique amongst a set of other labels .
117
public String resolveCodeWithoutArguments ( String code , Locale locale ) { return Optional . ofNullable ( dataService . query ( L10N_STRING , L10nString . class ) . eq ( MSGID , code ) . findOne ( ) ) . map ( l10nString -> l10nString . getString ( locale ) ) . orElse ( null ) ; }
Looks up a single localized message .
118
public Map < String , String > getMessages ( String namespace , Locale locale ) { return getL10nStrings ( namespace ) . stream ( ) . filter ( e -> e . getString ( locale ) != null ) . collect ( toMap ( L10nString :: getMessageID , e -> e . getString ( locale ) ) ) ; }
Gets all messages for a certain namespace and languageCode . Returns exactly those messages that are explicitly specified for this namespace and languageCode . Does not fall back to the default language .
119
public void deleteNamespace ( String namespace ) { List < L10nString > namespaceEntities = getL10nStrings ( namespace ) ; dataService . delete ( L10N_STRING , namespaceEntities . stream ( ) ) ; }
Deletes all localization strings for a given namespace
120
@ SuppressWarnings ( "WeakerAccess" ) public final < R > Optional < R > apply ( Timeout timeout , Function < T , R > function ) throws InterruptedException { T obj = claim ( timeout ) ; if ( obj == null ) { return Optional . empty ( ) ; } try { return Optional . ofNullable ( function . apply ( obj ) ) ; } finally { obj . release ( ) ; } }
Claim an object from the pool and apply the given function to it returning the result and releasing the object back to the pool .
121
@ SuppressWarnings ( "WeakerAccess" ) public final boolean supply ( Timeout timeout , Consumer < T > consumer ) throws InterruptedException { T obj = claim ( timeout ) ; if ( obj == null ) { return false ; } try { consumer . accept ( obj ) ; return true ; } finally { obj . release ( ) ; } }
Claim an object from the pool and supply it to the given consumer and then release it back to the pool .
122
Reallocator < T > getAdaptedReallocator ( ) { if ( allocator == null ) { return null ; } if ( metricsRecorder == null ) { if ( allocator instanceof Reallocator ) { return ( Reallocator < T > ) allocator ; } return new ReallocatingAdaptor < > ( ( Allocator < T > ) allocator ) ; } else { if ( allocator instanceof Reallocator ) { return new TimingReallocatorAdaptor < > ( ( Reallocator < T > ) allocator , metricsRecorder ) ; } return new TimingReallocatingAdaptor < > ( ( Allocator < T > ) allocator , metricsRecorder ) ; } }
Returns null if no allocator has been configured . Otherwise returns a Reallocator possibly by adapting the configured Allocator if need be . If a MetricsRecorder has been configured the return Reallocator will automatically record allocation reallocation and deallocation latencies .
123
public void setFunctionName ( String functionName ) { String oldFunctionName = functionName ; this . functionName = functionName ; firePropertyChange ( "FunctionName" , oldFunctionName , functionName ) ; }
Sets the functionName
124
public static String getSpringBootMavenPluginClassifier ( MavenProject project , Log log ) { String classifier = null ; try { classifier = MavenProjectUtil . getPluginGoalConfigurationString ( project , "org.springframework.boot:spring-boot-maven-plugin" , "repackage" , "classifier" ) ; } catch ( PluginScenarioException e ) { log . debug ( "No classifier found for spring-boot-maven-plugin" ) ; } return classifier ; }
Read the value of the classifier configuration parameter from the spring - boot - maven - plugin
125
public static File getSpringBootUberJAR ( MavenProject project , Log log ) { File fatArchive = getSpringBootUberJARLocation ( project , log ) ; if ( net . wasdev . wlp . common . plugins . util . SpringBootUtil . isSpringBootUberJar ( fatArchive ) ) { log . info ( "Found Spring Boot Uber JAR: " + fatArchive . getAbsolutePath ( ) ) ; return fatArchive ; } log . warn ( "Spring Boot Uber JAR was not found in expected location: " + fatArchive . getAbsolutePath ( ) ) ; return null ; }
Get the Spring Boot Uber JAR in its expected location validating the JAR contents and handling spring - boot - maven - plugin classifier configuration as well . If the JAR was not found in its expected location then return null .
126
public static File getSpringBootUberJARLocation ( MavenProject project , Log log ) { String classifier = getSpringBootMavenPluginClassifier ( project , log ) ; if ( classifier == null ) { classifier = "" ; } if ( ! classifier . isEmpty ( ) && ! classifier . startsWith ( "-" ) ) { classifier = "-" + classifier ; } return new File ( project . getBuild ( ) . getDirectory ( ) , project . getBuild ( ) . getFinalName ( ) + classifier + "." + project . getArtifact ( ) . getArtifactHandler ( ) . getExtension ( ) ) ; }
Get the Spring Boot Uber JAR in its expected location taking into account the spring - boot - maven - plugin classifier configuration as well . No validation is done that is there is no guarantee the JAR file actually exists at the returned location .
127
protected void installServerAssembly ( ) throws Exception { if ( installType == InstallType . ALREADY_EXISTS ) { log . info ( MessageFormat . format ( messages . getString ( "info.install.type.preexisting" ) , "" ) ) ; } else { if ( installType == InstallType . FROM_ARCHIVE ) { installFromArchive ( ) ; } else { installFromFile ( ) ; } installLicense ( ) ; } }
Performs assembly installation unless the install type is pre - existing .
128
protected String stripVersionFromName ( String name , String version ) { int versionBeginIndex = name . lastIndexOf ( "-" + version ) ; if ( versionBeginIndex != - 1 ) { return name . substring ( 0 , versionBeginIndex ) + name . substring ( versionBeginIndex + version . length ( ) + 1 ) ; } else { return name ; } }
Strip version string from name
129
private String getWlpOutputDir ( ) throws IOException { Properties envvars = new Properties ( ) ; File serverEnvFile = new File ( installDirectory , "etc/server.env" ) ; if ( serverEnvFile . exists ( ) ) { envvars . load ( new FileInputStream ( serverEnvFile ) ) ; } serverEnvFile = new File ( configDirectory , "server.env" ) ; if ( configDirectory != null && serverEnvFile . exists ( ) ) { envvars . load ( new FileInputStream ( serverEnvFile ) ) ; } else if ( serverEnv . exists ( ) ) { envvars . load ( new FileInputStream ( serverEnv ) ) ; } return ( String ) envvars . get ( "WLP_OUTPUT_DIR" ) ; }
exist or variable is not in server . env
130
protected Artifact createArtifact ( final ArtifactItem item ) throws MojoExecutionException { assert item != null ; if ( item . getVersion ( ) == null ) { throw new MojoExecutionException ( "Unable to find artifact without version specified: " + item . getGroupId ( ) + ":" + item . getArtifactId ( ) + ":" + item . getVersion ( ) + " in either project dependencies or in project dependencyManagement." ) ; } if ( item . getVersion ( ) . trim ( ) . startsWith ( "[" ) || item . getVersion ( ) . trim ( ) . startsWith ( "(" ) ) { try { item . setVersion ( resolveVersionRange ( item . getGroupId ( ) , item . getArtifactId ( ) , item . getType ( ) , item . getVersion ( ) ) ) ; } catch ( VersionRangeResolutionException e ) { throw new MojoExecutionException ( "Could not get the highest version from the range: " + item . getVersion ( ) , e ) ; } } return resolveArtifactItem ( item ) ; }
Create a new artifact .
131
public void addFeature ( String feature ) { if ( feature == null ) { throw new IllegalArgumentException ( "Invalid null argument passed for addFeature" ) ; } feature = feature . trim ( ) ; if ( ! feature . isEmpty ( ) ) { Feature newFeature = new Feature ( ) ; newFeature . addText ( feature ) ; featureList . add ( newFeature ) ; } }
Add a feature into a list .
132
public static String getPluginConfiguration ( MavenProject proj , String pluginGroupId , String pluginArtifactId , String key ) { Xpp3Dom dom = proj . getGoalConfiguration ( pluginGroupId , pluginArtifactId , null , null ) ; if ( dom != null ) { Xpp3Dom val = dom . getChild ( key ) ; if ( val != null ) { return val . getValue ( ) ; } } return null ; }
Get a configuration value from a plugin
133
public static String getPluginGoalConfigurationString ( MavenProject project , String pluginKey , String goal , String configName ) throws PluginScenarioException { PluginExecution execution = getPluginGoalExecution ( project , pluginKey , goal ) ; final Xpp3Dom config = ( Xpp3Dom ) execution . getConfiguration ( ) ; if ( config != null ) { Xpp3Dom configElement = config . getChild ( configName ) ; if ( configElement != null ) { String value = configElement . getValue ( ) . trim ( ) ; return value ; } } throw new PluginScenarioException ( "Could not find configuration string " + configName + " for goal " + goal + " on plugin " + pluginKey ) ; }
Get a configuration value from a goal from a plugin
134
public static File getManifestFile ( MavenProject proj , String pluginArtifactId ) { Xpp3Dom dom = proj . getGoalConfiguration ( "org.apache.maven.plugins" , pluginArtifactId , null , null ) ; if ( dom != null ) { Xpp3Dom archive = dom . getChild ( "archive" ) ; if ( archive != null ) { Xpp3Dom val = archive . getChild ( "manifestFile" ) ; if ( val != null ) { return new File ( proj . getBasedir ( ) . getAbsolutePath ( ) + "/" + val . getValue ( ) ) ; } } } return null ; }
Get manifest file from plugin configuration
135
protected void installLooseConfigWar ( MavenProject proj , LooseConfigData config ) throws Exception { File dir = new File ( proj . getBuild ( ) . getOutputDirectory ( ) ) ; if ( ! dir . exists ( ) && containsJavaSource ( proj ) ) { throw new MojoExecutionException ( MessageFormat . format ( messages . getString ( "error.project.not.compile" ) , proj . getId ( ) ) ) ; } LooseWarApplication looseWar = new LooseWarApplication ( proj , config ) ; looseWar . addSourceDir ( proj ) ; looseWar . addOutputDir ( looseWar . getDocumentRoot ( ) , new File ( proj . getBuild ( ) . getOutputDirectory ( ) ) , "/WEB-INF/classes" ) ; addEmbeddedLib ( looseWar . getDocumentRoot ( ) , proj , looseWar , "/WEB-INF/lib/" ) ; File manifestFile = MavenProjectUtil . getManifestFile ( proj , "maven-war-plugin" ) ; looseWar . addManifestFile ( manifestFile ) ; }
install war project artifact using loose application configuration file
136
protected void installLooseConfigEar ( MavenProject proj , LooseConfigData config ) throws Exception { LooseEarApplication looseEar = new LooseEarApplication ( proj , config ) ; looseEar . addSourceDir ( ) ; looseEar . addApplicationXmlFile ( ) ; Set < Artifact > artifacts = proj . getArtifacts ( ) ; log . debug ( "Number of compile dependencies for " + proj . getArtifactId ( ) + " : " + artifacts . size ( ) ) ; for ( Artifact artifact : artifacts ) { if ( "compile" . equals ( artifact . getScope ( ) ) || "runtime" . equals ( artifact . getScope ( ) ) ) { if ( ! isReactorMavenProject ( artifact ) ) { if ( looseEar . isEarSkinnyWars ( ) && "war" . equals ( artifact . getType ( ) ) ) { throw new MojoExecutionException ( "Unable to create loose configuration for the EAR application with skinnyWars package from " + artifact . getGroupId ( ) + ":" + artifact . getArtifactId ( ) + ":" + artifact . getVersion ( ) + ". Please set the looseApplication configuration parameter to false and try again." ) ; } looseEar . addModuleFromM2 ( resolveArtifact ( artifact ) ) ; } else { MavenProject dependencyProject = getReactorMavenProject ( artifact ) ; switch ( artifact . getType ( ) ) { case "jar" : looseEar . addJarModule ( dependencyProject ) ; break ; case "ejb" : looseEar . addEjbModule ( dependencyProject ) ; break ; case "war" : Element warArchive = looseEar . addWarModule ( dependencyProject , getWarSourceDirectory ( dependencyProject ) ) ; if ( looseEar . isEarSkinnyWars ( ) ) { addSkinnyWarLib ( warArchive , dependencyProject , looseEar ) ; } else { addEmbeddedLib ( warArchive , dependencyProject , looseEar , "/WEB-INF/lib/" ) ; } break ; case "rar" : Element rarArchive = looseEar . addRarModule ( dependencyProject ) ; addEmbeddedLib ( rarArchive , dependencyProject , looseEar , "/" ) ; break ; default : looseEar . addModuleFromM2 ( resolveArtifact ( artifact ) ) ; break ; } } } } File manifestFile = MavenProjectUtil . getManifestFile ( proj , "maven-ear-plugin" ) ; looseEar . addManifestFile ( manifestFile ) ; }
install ear project artifact using loose application configuration file
137
private String getAppFileName ( MavenProject project ) { String name = project . getBuild ( ) . getFinalName ( ) + "." + project . getPackaging ( ) ; if ( project . getPackaging ( ) . equals ( "liberty-assembly" ) ) { name = project . getBuild ( ) . getFinalName ( ) + ".war" ; } if ( stripVersion ) { name = stripVersionFromName ( name , project . getVersion ( ) ) ; } return name ; }
get loose application configuration file name for project artifact
138
protected void invokeSpringBootUtilCommand ( File installDirectory , String fatArchiveSrcLocation , String thinArchiveTargetLocation , String libIndexCacheTargetLocation ) throws Exception { SpringBootUtilTask springBootUtilTask = ( SpringBootUtilTask ) ant . createTask ( "antlib:net/wasdev/wlp/ant:springBootUtil" ) ; if ( springBootUtilTask == null ) { throw new IllegalStateException ( MessageFormat . format ( messages . getString ( "error.dependencies.not.found" ) , "springBootUtil" ) ) ; } Validate . notNull ( fatArchiveSrcLocation , "Spring Boot source archive location cannot be null" ) ; Validate . notNull ( thinArchiveTargetLocation , "Target thin archive location cannot be null" ) ; Validate . notNull ( libIndexCacheTargetLocation , "Library cache location cannot be null" ) ; springBootUtilTask . setInstallDir ( installDirectory ) ; springBootUtilTask . setTargetThinAppPath ( thinArchiveTargetLocation ) ; springBootUtilTask . setSourceAppPath ( fatArchiveSrcLocation ) ; springBootUtilTask . setTargetLibCachePath ( libIndexCacheTargetLocation ) ; springBootUtilTask . execute ( ) ; }
Executes the SpringBootUtilTask to thin the Spring Boot application executable archive and place the thin archive and lib . index . cache in the specified location .
139
public void onCreate ( Activity activity , Bundle savedInstanceState ) { this . activity = activity ; container = ( ScreenContainer ) activity . findViewById ( R . id . magellan_container ) ; checkState ( container != null , "There must be a ScreenContainer whose id is R.id.magellan_container in the view hierarchy" ) ; for ( Screen screen : backStack ) { screen . restore ( savedInstanceState ) ; screen . onRestore ( savedInstanceState ) ; } showCurrentScreen ( FORWARD ) ; }
Initializes the Navigator with Activity instance and Bundle for saved instance state .
140
public void onSaveInstanceState ( Bundle outState ) { for ( Screen screen : backStack ) { screen . save ( outState ) ; screen . onSave ( outState ) ; } }
Notifies all screens to save instance state in input Bundle .
141
public void resetWithRoot ( Activity activity , final Screen root ) { checkOnCreateNotYetCalled ( activity , "resetWithRoot() must be called before onCreate()" ) ; backStack . clear ( ) ; backStack . push ( root ) ; }
Clears the back stack of this Navigator and adds the input Screen as the new root of the back stack .
142
public void goBackToRoot ( NavigationType navigationType ) { navigate ( new HistoryRewriter ( ) { public void rewriteHistory ( Deque < Screen > history ) { while ( history . size ( ) > 1 ) { history . pop ( ) ; } } } , navigationType , BACKWARD ) ; }
Navigates from current screen all the way to the root screen in this Navigator s back stack removing all intermediate screen in this Navigator s back stack along the way . The current screen animates out of the view according to the animation specified by the NavigationType parameter .
143
public String getBackStackDescription ( ) { ArrayList < Screen > backStackCopy = new ArrayList < > ( backStack ) ; Collections . reverse ( backStackCopy ) ; String currentScreen = "" ; if ( ! backStackCopy . isEmpty ( ) ) { currentScreen = backStackCopy . remove ( backStackCopy . size ( ) - 1 ) . toString ( ) ; } return TextUtils . join ( " > " , backStackCopy ) + ( backStackCopy . isEmpty ( ) ? "" : " > " ) + "[" + currentScreen + "]" ; }
Returns a human - readable string describing the screens in this Navigator s back stack .
144
public int read ( final byte [ ] buffer , final int bufPos , final int length ) throws IOException { int i = super . read ( buffer , bufPos , length ) ; if ( ( i == length ) || ( i == - 1 ) ) return i ; int j = super . read ( buffer , bufPos + i , length - i ) ; if ( j == - 1 ) return i ; return j + i ; }
Workaround for an unexpected behavior of BufferedInputStream !
145
private String sendBind ( BindType bindType , String systemId , String password , String systemType , InterfaceVersion interfaceVersion , TypeOfNumber addrTon , NumberingPlanIndicator addrNpi , String addressRange , long timeout ) throws PDUException , ResponseTimeoutException , InvalidResponseException , NegativeResponseException , IOException { BindCommandTask task = new BindCommandTask ( pduSender ( ) , bindType , systemId , password , systemType , interfaceVersion , addrTon , addrNpi , addressRange ) ; BindResp resp = ( BindResp ) executeSendCommand ( task , timeout ) ; OptionalParameter . Sc_interface_version scVersion = resp . getOptionalParameter ( Sc_interface_version . class ) ; if ( scVersion != null ) { logger . debug ( "Other side reports SMPP interface version {}" , scVersion ) ; } logger . info ( "Bind response systemId '{}'" , resp . getSystemId ( ) ) ; return resp . getSystemId ( ) ; }
Sending bind .
146
public OutbindRequest waitForOutbind ( long timeout ) throws IllegalStateException , TimeoutException { SessionState currentSessionState = getSessionState ( ) ; if ( currentSessionState . equals ( SessionState . OPEN ) ) { new SMPPOutboundServerSession . PDUReaderWorker ( ) . start ( ) ; try { return outbindRequestReceiver . waitForRequest ( timeout ) ; } catch ( IllegalStateException e ) { throw new IllegalStateException ( "Invocation of waitForOutbind() has been made" , e ) ; } catch ( TimeoutException e ) { close ( ) ; throw e ; } } else { throw new IllegalStateException ( "waitForOutbind() should be invoked on OPEN state, actual state is " + currentSessionState ) ; } }
Wait for outbind request .
147
public String bind ( BindParameter bindParam , long timeout ) throws IOException { try { String smscSystemId = sendBind ( bindParam . getBindType ( ) , bindParam . getSystemId ( ) , bindParam . getPassword ( ) , bindParam . getSystemType ( ) , bindParam . getInterfaceVersion ( ) , bindParam . getAddrTon ( ) , bindParam . getAddrNpi ( ) , bindParam . getAddressRange ( ) , timeout ) ; sessionContext . bound ( bindParam . getBindType ( ) ) ; logger . info ( "Start EnquireLinkSender" ) ; enquireLinkSender = new EnquireLinkSender ( ) ; enquireLinkSender . start ( ) ; return smscSystemId ; } catch ( PDUException e ) { logger . error ( "Failed sending bind command" , e ) ; throw new IOException ( "Failed sending bind since some string parameter area invalid: " + e . getMessage ( ) , e ) ; } catch ( NegativeResponseException e ) { String message = "Receive negative bind response" ; logger . error ( message , e ) ; close ( ) ; throw new IOException ( message + ": " + e . getMessage ( ) , e ) ; } catch ( InvalidResponseException e ) { String message = "Receive invalid response of bind" ; logger . error ( message , e ) ; close ( ) ; throw new IOException ( message + ": " + e . getMessage ( ) , e ) ; } catch ( ResponseTimeoutException e ) { String message = "Waiting bind response take time too long" ; logger . error ( message , e ) ; close ( ) ; throw new IOException ( message + ": " + e . getMessage ( ) , e ) ; } catch ( IOException e ) { logger . error ( "IO error occurred" , e ) ; close ( ) ; throw e ; } }
Bind immediately .
148
public static String convertHexStringToString ( String hexString ) { String uHexString = hexString . toLowerCase ( ) ; StringBuilder sBld = new StringBuilder ( ) ; for ( int i = 0 ; i < uHexString . length ( ) ; i = i + 2 ) { char c = ( char ) Integer . parseInt ( uHexString . substring ( i , i + 2 ) , 16 ) ; sBld . append ( c ) ; } return sBld . toString ( ) ; }
Convert the hex string to string .
149
public static byte [ ] convertHexStringToBytes ( String hexString , int offset , int endIndex ) { byte [ ] data ; String realHexString = hexString . substring ( offset , endIndex ) . toLowerCase ( ) ; if ( ( realHexString . length ( ) % 2 ) == 0 ) data = new byte [ realHexString . length ( ) / 2 ] ; else data = new byte [ ( int ) Math . ceil ( realHexString . length ( ) / 2d ) ] ; int j = 0 ; char [ ] tmp ; for ( int i = 0 ; i < realHexString . length ( ) ; i += 2 ) { try { tmp = realHexString . substring ( i , i + 2 ) . toCharArray ( ) ; } catch ( StringIndexOutOfBoundsException siob ) { tmp = ( realHexString . substring ( i ) + "0" ) . toCharArray ( ) ; } data [ j ] = ( byte ) ( ( Arrays . binarySearch ( hexChar , tmp [ 0 ] ) & 0xf ) << 4 ) ; data [ j ++ ] |= ( byte ) ( Arrays . binarySearch ( hexChar , tmp [ 1 ] ) & 0xf ) ; } for ( int i = realHexString . length ( ) ; i > 0 ; i -= 2 ) { } return data ; }
Convert the hex string to bytes .
150
private static String intToString ( int value , int digit ) { StringBuilder stringBuilder = new StringBuilder ( digit ) ; stringBuilder . append ( Integer . toString ( value ) ) ; while ( stringBuilder . length ( ) < digit ) { stringBuilder . insert ( 0 , "0" ) ; } return stringBuilder . toString ( ) ; }
Create String representation of integer . Preceding 0 will be add as needed .
151
private static String getDeliveryReceiptValue ( String attrName , String source ) throws IndexOutOfBoundsException { String tmpAttr = attrName + ":" ; int startIndex = source . indexOf ( tmpAttr ) ; if ( startIndex < 0 ) { return null ; } startIndex = startIndex + tmpAttr . length ( ) ; int endIndex = source . indexOf ( " " , startIndex ) ; if ( endIndex > 0 ) { return source . substring ( startIndex , endIndex ) ; } return source . substring ( startIndex ) ; }
Get the delivery receipt attribute value .
152
private SMPPSession getSession ( ) throws IOException { if ( session == null ) { LOGGER . info ( "Initiate session for the first time to {}:{}" , remoteIpAddress , remotePort ) ; session = newSession ( ) ; } else if ( ! session . getSessionState ( ) . isBound ( ) ) { throw new IOException ( "We have no valid session yet" ) ; } return session ; }
Get the session . If the session still null or not in bound state then IO exception will be thrown .
153
private void reconnectAfter ( final long timeInMillis ) { new Thread ( ) { public void run ( ) { LOGGER . info ( "Schedule reconnect after {} millis" , timeInMillis ) ; try { Thread . sleep ( timeInMillis ) ; } catch ( InterruptedException e ) { } int attempt = 0 ; while ( session == null || session . getSessionState ( ) . equals ( SessionState . CLOSED ) ) { try { LOGGER . info ( "Reconnecting attempt #{} ..." , ++ attempt ) ; session = newSession ( ) ; } catch ( IOException e ) { LOGGER . error ( "Failed opening connection and bind to " + remoteIpAddress + ":" + remotePort , e ) ; try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException ee ) { } } } } } . start ( ) ; }
Reconnect session after specified interval .
154
public void accept ( String systemId , InterfaceVersion interfaceVersion ) throws PDUStringException , IllegalStateException , IOException { StringValidator . validateString ( systemId , StringParameter . SYSTEM_ID ) ; lock . lock ( ) ; try { if ( ! done ) { done = true ; try { responseHandler . sendBindResp ( systemId , interfaceVersion , bindType , originalSequenceNumber ) ; } finally { condition . signal ( ) ; } } else { throw new IllegalStateException ( "Response already initiated" ) ; } } finally { lock . unlock ( ) ; } done = true ; }
Accept the bind request . The provided interface version will be put into the optional parameter sc_interface_version in the bind response message .
155
public void reject ( int errorCode ) throws IllegalStateException , IOException { lock . lock ( ) ; try { if ( done ) { throw new IllegalStateException ( "Response already initiated" ) ; } else { done = true ; try { responseHandler . sendNegativeResponse ( bindType . commandId ( ) , errorCode , originalSequenceNumber ) ; } finally { condition . signal ( ) ; } } } finally { lock . unlock ( ) ; } }
Reject the bind request .
156
public void done ( T response ) throws IllegalArgumentException { lock . lock ( ) ; try { if ( response != null ) { this . response = response ; condition . signal ( ) ; } else { throw new IllegalArgumentException ( "response cannot be null" ) ; } } finally { lock . unlock ( ) ; } }
Done with valid response and notify that response already received .
157
public void waitDone ( ) throws ResponseTimeoutException , InvalidResponseException { lock . lock ( ) ; try { if ( ! isDoneResponse ( ) ) { try { condition . await ( timeout , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new RuntimeException ( "Interrupted" ) ; } } if ( illegalResponseException != null ) { throw illegalResponseException ; } if ( ! isDoneResponse ( ) ) { throw new ResponseTimeoutException ( "No response after " + timeout + " millis" ) ; } } finally { lock . unlock ( ) ; } }
Wait until response received or timeout already reached .
158
public byte [ ] serialize ( ) { byte [ ] value = serializeValue ( ) ; ByteBuffer buffer = ByteBuffer . allocate ( value . length + 4 ) ; buffer . putShort ( tag ) ; buffer . putShort ( ( short ) value . length ) ; buffer . put ( value ) ; return buffer . array ( ) ; }
Convert the optional parameter into a byte serialized form conforming to the SMPP specification .
159
public BindRequest connectAndOutbind ( String host , int port , String systemId , String password ) throws IOException { return connectAndOutbind ( host , port , new OutbindParameter ( systemId , password ) , 60000 ) ; }
Open connection and outbind immediately . The default timeout is 60 seconds .
160
public BindRequest connectAndOutbind ( String host , int port , OutbindParameter outbindParameter , long timeout ) throws IOException { logger . debug ( "Connect and bind to {} port {}" , host , port ) ; if ( getSessionState ( ) != SessionState . CLOSED ) { throw new IOException ( "Session state is not closed" ) ; } conn = connFactory . createConnection ( host , port ) ; logger . info ( "Connected to {}" , conn . getInetAddress ( ) ) ; conn . setSoTimeout ( getEnquireLinkTimer ( ) ) ; sessionContext . open ( ) ; try { in = new DataInputStream ( conn . getInputStream ( ) ) ; out = conn . getOutputStream ( ) ; pduReaderWorker = new PDUReaderWorker ( ) ; pduReaderWorker . start ( ) ; sendOutbind ( outbindParameter . getSystemId ( ) , outbindParameter . getPassword ( ) ) ; } catch ( IOException e ) { logger . error ( "IO error occurred" , e ) ; close ( ) ; throw e ; } try { BindRequest bindRequest = waitForBind ( timeout ) ; logger . info ( "Start enquireLinkSender" ) ; enquireLinkSender = new EnquireLinkSender ( ) ; enquireLinkSender . start ( ) ; return bindRequest ; } catch ( IllegalStateException e ) { String message = "System error" ; logger . error ( message , e ) ; close ( ) ; throw new IOException ( message + ": " + e . getMessage ( ) , e ) ; } catch ( TimeoutException e ) { String message = "Waiting bind response take time too long" ; logger . error ( message , e ) ; throw new IOException ( message + ": " + e . getMessage ( ) , e ) ; } }
Open connection and outbind immediately .
161
private BindRequest waitForBind ( long timeout ) throws IllegalStateException , TimeoutException { SessionState currentSessionState = getSessionState ( ) ; if ( currentSessionState . equals ( SessionState . OPEN ) ) { try { return bindRequestReceiver . waitForRequest ( timeout ) ; } catch ( IllegalStateException e ) { throw new IllegalStateException ( "Invocation of waitForBind() has been made" , e ) ; } catch ( TimeoutException e ) { close ( ) ; throw e ; } } else { throw new IllegalStateException ( "waitForBind() should be invoked on OPEN state, actual state is " + currentSessionState ) ; } }
Wait for bind request .
162
public static int bytesToInt ( byte [ ] bytes , int offset ) { int result = 0x00000000 ; int length ; if ( bytes . length - offset < 4 ) length = bytes . length - offset ; else length = 4 ; int end = offset + length ; for ( int i = 0 ; i < length ; i ++ ) { result |= ( bytes [ end - i - 1 ] & 0xff ) << ( 8 * i ) ; } return result ; }
32 bit .
163
public static short bytesToShort ( byte [ ] bytes , int offset ) { short result = 0x0000 ; int end = offset + 2 ; for ( int i = 0 ; i < 2 ; i ++ ) { result |= ( bytes [ end - i - 1 ] & 0xff ) << ( 8 * i ) ; } return result ; }
16 bit .
164
OutbindRequest waitForRequest ( long timeout ) throws IllegalStateException , TimeoutException { this . lock . lock ( ) ; try { if ( this . alreadyWaitForRequest ) { throw new IllegalStateException ( "waitForRequest(long) method already invoked" ) ; } else if ( this . request == null ) { try { this . requestCondition . await ( timeout , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new RuntimeException ( "waitForRequest was interrupted" ) ; } } if ( this . request != null ) { return this . request ; } else { throw new TimeoutException ( "Waiting for outbind request take time too long" ) ; } } finally { this . alreadyWaitForRequest = true ; this . lock . unlock ( ) ; } }
Wait until the outbind request received for specified timeout .
165
void notifyAcceptOutbind ( Outbind outbind ) throws IllegalStateException { this . lock . lock ( ) ; try { if ( this . request == null ) { this . request = new OutbindRequest ( outbind ) ; this . requestCondition . signal ( ) ; } else { throw new IllegalStateException ( "Already waiting for acceptance outbind" ) ; } } finally { this . lock . unlock ( ) ; } }
Notify that the outbind was accepted .
166
public void setPduProcessorDegree ( int pduProcessorDegree ) throws IllegalStateException { if ( ! getSessionState ( ) . equals ( SessionState . CLOSED ) ) { throw new IllegalStateException ( "Cannot set PDU processor degree since the PDU dispatcher thread already created" ) ; } this . pduProcessorDegree = pduProcessorDegree ; }
Set total thread can read PDU and process it in parallel . It s defaulted to 3 .
167
protected void ensureReceivable ( String activityName ) throws IOException { SessionState currentState = getSessionState ( ) ; if ( ! currentState . isReceivable ( ) ) { throw new IOException ( "Cannot " + activityName + " while session " + sessionId + " in state " + currentState ) ; } }
Ensure the session is receivable . If the session not receivable then an exception thrown .
168
protected void ensureTransmittable ( String activityName , boolean only ) throws IOException { SessionState currentState = getSessionState ( ) ; if ( ! currentState . isTransmittable ( ) || ( only && currentState . isReceivable ( ) ) ) { throw new IOException ( "Cannot " + activityName + " while session " + sessionId + " in state " + currentState ) ; } }
Ensure the session is transmittable . If the session not transmittable then an exception thrown .
169
void notifyAcceptBind ( Bind bindParameter ) throws IllegalStateException { lock . lock ( ) ; try { if ( request == null ) { request = new BindRequest ( bindParameter , responseHandler ) ; requestCondition . signal ( ) ; } else { throw new IllegalStateException ( "Already waiting for acceptance bind" ) ; } } finally { lock . unlock ( ) ; } }
Notify that the bind has accepted .
170
static boolean isCOctetStringValid ( String value , int maxLength ) { if ( value == null ) return true ; if ( value . length ( ) >= maxLength ) return false ; return true ; }
Validate the C - Octet String .
171
static boolean isCOctetStringNullOrNValValid ( String value , int length ) { if ( value == null ) { return true ; } if ( value . length ( ) == 0 ) { return true ; } if ( value . length ( ) == length - 1 ) { return true ; } return false ; }
Validate the C - Octet String
172
static boolean isOctetStringValid ( String value , int maxLength ) { if ( value == null ) return true ; if ( value . length ( ) > maxLength ) return false ; return true ; }
Validate the Octet String
173
public String format ( Calendar calendar , Calendar smscCalendar ) { if ( calendar == null || smscCalendar == null ) { return null ; } long diffTimeInMillis = calendar . getTimeInMillis ( ) - smscCalendar . getTimeInMillis ( ) ; if ( diffTimeInMillis < 0 ) { throw new IllegalArgumentException ( "The requested relative time has already past." ) ; } Calendar offsetEpoch = Calendar . getInstance ( utcTimeZone ) ; offsetEpoch . setTimeInMillis ( diffTimeInMillis ) ; int years = offsetEpoch . get ( Calendar . YEAR ) - 1970 ; int months = offsetEpoch . get ( Calendar . MONTH ) ; int days = offsetEpoch . get ( Calendar . DAY_OF_MONTH ) - 1 ; int hours = offsetEpoch . get ( Calendar . HOUR_OF_DAY ) ; int minutes = offsetEpoch . get ( Calendar . MINUTE ) ; int seconds = offsetEpoch . get ( Calendar . SECOND ) ; if ( years >= 100 ) { throw new IllegalArgumentException ( "The requested relative time is more then a century (" + years + " years)." ) ; } return format ( years , months , days , hours , minutes , seconds ) ; }
Return the relative time from the calendar datetime against the SMSC datetime .
174
public int append ( byte [ ] b , int offset , int length ) { int oldLength = bytesLength ; bytesLength += length ; int newCapacity = capacityPolicy . ensureCapacity ( bytesLength , bytes . length ) ; if ( newCapacity > bytes . length ) { byte [ ] newB = new byte [ newCapacity ] ; System . arraycopy ( bytes , 0 , newB , 0 , bytes . length ) ; bytes = newB ; } System . arraycopy ( b , offset , bytes , oldLength , length ) ; normalizeCommandLength ( ) ; return bytesLength ; }
Append bytes to specified offset and length .
175
public int appendAll ( OptionalParameter [ ] optionalParameters ) { int length = 0 ; for ( OptionalParameter optionalParamameter : optionalParameters ) { length += append ( optionalParamameter ) ; } return length ; }
Append all optional parameters .
176
public void setSourceArchiveUrls ( List < String > sourceArchiveUrls ) { if ( sourceArchiveUrls == null ) throw new IllegalArgumentException ( ) ; this . sourceArchiveUrls = new ArrayList < String > ( sourceArchiveUrls ) ; }
Sets the list of source archive URLs . The source archives must be ZIP compressed archives containing COPPER workflows as . java files .
177
public void setCompilerOptionsProviders ( List < CompilerOptionsProvider > compilerOptionsProviders ) { if ( compilerOptionsProviders == null ) throw new NullPointerException ( ) ; this . compilerOptionsProviders = new ArrayList < CompilerOptionsProvider > ( compilerOptionsProviders ) ; }
Sets the list of CompilerOptionsProviders . They are called before compiling the workflow files to append compiler options .
178
private void doHousekeeping ( ) { logger . info ( "started" ) ; while ( ! shutdown ) { try { List < EarlyResponse > removedEarlyResponses = new ArrayList < > ( ) ; synchronized ( responseMap ) { Iterator < List < EarlyResponse > > responseMapIterator = responseMap . values ( ) . iterator ( ) ; while ( responseMapIterator . hasNext ( ) ) { List < EarlyResponse > erList = responseMapIterator . next ( ) ; Iterator < EarlyResponse > erListIterator = erList . iterator ( ) ; while ( erListIterator . hasNext ( ) ) { EarlyResponse earlyResponse = erListIterator . next ( ) ; if ( earlyResponse . ts < System . currentTimeMillis ( ) ) { responseMapIterator . remove ( ) ; removedEarlyResponses . add ( earlyResponse ) ; } } if ( erList . isEmpty ( ) ) { responseMapIterator . remove ( ) ; } } } for ( EarlyResponse er : removedEarlyResponses ) { logger . info ( "Removed early response with correlationId {} and responseId {}" , er . response . getCorrelationId ( ) , er . response . getResponseId ( ) ) ; } removedEarlyResponses = null ; Thread . sleep ( checkInterval ) ; } catch ( InterruptedException e ) { } } logger . info ( "stopped" ) ; }
Jetzt gibt es eine Map von Listen und man muss immer alles komplett Ueberpruefen - ggf . optimieren
179
public void asynchLog ( final AuditTrailEvent e , final AuditTrailCallback cb ) { CommandCallback < BatchInsertIntoAutoTrail . Command > callback = new CommandCallback < BatchInsertIntoAutoTrail . Command > ( ) { public void commandCompleted ( ) { cb . done ( ) ; } public void unhandledException ( Exception e ) { cb . error ( e ) ; } } ; doLog ( e , false , callback ) ; }
returns immediately after queueing the log message
180
public static void closeConnection ( Connection con ) { if ( con != null ) { try { con . close ( ) ; } catch ( SQLException ex ) { logger . debug ( "Could not close JDBC Connection" , ex ) ; } catch ( Throwable ex ) { logger . debug ( "Unexpected exception on closing JDBC Connection" , ex ) ; } } }
Close the given JDBC Connection and ignore any thrown exception . This is useful for typical finally blocks in manual JDBC code .
181
public synchronized void release ( int count ) { used -= count ; if ( used < 0 ) used = 0 ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "Released " + count + " tickets! (Now " + this . toString ( ) + ")" ) ; notifyAll ( ) ; }
Releases the given number of tickets and notifies potentially waiting threads that new tickets are in the pool .
182
public String obtainAndReturnTicketPoolId ( Workflow < ? > wf ) { TicketPool tp = findPool ( wf . getClass ( ) . getName ( ) ) ; tp . obtain ( ) ; return tp . getId ( ) ; }
For testing ..
183
protected String classnameReplacement ( String classname ) { if ( classname . startsWith ( COPPER_2X_PACKAGE_PREFIX ) ) { String className3x = classname . replace ( COPPER_2X_PACKAGE_PREFIX , COPPER_3_PACKAGE_PREFIX ) ; if ( ( COPPER_3_PACKAGE_PREFIX + COPPER_2X_INTERRUPT_NAME ) . equals ( className3x ) ) { return COPPER_3_PACKAGE_PREFIX + COPPER_3_INTERRUPT_NAME ; } return className3x ; } return classname ; }
For downward compatibility there is a package name replacement during deserialization of workflow instances and responses . The default implementation ensures downward compatibility to copper &lt ; = 2 . x .
184
public void addCurrentEntity ( Object entity ) { Object identifier = identifier ( entity ) ; Object o = memento . get ( identifier ) ; if ( o == null ) { inserted . add ( entity ) ; } else { potentiallyChanged . put ( identifier , entity ) ; } }
Use this entity as the new
185
public void putResponse ( Response < ? > r ) { synchronized ( responseMap ) { List < Response < ? > > l = responseMap . get ( r . getCorrelationId ( ) ) ; if ( l == null ) { l = new SortedResponseList ( ) ; responseMap . put ( r . getCorrelationId ( ) , l ) ; } l . add ( r ) ; } }
Internal use only - called by the processing engine
186
protected final void resubmit ( ) throws Interrupt { final String cid = engine . createUUID ( ) ; engine . registerCallbacks ( this , WaitMode . ALL , 0 , cid ) ; Acknowledge ack = createCheckpointAcknowledge ( ) ; engine . notify ( new Response < Object > ( cid , null , null ) , ack ) ; registerCheckpointAcknowledge ( ack ) ; updateLastWaitStackTrace ( ) ; }
Causes the engine to stop processing of this workflow instance and to enqueue it again . May be used in case of processor pool change or to create a savepoint .
187
public int countWorkflowInstances ( WorkflowInstanceFilter filter ) throws Exception { final StringBuilder query = new StringBuilder ( ) ; final List < Object > values = new ArrayList < > ( ) ; query . append ( "SELECT COUNT(*) AS COUNT_NUMBER FROM COP_WORKFLOW_INSTANCE" ) ; appendQueryBase ( query , values , filter ) ; query . append ( " ALLOW FILTERING" ) ; final String cqlQuery = query . toString ( ) ; logger . info ( "queryWorkflowInstances - cqlQuery = {}" , cqlQuery ) ; final ResultSet resultSet = session . execute ( cqlQuery , values . toArray ( ) ) ; Row row ; while ( ( row = resultSet . one ( ) ) != null ) { return row . getInt ( "COUNT_NUMBER" ) ; } throw new SQLException ( "Failed to get result of CQL request for counting workflow instances" ) ; }
Probably it s gonna be slow . We can consider creating counting table for that sake .
188
private String getAuthHash ( WebContext ctx ) { Value authorizationHeaderValue = ctx . getHeaderValue ( HttpHeaderNames . AUTHORIZATION ) ; if ( ! authorizationHeaderValue . isFilled ( ) ) { return ctx . get ( "Signature" ) . asString ( ctx . get ( "X-Amz-Signature" ) . asString ( ) ) ; } String authentication = Strings . isEmpty ( authorizationHeaderValue . getString ( ) ) ? "" : authorizationHeaderValue . getString ( ) ; Matcher m = AWS_AUTH_PATTERN . matcher ( authentication ) ; if ( m . matches ( ) ) { return m . group ( 2 ) ; } m = AWS_AUTH4_PATTERN . matcher ( authentication ) ; if ( m . matches ( ) ) { return m . group ( 7 ) ; } return null ; }
Extracts the given hash from the given request . Returns null if no hash was given .
189
private void signalObjectError ( WebContext ctx , HttpResponseStatus status , String message ) { if ( ctx . getRequest ( ) . method ( ) == HEAD ) { ctx . respondWith ( ) . status ( status ) ; } else { ctx . respondWith ( ) . error ( status , message ) ; } log . log ( ctx . getRequest ( ) . method ( ) . name ( ) , message + " - " + ctx . getRequestedURI ( ) , APILog . Result . ERROR , CallContext . getCurrent ( ) . getWatch ( ) ) ; }
Writes an API error to the log
190
private void signalObjectSuccess ( WebContext ctx ) { log . log ( ctx . getRequest ( ) . method ( ) . name ( ) , ctx . getRequestedURI ( ) , APILog . Result . OK , CallContext . getCurrent ( ) . getWatch ( ) ) ; }
Writes an API success entry to the log
191
private void listBuckets ( WebContext ctx ) { HttpMethod method = ctx . getRequest ( ) . method ( ) ; if ( GET == method ) { List < Bucket > buckets = storage . getBuckets ( ) ; Response response = ctx . respondWith ( ) ; response . setHeader ( HTTP_HEADER_NAME_CONTENT_TYPE , CONTENT_TYPE_XML ) ; XMLStructuredOutput out = response . xml ( ) ; out . beginOutput ( "ListAllMyBucketsResult" , Attribute . set ( "xmlns" , "http://s3.amazonaws.com/doc/2006-03-01/" ) ) ; out . property ( "hint" , "Goto: " + ctx . getBaseURL ( ) + "/ui to visit the admin UI" ) ; outputOwnerInfo ( out , "Owner" ) ; out . beginObject ( "Buckets" ) ; for ( Bucket bucket : buckets ) { out . beginObject ( RESPONSE_BUCKET ) ; out . property ( "Name" , bucket . getName ( ) ) ; out . property ( "CreationDate" , RFC822_INSTANT . format ( Instant . ofEpochMilli ( bucket . getFile ( ) . lastModified ( ) ) ) ) ; out . endObject ( ) ; } out . endObject ( ) ; out . endOutput ( ) ; } else { throw new IllegalArgumentException ( ctx . getRequest ( ) . method ( ) . name ( ) ) ; } }
GET a list of all buckets
192
private void readObject ( WebContext ctx , String bucketName , String objectId ) throws IOException { Bucket bucket = storage . getBucket ( bucketName ) ; String id = objectId . replace ( '/' , '_' ) ; String uploadId = ctx . get ( "uploadId" ) . asString ( ) ; if ( ! checkObjectRequest ( ctx , bucket , id ) ) { return ; } HttpMethod method = ctx . getRequest ( ) . method ( ) ; if ( HEAD == method ) { getObject ( ctx , bucket , id , false ) ; } else if ( GET == method ) { if ( Strings . isFilled ( uploadId ) ) { getPartList ( ctx , bucket , id , uploadId ) ; } else { getObject ( ctx , bucket , id , true ) ; } } else if ( DELETE == method ) { if ( Strings . isFilled ( uploadId ) ) { abortMultipartUpload ( ctx , uploadId ) ; } else { deleteObject ( ctx , bucket , id ) ; } } else { throw new IllegalArgumentException ( ctx . getRequest ( ) . method ( ) . name ( ) ) ; } }
Dispatching method handling all object specific calls which either read or delete the object but do not provide any data .
193
public boolean supports ( final WebContext ctx ) { return AWS_AUTH4_PATTERN . matcher ( ctx . getHeaderValue ( "Authorization" ) . asString ( "" ) ) . matches ( ) || X_AMZ_CREDENTIAL_PATTERN . matcher ( ctx . get ( "X-Amz-Credential" ) . asString ( "" ) ) . matches ( ) ; }
Determines if the given request contains an AWS4 auth token .
194
public String getBasePath ( ) { StringBuilder sb = new StringBuilder ( getBaseDirUnchecked ( ) . getAbsolutePath ( ) ) ; if ( ! getBaseDirUnchecked ( ) . exists ( ) ) { sb . append ( " (non-existent!)" ) ; } else if ( ! getBaseDirUnchecked ( ) . isDirectory ( ) ) { sb . append ( " (no directory!)" ) ; } else { sb . append ( " (Free: " ) . append ( NLS . formatSize ( getBaseDir ( ) . getFreeSpace ( ) ) ) . append ( ")" ) ; } return sb . toString ( ) ; }
Returns the base directory as string .
195
public List < Bucket > getBuckets ( ) { List < Bucket > result = Lists . newArrayList ( ) ; for ( File file : getBaseDir ( ) . listFiles ( ) ) { if ( file . isDirectory ( ) ) { result . add ( new Bucket ( file ) ) ; } } return result ; }
Enumerates all known buckets .
196
public Bucket getBucket ( String bucket ) { if ( bucket . contains ( ".." ) || bucket . contains ( "/" ) || bucket . contains ( "\\" ) ) { throw Exceptions . createHandled ( ) . withSystemErrorMessage ( "Invalid bucket name: %s. A bucket name must not contain '..' '/' or '\\'" , bucket ) . handle ( ) ; } return new Bucket ( new File ( getBaseDir ( ) , bucket ) ) ; }
Returns a bucket with the given name
197
public void delete ( ) { if ( ! file . delete ( ) ) { Storage . LOG . WARN ( "Failed to delete data file for object %s (%s)." , getName ( ) , file . getAbsolutePath ( ) ) ; } if ( ! getPropertiesFile ( ) . delete ( ) ) { Storage . LOG . WARN ( "Failed to delete properties file for object %s (%s)." , getName ( ) , getPropertiesFile ( ) . getAbsolutePath ( ) ) ; } }
Deletes the object
198
public void storeProperties ( Map < String , String > properties ) throws IOException { Properties props = new Properties ( ) ; properties . forEach ( props :: setProperty ) ; try ( FileOutputStream out = new FileOutputStream ( getPropertiesFile ( ) ) ) { props . store ( out , "" ) ; } }
Stores the given meta infos for the stored object .
199
public boolean delete ( ) { boolean deleted = false ; for ( File child : file . listFiles ( ) ) { deleted = child . delete ( ) || deleted ; } deleted = file . delete ( ) || deleted ; return deleted ; }
Deletes the bucket and all of its contents .