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 . getBool...
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:{}, cu...
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 . ad...
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 ( ) ; cre...
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 ...
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 ) { hasRe...
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 ) ; St...
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 , str...
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...
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...
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 Realloc...
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 ( PluginScenarioExceptio...
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 . getAbsolu...
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 ; } retur...
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 { install...
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....
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 . getV...
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 ( newF...
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 . g...
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 ( ) ; i...
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...
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 ( "err...
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 ( "Num...
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 = stripVersio...
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" ) ; ...
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" ) ;...
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 ( ) ; } retur...
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 , NegativeRespo...
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 outbindRequestRece...
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...
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 . ap...
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 byt...
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 ...
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 ye...
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 (...
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...
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 )...
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 ( "Inte...
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" ) ; } co...
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 ) { ...
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 ) ; } re...
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 ....
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" ) ; } } ...
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 = pduProcessor...
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 +...
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 { ...
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 ...
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 ,...
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 ( responseMapIterat...
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 . ...
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 COPP...
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 (...
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 ) ...
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 = String...
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 ( ) , messa...
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 ou...
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...
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 . app...
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 Buc...
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 ( ) , getPr...
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 .