idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
17,600
public static String getRelativePath ( File file , File srcDir ) { String base = srcDir . getPath ( ) ; String filePath = file . getPath ( ) ; String relativePath = new File ( base ) . toURI ( ) . relativize ( new File ( filePath ) . toURI ( ) ) . getPath ( ) ; return relativePath ; }
Returns the relative path .
17,601
public static void copyFile ( File srcFile , File destFile ) { OutputStream out = null ; InputStream in = null ; try { if ( ! destFile . getParentFile ( ) . exists ( ) ) destFile . getParentFile ( ) . mkdirs ( ) ; in = new FileInputStream ( srcFile ) ; out = new FileOutputStream ( destFile ) ; byte [ ] buf = new byte [ 1024 ] ; int len ; while ( ( len = in . read ( buf ) ) > 0 ) { out . write ( buf , 0 , len ) ; } in . close ( ) ; out . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Copy a file to new destination .
17,602
public static ContextLoaderListener createSpringContextLoader ( final WebApplicationContext webApplicationContext ) { return new ContextLoaderListener ( ) { @ SuppressWarnings ( "unchecked" ) protected WebApplicationContext createWebApplicationContext ( ServletContext sc ) { return webApplicationContext ; } } ; }
Creates a spring context loader listener
17,603
public static JsonNode getFieldValue ( JsonNode doc , String field ) { StringTokenizer tkz = new StringTokenizer ( field , ". " ) ; JsonNode trc = doc ; while ( tkz . hasMoreTokens ( ) && trc != null ) { String tok = tkz . nextToken ( ) ; trc = trc . get ( tok ) ; } return trc ; }
Ooes not do array index lookup!
17,604
public OPhysicalPosition getPhysicalPosition ( final OPhysicalPosition iPPosition ) throws IOException { final long filePosition = iPPosition . clusterPosition * RECORD_SIZE ; acquireSharedLock ( ) ; try { final long [ ] pos = fileSegment . getRelativePosition ( filePosition ) ; final OFile f = fileSegment . files [ ( int ) pos [ 0 ] ] ; long p = pos [ 1 ] ; iPPosition . dataSegmentId = f . readShort ( p ) ; iPPosition . dataSegmentPos = f . readLong ( p += OBinaryProtocol . SIZE_SHORT ) ; iPPosition . recordType = f . readByte ( p += OBinaryProtocol . SIZE_LONG ) ; iPPosition . recordVersion = f . readInt ( p += OBinaryProtocol . SIZE_BYTE ) ; return iPPosition ; } finally { releaseSharedLock ( ) ; } }
Fills and return the PhysicalPosition object received as parameter with the physical position of logical record iPosition
17,605
public void removePhysicalPosition ( final long iPosition ) throws IOException { final long position = iPosition * RECORD_SIZE ; acquireExclusiveLock ( ) ; try { final long [ ] pos = fileSegment . getRelativePosition ( position ) ; final OFile file = fileSegment . files [ ( int ) pos [ 0 ] ] ; final long p = pos [ 1 ] + OBinaryProtocol . SIZE_SHORT + OBinaryProtocol . SIZE_LONG + OBinaryProtocol . SIZE_BYTE ; holeSegment . pushPosition ( position ) ; final int version = file . readInt ( p ) ; file . writeInt ( p , ( version + 1 ) * - 1 ) ; updateBoundsAfterDeletion ( iPosition ) ; } finally { releaseExclusiveLock ( ) ; } }
Removes the Logical position entry . Add to the hole segment and add the minus to the version .
17,606
public void addPhysicalPosition ( final OPhysicalPosition iPPosition ) throws IOException { final long [ ] pos ; final boolean recycled ; long offset ; acquireExclusiveLock ( ) ; try { offset = holeSegment . popLastEntryPosition ( ) ; if ( offset > - 1 ) { pos = fileSegment . getRelativePosition ( offset ) ; recycled = true ; } else { pos = allocateRecord ( ) ; offset = fileSegment . getAbsolutePosition ( pos ) ; recycled = false ; } final OFile file = fileSegment . files [ ( int ) pos [ 0 ] ] ; long p = pos [ 1 ] ; file . writeShort ( p , ( short ) iPPosition . dataSegmentId ) ; file . writeLong ( p += OBinaryProtocol . SIZE_SHORT , iPPosition . dataSegmentPos ) ; file . writeByte ( p += OBinaryProtocol . SIZE_LONG , iPPosition . recordType ) ; if ( recycled ) iPPosition . recordVersion = file . readInt ( p + OBinaryProtocol . SIZE_BYTE ) * - 1 ; else iPPosition . recordVersion = 0 ; file . writeInt ( p + OBinaryProtocol . SIZE_BYTE , iPPosition . recordVersion ) ; iPPosition . clusterPosition = offset / RECORD_SIZE ; updateBoundsAfterInsertion ( iPPosition . clusterPosition ) ; } finally { releaseExclusiveLock ( ) ; } }
Adds a new entry .
17,607
private void setDataSegmentInternal ( final String iName ) { final int dataId = storage . getDataSegmentIdByName ( iName ) ; config . setDataSegmentId ( dataId ) ; storage . getConfiguration ( ) . update ( ) ; }
Assigns a different data - segment id .
17,608
protected Object getCustomEventLoggerFromRegistry ( MuleContext muleContext ) { Object obj = muleContext . getRegistry ( ) . lookupObject ( CUSTOM_EVENT_LOGGER_BEAN_NAME ) ; return obj ; }
open up for testing without a live MuleContext
17,609
public void addIndex ( final OIndexDefinition indexDefinition ) { indexDefinitions . add ( indexDefinition ) ; if ( indexDefinition instanceof OIndexDefinitionMultiValue ) { if ( multiValueDefinitionIndex == - 1 ) multiValueDefinitionIndex = indexDefinitions . size ( ) - 1 ; else throw new OIndexException ( "Composite key can not contain more than one collection item" ) ; } }
Add new indexDefinition in current composite .
17,610
public OIdentifiableIterator < REC > setReuseSameRecord ( final boolean reuseSameRecord ) { reusedRecord = ( ORecordInternal < ? > ) ( reuseSameRecord ? database . newInstance ( ) : null ) ; return this ; }
Tell to the iterator to use the same record for browsing . The record will be reset before every use . This improve the performance and reduce memory utilization since it does not create a new one for each operation but pay attention to copy the data of the record once read otherwise they will be reset to the next operation .
17,611
protected ORecordInternal < ? > getRecord ( ) { final ORecordInternal < ? > record ; if ( reusedRecord != null ) { record = reusedRecord ; record . reset ( ) ; } else record = null ; return record ; }
Return the record to use for the operation .
17,612
protected ORecordInternal < ? > readCurrentRecord ( ORecordInternal < ? > iRecord , final int iMovement ) { if ( limit > - 1 && browsedRecords >= limit ) return null ; current . clusterPosition += iMovement ; if ( iRecord != null ) { iRecord . setIdentity ( current ) ; iRecord = lowLevelDatabase . load ( iRecord , fetchPlan ) ; } else iRecord = lowLevelDatabase . load ( current , fetchPlan ) ; if ( iRecord != null ) browsedRecords ++ ; return iRecord ; }
Read the current record and increment the counter if the record was found .
17,613
public void bindParameters ( final Map < Object , Object > iArgs ) { if ( parameterItems == null || iArgs == null || iArgs . size ( ) == 0 ) return ; for ( Entry < Object , Object > entry : iArgs . entrySet ( ) ) { if ( entry . getKey ( ) instanceof Integer ) parameterItems . get ( ( ( Integer ) entry . getKey ( ) ) ) . setValue ( entry . setValue ( entry . getValue ( ) ) ) ; else { String paramName = entry . getKey ( ) . toString ( ) ; for ( OSQLFilterItemParameter value : parameterItems ) { if ( value . getName ( ) . equalsIgnoreCase ( paramName ) ) { value . setValue ( entry . getValue ( ) ) ; break ; } } } } }
Binds parameters .
17,614
public boolean send ( Context context , Report report ) { if ( url != null ) { String reportStr = report . asJSON ( ) . toString ( ) ; try { postReport ( url , reportStr ) ; return true ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return false ; }
If the reporter was configured correctly post the report to the set URL .
17,615
public static void post ( URL url , String params ) throws IOException { URLConnection conn = url . openConnection ( ) ; if ( conn instanceof HttpURLConnection ) { ( ( HttpURLConnection ) conn ) . setRequestMethod ( "POST" ) ; conn . setRequestProperty ( "Content-Type" , "application/json" ) ; } OutputStreamWriter writer = null ; try { conn . setDoOutput ( true ) ; writer = new OutputStreamWriter ( conn . getOutputStream ( ) , Charset . forName ( "UTF-8" ) ) ; writer . write ( params ) ; writer . flush ( ) ; } finally { if ( writer != null ) { writer . close ( ) ; } } }
Executes the given request as a HTTP POST action .
17,616
public static String read ( InputStream in ) throws IOException { InputStreamReader isReader = new InputStreamReader ( in , "UTF-8" ) ; BufferedReader reader = new BufferedReader ( isReader ) ; StringBuffer out = new StringBuffer ( ) ; char [ ] c = new char [ 4096 ] ; for ( int n ; ( n = reader . read ( c ) ) != - 1 ; ) { out . append ( new String ( c , 0 , n ) ) ; } reader . close ( ) ; return out . toString ( ) ; }
Reads an input stream and returns the result as a String .
17,617
public Object joinGame ( long id , String password ) { return client . sendRpcAndWait ( SERVICE , "joinGame" , id , password ) ; }
Join a password - protected game .
17,618
public Object observeGame ( long id , String password ) { return client . sendRpcAndWait ( SERVICE , "observeGame" , id , password ) ; }
Join a password - protected game as a spectator
17,619
public boolean switchToPlayer ( long id , PlayerSide team ) { return client . sendRpcAndWait ( SERVICE , "switchObserverToPlayer" , id , team . id ) ; }
Switch from observer to player
17,620
protected byte [ ] serializeStreamValue ( final int iIndex ) throws IOException { if ( serializedValues [ iIndex ] <= 0 ) { OProfiler . getInstance ( ) . updateCounter ( "OMVRBTreeMapEntry.serializeValue" , 1 ) ; return ( ( OMVRBTreeMapProvider < K , V > ) treeDataProvider ) . valueSerializer . toStream ( values [ iIndex ] ) ; } return stream . getAsByteArray ( serializedValues [ iIndex ] ) ; }
Serialize only the new values or the changed .
17,621
public MigrationJob [ ] retrieveJobs ( int batchSize , int startIndex , JobType jobType ) throws IOException , LightblueException { LOGGER . debug ( "Retrieving jobs: batchSize={}, startIndex={}" , batchSize , startIndex ) ; DataFindRequest findRequest = new DataFindRequest ( "migrationJob" , null ) ; List < Query > conditions = new ArrayList < > ( Arrays . asList ( new Query [ ] { Query . withValue ( "configurationName" , Query . eq , migrationConfiguration . getConfigurationName ( ) ) , Query . withValue ( "status" , Query . eq , "available" ) , Query . withValue ( "scheduledDate" , Query . lte , new Date ( ) ) } ) ) ; if ( jobType == JobType . GENERATED ) { LOGGER . debug ( "Looking for generated job" ) ; conditions . add ( Query . withValue ( "generated" , Query . eq , true ) ) ; } else if ( jobType == JobType . NONGENERATED ) { LOGGER . debug ( "Looking for non generated job" ) ; conditions . add ( Query . withValue ( "generated" , Query . eq , false ) ) ; } findRequest . where ( Query . and ( conditions ) ) ; findRequest . select ( Projection . includeField ( "*" ) ) ; findRequest . range ( startIndex , startIndex + batchSize - 1 ) ; LOGGER . debug ( "Finding Jobs to execute: {}" , findRequest . getBody ( ) ) ; return lbClient . data ( findRequest , MigrationJob [ ] . class ) ; }
Retrieves jobs that are available and their scheduled time has passed . Returns at most batchSize jobs starting at startIndex
17,622
public ActiveExecution lock ( String id ) throws Exception { LOGGER . debug ( "locking {}" , id ) ; if ( ! myLocks . contains ( id ) ) { if ( locking . acquire ( id , null ) ) { myLocks . add ( id ) ; ActiveExecution ae = new ActiveExecution ( ) ; ae . setMigrationJobId ( id ) ; ae . set_id ( id ) ; ae . setStartTime ( new Date ( ) ) ; return ae ; } } return null ; }
Attempts to lock a migration job . If successful return the migration job and the active execution
17,623
public < H extends EventHandler > H getHandler ( GwtEvent . Type < H > type , int index ) { return this . eventBus . superGetHandler ( type , index ) ; }
Gets the handler at the given index .
17,624
public < H extends EventHandler > void removeHandler ( GwtEvent . Type < H > type , final H handler ) { this . eventBus . superDoRemove ( type , null , handler ) ; }
Removes the given handler from the specified event type .
17,625
public void sendFailure ( String message ) { System . out . print ( "Warning: " + message ) ; System . exit ( 1 ) ; }
logs message with status code 1 - warn
17,626
public void sendError ( String message ) { System . out . print ( "Critical: " + message ) ; System . exit ( 2 ) ; }
logs message with status code 2 - critical
17,627
public Object execute ( final Map < Object , Object > iArgs ) { if ( className == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseRecord database = getDatabase ( ) ; if ( database . getMetadata ( ) . getSchema ( ) . existsClass ( className ) ) throw new OCommandExecutionException ( "Class " + className + " already exists" ) ; final OClassImpl sourceClass = ( OClassImpl ) ( ( OSchemaProxy ) database . getMetadata ( ) . getSchema ( ) ) . createClassInternal ( className , superClass , clusterIds ) ; sourceClass . saveInternal ( ) ; if ( superClass != null ) { int [ ] clustersToIndex = superClass . getPolymorphicClusterIds ( ) ; String [ ] clusterNames = new String [ clustersToIndex . length ] ; for ( int i = 0 ; i < clustersToIndex . length ; i ++ ) { clusterNames [ i ] = database . getClusterNameById ( clustersToIndex [ i ] ) ; } for ( OIndex < ? > index : superClass . getIndexes ( ) ) for ( String clusterName : clusterNames ) index . getInternal ( ) . addCluster ( clusterName ) ; } return database . getMetadata ( ) . getSchema ( ) . getClasses ( ) . size ( ) ; }
Execute the CREATE CLASS .
17,628
public boolean callbackHooks ( final TYPE iType , final OIdentifiable id ) { if ( ! OHookThreadLocal . INSTANCE . push ( id ) ) return false ; try { final ORecord < ? > rec = id . getRecord ( ) ; if ( rec == null ) return false ; boolean recordChanged = false ; for ( ORecordHook hook : hooks ) if ( hook . onTrigger ( iType , rec ) ) recordChanged = true ; return recordChanged ; } finally { OHookThreadLocal . INSTANCE . pop ( id ) ; } }
Callback the registeted hooks if any .
17,629
public String execute ( String url , String urlParameters , String clientId , String secret , String method ) throws Exception { HttpURLConnection connection ; String credentials = clientId + ":" + secret ; String authorizationHeader = "Basic " + Base64 . getEncoder ( ) . encodeToString ( credentials . getBytes ( ) ) ; if ( "POST" . equalsIgnoreCase ( method ) ) { connection = ( HttpURLConnection ) new URL ( url ) . openConnection ( ) ; connection . setRequestMethod ( method ) ; connection . setRequestProperty ( "Content-Type" , "application/x-www-form-urlencoded" ) ; connection . setRequestProperty ( "Authorization" , authorizationHeader ) ; connection . setDoInput ( true ) ; connection . setDoOutput ( true ) ; if ( null != urlParameters ) { try ( PrintWriter out = new PrintWriter ( connection . getOutputStream ( ) ) ) { out . print ( urlParameters ) ; } } } else { connection = ( HttpURLConnection ) new URL ( url + "?" + urlParameters ) . openConnection ( ) ; connection . setRequestMethod ( method ) ; connection . setRequestProperty ( "Authorization" , authorizationHeader ) ; } int timeout = Integer . parseInt ( System . getProperty ( "org.hawkular.accounts.http.timeout" , "5000" ) ) ; connection . setConnectTimeout ( timeout ) ; connection . setReadTimeout ( timeout ) ; StringBuilder response = new StringBuilder ( ) ; int statusCode ; try { statusCode = connection . getResponseCode ( ) ; } catch ( SocketTimeoutException timeoutException ) { throw new UsernamePasswordConversionException ( "Timed out when trying to contact the Keycloak server." ) ; } InputStream inputStream ; if ( statusCode < 300 ) { inputStream = connection . getInputStream ( ) ; } else { inputStream = connection . getErrorStream ( ) ; } try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream , "UTF-8" ) ) ) { for ( String line ; ( line = reader . readLine ( ) ) != null ; ) { response . append ( line ) ; } } return response . toString ( ) ; }
Performs an HTTP call to the Keycloak server returning the server s response as String .
17,630
private void buildReport ( Context context ) { try { buildBaseReport ( ) ; buildApplicationData ( context ) ; buildDeviceData ( context ) ; buildLog ( ) ; report . put ( "application" , app ) ; report . put ( "device" , device ) ; report . put ( "log" , logs ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } }
Creates the report as a JSON Object .
17,631
private void buildLog ( ) throws JSONException { logs = new JSONObject ( ) ; List < String > list = Log . getReportedEntries ( ) ; if ( list != null ) { logs . put ( "numberOfEntry" , list . size ( ) ) ; JSONArray array = new JSONArray ( ) ; for ( String s : list ) { array . put ( s ) ; } logs . put ( "log" , array ) ; } }
Adds the log entries to the report .
17,632
private void buildDeviceData ( Context context ) throws JSONException { device = new JSONObject ( ) ; device . put ( "device" , Build . DEVICE ) ; device . put ( "brand" , Build . BRAND ) ; Object windowService = context . getSystemService ( Context . WINDOW_SERVICE ) ; if ( windowService instanceof WindowManager ) { Display display = ( ( WindowManager ) windowService ) . getDefaultDisplay ( ) ; device . put ( "resolution" , display . getWidth ( ) + "x" + display . getHeight ( ) ) ; device . put ( "orientation" , display . getOrientation ( ) ) ; } device . put ( "display" , Build . DISPLAY ) ; device . put ( "manufacturer" , Build . MANUFACTURER ) ; device . put ( "model" , Build . MODEL ) ; device . put ( "product" , Build . PRODUCT ) ; device . put ( "build.type" , Build . TYPE ) ; device . put ( "android.version" , Build . VERSION . SDK_INT ) ; }
Adds the device data to the report .
17,633
private void buildApplicationData ( Context context ) throws JSONException { app = new JSONObject ( ) ; app . put ( "package" , context . getPackageName ( ) ) ; try { PackageInfo info = context . getPackageManager ( ) . getPackageInfo ( context . getPackageName ( ) , 0 ) ; app . put ( "versionCode" , info . versionCode ) ; app . put ( "versionName" , info . versionName ) ; } catch ( NameNotFoundException e ) { } }
Adds the application data to the report .
17,634
public Set < ODocument > getEdgesBetweenVertexes ( final ODocument iVertex1 , final ODocument iVertex2 ) { return getEdgesBetweenVertexes ( iVertex1 , iVertex2 , null , null ) ; }
Returns all the edges between the vertexes iVertex1 and iVertex2 .
17,635
public Set < ODocument > getEdgesBetweenVertexes ( final ODocument iVertex1 , final ODocument iVertex2 , final String [ ] iLabels ) { return getEdgesBetweenVertexes ( iVertex1 , iVertex2 , iLabels , null ) ; }
Returns all the edges between the vertexes iVertex1 and iVertex2 with label between the array of labels passed as iLabels .
17,636
public Set < ODocument > getEdgesBetweenVertexes ( final ODocument iVertex1 , final ODocument iVertex2 , final String [ ] iLabels , final String [ ] iClassNames ) { final Set < ODocument > result = new HashSet < ODocument > ( ) ; if ( iVertex1 != null && iVertex2 != null ) { for ( OIdentifiable e : getOutEdges ( iVertex1 ) ) { final ODocument edge = ( ODocument ) e ; if ( checkEdge ( edge , iLabels , iClassNames ) ) { if ( edge . < ODocument > field ( "in" ) . equals ( iVertex2 ) ) result . add ( edge ) ; } } for ( OIdentifiable e : getInEdges ( iVertex1 ) ) { final ODocument edge = ( ODocument ) e ; if ( checkEdge ( edge , iLabels , iClassNames ) ) { if ( edge . < ODocument > field ( "out" ) . equals ( iVertex2 ) ) result . add ( edge ) ; } } } return result ; }
Returns all the edges between the vertexes iVertex1 and iVertex2 with label between the array of labels passed as iLabels and with class between the array of class names passed as iClassNames .
17,637
public Set < OIdentifiable > getOutEdgesHavingProperties ( final OIdentifiable iVertex , Iterable < String > iProperties ) { final ODocument vertex = iVertex . getRecord ( ) ; checkVertexClass ( vertex ) ; return filterEdgesByProperties ( ( OMVRBTreeRIDSet ) vertex . field ( VERTEX_FIELD_OUT ) , iProperties ) ; }
Retrieves the outgoing edges of vertex iVertex having the requested properties iProperties
17,638
public Set < OIdentifiable > getInEdgesHavingProperties ( final OIdentifiable iVertex , Iterable < String > iProperties ) { final ODocument vertex = iVertex . getRecord ( ) ; checkVertexClass ( vertex ) ; return filterEdgesByProperties ( ( OMVRBTreeRIDSet ) vertex . field ( VERTEX_FIELD_IN ) , iProperties ) ; }
Retrieves the incoming edges of vertex iVertex having the requested properties iProperties
17,639
public Set < OIdentifiable > getInEdgesHavingProperties ( final ODocument iVertex , final Map < String , Object > iProperties ) { checkVertexClass ( iVertex ) ; return filterEdgesByProperties ( ( OMVRBTreeRIDSet ) iVertex . field ( VERTEX_FIELD_IN ) , iProperties ) ; }
Retrieves the incoming edges of vertex iVertex having the requested properties iProperties set to the passed values
17,640
public synchronized OServerAdmin connect ( final String iUserName , final String iUserPassword ) throws IOException { storage . createConnectionPool ( ) ; storage . setSessionId ( - 1 ) ; try { final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_CONNECT ) ; storage . sendClientInfo ( network ) ; try { network . writeString ( iUserName ) ; network . writeString ( iUserPassword ) ; } finally { storage . endRequest ( network ) ; } try { storage . beginResponse ( network ) ; sessionId = network . readInt ( ) ; storage . setSessionId ( sessionId ) ; } finally { storage . endResponse ( network ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Cannot connect to the remote server: " + storage . getName ( ) , e , OStorageException . class ) ; storage . close ( true ) ; } return this ; }
Connects to a remote server .
17,641
@ SuppressWarnings ( "unchecked" ) public synchronized Map < String , String > listDatabases ( ) throws IOException { storage . checkConnection ( ) ; final ODocument result = new ODocument ( ) ; try { final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_DB_LIST ) ; storage . endRequest ( network ) ; try { storage . beginResponse ( network ) ; result . fromStream ( network . readBytes ( ) ) ; } finally { storage . endResponse ( network ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . exception ( "Cannot retrieve the configuration list" , e , OStorageException . class ) ; storage . close ( true ) ; } return ( Map < String , String > ) result . field ( "databases" ) ; }
List the databases on a remote server .
17,642
public synchronized OServerAdmin createDatabase ( final String iDatabaseType , String iStorageMode ) throws IOException { storage . checkConnection ( ) ; try { if ( storage . getName ( ) == null || storage . getName ( ) . length ( ) <= 0 ) { OLogManager . instance ( ) . error ( this , "Cannot create unnamed remote storage. Check your syntax" , OStorageException . class ) ; } else { if ( iStorageMode == null ) iStorageMode = "csv" ; final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_DB_CREATE ) ; try { network . writeString ( storage . getName ( ) ) ; if ( network . getSrvProtocolVersion ( ) >= 8 ) network . writeString ( iDatabaseType ) ; network . writeString ( iStorageMode ) ; } finally { storage . endRequest ( network ) ; } storage . getResponse ( network ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Cannot create the remote storage: " + storage . getName ( ) , e , OStorageException . class ) ; storage . close ( true ) ; } return this ; }
Creates a database in a remote server .
17,643
public synchronized boolean existsDatabase ( ) throws IOException { storage . checkConnection ( ) ; try { final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_DB_EXIST ) ; try { network . writeString ( storage . getName ( ) ) ; } finally { storage . endRequest ( network ) ; } try { storage . beginResponse ( network ) ; return network . readByte ( ) == 1 ; } finally { storage . endResponse ( network ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . exception ( "Error on checking existence of the remote storage: " + storage . getName ( ) , e , OStorageException . class ) ; storage . close ( true ) ; } return false ; }
Checks if a database exists in the remote server .
17,644
public synchronized OServerAdmin dropDatabase ( ) throws IOException { storage . checkConnection ( ) ; boolean retry = true ; while ( retry ) try { final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_DB_DROP ) ; try { network . writeString ( storage . getName ( ) ) ; } finally { storage . endRequest ( network ) ; } storage . getResponse ( network ) ; retry = false ; } catch ( OModificationOperationProhibitedException oope ) { retry = handleDBFreeze ( ) ; } catch ( Exception e ) { OLogManager . instance ( ) . exception ( "Cannot delete the remote storage: " + storage . getName ( ) , e , OStorageException . class ) ; } for ( OStorage s : Orient . instance ( ) . getStorages ( ) ) { if ( s . getURL ( ) . startsWith ( getURL ( ) ) ) { s . removeResource ( OSchema . class . getSimpleName ( ) ) ; s . removeResource ( OIndexManager . class . getSimpleName ( ) ) ; s . removeResource ( OSecurity . class . getSimpleName ( ) ) ; } } ODatabaseRecordThreadLocal . INSTANCE . set ( null ) ; return this ; }
Drops a database from a remote server instance .
17,645
public ODocument clusterStatus ( ) { final ODocument response = sendRequest ( OChannelBinaryProtocol . REQUEST_CLUSTER , new ODocument ( ) . field ( "operation" , "status" ) , "Cluster status" ) ; OLogManager . instance ( ) . debug ( this , "Cluster status %s" , response . toJSON ( ) ) ; return response ; }
Gets the cluster status .
17,646
public synchronized OServerAdmin replicationStop ( final String iDatabaseName , final String iRemoteServer ) throws IOException { sendRequest ( OChannelBinaryProtocol . REQUEST_REPLICATION , new ODocument ( ) . field ( "operation" , "stop" ) . field ( "node" , iRemoteServer ) . field ( "db" , iDatabaseName ) , "Stop replication" ) ; OLogManager . instance ( ) . debug ( this , "Stopped replication of database '%s' from server '%s' to '%s'" , iDatabaseName , storage . getURL ( ) , iRemoteServer ) ; return this ; }
Stops the replication between two servers .
17,647
public synchronized ODocument getReplicationJournal ( final String iDatabaseName , final String iRemoteServer ) throws IOException { OLogManager . instance ( ) . debug ( this , "Retrieving the replication log for database '%s' from server '%s'..." , iDatabaseName , storage . getURL ( ) ) ; final ODocument response = sendRequest ( OChannelBinaryProtocol . REQUEST_REPLICATION , new ODocument ( ) . field ( "operation" , "getJournal" ) . field ( "node" , iRemoteServer ) . field ( "db" , iDatabaseName ) , "Retrieve replication log" ) ; OLogManager . instance ( ) . debug ( this , "Returned %d replication log entries for the database '%s' from server '%s' against server '%s'" , response . fields ( ) , iDatabaseName , storage . getURL ( ) , iRemoteServer ) ; return response ; }
Gets the replication journal for a database .
17,648
public OServerAdmin replicationAlign ( final String iDatabaseName , final String iRemoteServer , final String iOptions ) { OLogManager . instance ( ) . debug ( this , "Started the alignment of database '%s' from server '%s' to '%s' with options %s" , iDatabaseName , storage . getURL ( ) , iRemoteServer , iOptions ) ; sendRequest ( OChannelBinaryProtocol . REQUEST_REPLICATION , new ODocument ( ) . field ( "operation" , "align" ) . field ( "node" , iRemoteServer ) . field ( "db" , iDatabaseName ) . field ( "options" , iOptions ) , "Align databases" ) ; OLogManager . instance ( ) . debug ( this , "Alignment finished" ) ; return this ; }
Aligns a database between two servers
17,649
public synchronized OServerAdmin copyDatabase ( final String iDatabaseName , final String iDatabaseUserName , final String iDatabaseUserPassword , final String iRemoteName , final String iRemoteEngine ) throws IOException { storage . checkConnection ( ) ; try { final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_DB_COPY ) ; try { network . writeString ( iDatabaseName ) ; network . writeString ( iDatabaseUserName ) ; network . writeString ( iDatabaseUserPassword ) ; network . writeString ( iRemoteName ) ; network . writeString ( iRemoteEngine ) ; } finally { storage . endRequest ( network ) ; } storage . getResponse ( network ) ; OLogManager . instance ( ) . debug ( this , "Database '%s' has been copied to the server '%s'" , iDatabaseName , iRemoteName ) ; } catch ( Exception e ) { OLogManager . instance ( ) . exception ( "Cannot copy the database: " + iDatabaseName , e , OStorageException . class ) ; } return this ; }
Copies a database to a remote server instance .
17,650
public Object execute ( final OIdentifiable o , final OCommandExecutor iRequester ) { for ( int i = 0 ; i < configuredParameters . length ; ++ i ) { if ( configuredParameters [ i ] instanceof OSQLFilterItemField ) runtimeParameters [ i ] = ( ( OSQLFilterItemField ) configuredParameters [ i ] ) . getValue ( o , null ) ; else if ( configuredParameters [ i ] instanceof OSQLFunctionRuntime ) runtimeParameters [ i ] = ( ( OSQLFunctionRuntime ) configuredParameters [ i ] ) . execute ( o , iRequester ) ; } final Object functionResult = function . execute ( o , runtimeParameters , iRequester ) ; return transformValue ( o , functionResult ) ; }
Execute a function .
17,651
public static EmbeddedJettyBuilder . ServletContextHandlerBuilder addWicketHandler ( EmbeddedJettyBuilder embeddedJettyBuilder , String contextPath , EventListener springContextloader , Class < ? extends WebApplication > wicketApplication , boolean development ) { EmbeddedJettyBuilder . ServletContextHandlerBuilder wicketHandler = embeddedJettyBuilder . createRootServletContextHandler ( contextPath ) . setClassLoader ( Thread . currentThread ( ) . getContextClassLoader ( ) ) . addEventListener ( springContextloader ) ; return addWicketHandler ( wicketHandler , wicketApplication , development ) ; }
Adds wicket handler at root context .
17,652
public boolean add ( final OIdentifiable e ) { if ( e . getIdentity ( ) . isNew ( ) ) { final ORecord < ? > record = e . getRecord ( ) ; if ( newItems == null ) newItems = new IdentityHashMap < ORecord < ? > , Object > ( ) ; else if ( newItems . containsKey ( record ) ) return false ; newItems . put ( record , NEWMAP_VALUE ) ; setDirty ( ) ; return true ; } else if ( OGlobalConfiguration . LAZYSET_WORK_ON_STREAM . getValueAsBoolean ( ) && getStreamedContent ( ) != null ) { final String ridString = e . getIdentity ( ) . toString ( ) ; final StringBuilder buffer = getStreamedContent ( ) ; if ( buffer . indexOf ( ridString ) < 0 ) { if ( buffer . length ( ) > 0 ) buffer . append ( ',' ) ; e . getIdentity ( ) . toString ( buffer ) ; setDirty ( ) ; return true ; } return false ; } else { final int pos = indexOf ( e ) ; if ( pos < 0 ) { delegate . add ( pos * - 1 - 1 , e ) ; return true ; } return false ; } }
Adds the item in the underlying List preserving the order of the collection .
17,653
public int indexOf ( final OIdentifiable iElement ) { if ( delegate . isEmpty ( ) ) return - 1 ; final boolean prevConvert = delegate . isAutoConvertToRecord ( ) ; if ( prevConvert ) delegate . setAutoConvertToRecord ( false ) ; final int pos = Collections . binarySearch ( delegate , iElement ) ; if ( prevConvert ) delegate . setAutoConvertToRecord ( true ) ; return pos ; }
Returns the position of the element in the set . Execute a binary search since the elements are always ordered .
17,654
public ORDER compare ( OQueryOperator other ) { final Class < ? > thisClass = this . getClass ( ) ; final Class < ? > otherClass = other . getClass ( ) ; int thisPosition = - 1 ; int otherPosition = - 1 ; for ( int i = 0 ; i < DEFAULT_OPERATORS_ORDER . length ; i ++ ) { final Class < ? > clazz = DEFAULT_OPERATORS_ORDER [ i ] ; if ( clazz . isAssignableFrom ( thisClass ) ) { thisPosition = i ; } if ( clazz . isAssignableFrom ( otherClass ) ) { otherPosition = i ; } } if ( thisPosition == - 1 || otherPosition == - 1 ) { return ORDER . UNKNOWNED ; } if ( thisPosition > otherPosition ) { return ORDER . AFTER ; } else if ( thisPosition < otherPosition ) { return ORDER . BEFORE ; } return ORDER . EQUAL ; }
Check priority of this operator compare to given operator .
17,655
public Object execute ( final Map < Object , Object > iArgs ) { if ( attribute == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseRecord database = getDatabase ( ) ; database . checkSecurity ( ODatabaseSecurityResources . DATABASE , ORole . PERMISSION_UPDATE ) ; ( ( ODatabaseComplex < ? > ) database ) . setInternal ( attribute , value ) ; return null ; }
Execute the ALTER DATABASE .
17,656
public boolean open ( ) throws IOException { lock . acquireExclusiveLock ( ) ; try { super . open ( ) ; recoverTransactions ( ) ; return true ; } finally { lock . releaseExclusiveLock ( ) ; } }
Opens the file segment and recovers pending transactions if any
17,657
public void addLog ( final byte iOperation , final int iTxId , final int iClusterId , final long iClusterOffset , final byte iRecordType , final int iRecordVersion , final byte [ ] iRecordContent , int dataSegmentId ) throws IOException { final int contentSize = iRecordContent != null ? iRecordContent . length : 0 ; final int size = OFFSET_RECORD_CONTENT + contentSize ; lock . acquireExclusiveLock ( ) ; try { int offset = file . allocateSpace ( size ) ; file . writeByte ( offset , STATUS_COMMITTING ) ; offset += OBinaryProtocol . SIZE_BYTE ; file . writeByte ( offset , iOperation ) ; offset += OBinaryProtocol . SIZE_BYTE ; file . writeInt ( offset , iTxId ) ; offset += OBinaryProtocol . SIZE_INT ; file . writeShort ( offset , ( short ) iClusterId ) ; offset += OBinaryProtocol . SIZE_SHORT ; file . writeLong ( offset , iClusterOffset ) ; offset += OBinaryProtocol . SIZE_LONG ; file . writeByte ( offset , iRecordType ) ; offset += OBinaryProtocol . SIZE_BYTE ; file . writeInt ( offset , iRecordVersion ) ; offset += OBinaryProtocol . SIZE_INT ; file . writeInt ( offset , dataSegmentId ) ; offset += OBinaryProtocol . SIZE_INT ; file . writeInt ( offset , contentSize ) ; offset += OBinaryProtocol . SIZE_INT ; file . write ( offset , iRecordContent ) ; offset += contentSize ; if ( synchEnabled ) file . synch ( ) ; } finally { lock . releaseExclusiveLock ( ) ; } }
Appends a log entry
17,658
private Set < Integer > scanForTransactionsToRecover ( ) throws IOException { final Set < Integer > txToRecover = new HashSet < Integer > ( ) ; final Set < Integer > txToNotRecover = new HashSet < Integer > ( ) ; for ( long offset = 0 ; eof ( offset ) ; offset = nextEntry ( offset ) ) { final byte status = file . readByte ( offset ) ; final int txId = file . readInt ( offset + OFFSET_TX_ID ) ; switch ( status ) { case STATUS_FREE : txToNotRecover . add ( txId ) ; break ; case STATUS_COMMITTING : txToRecover . add ( txId ) ; break ; } } if ( txToNotRecover . size ( ) > 0 ) txToRecover . removeAll ( txToNotRecover ) ; return txToRecover ; }
Scans the segment and returns the set of transactions ids to recover .
17,659
private int recoverTransaction ( final int iTxId ) throws IOException { int recordsRecovered = 0 ; final ORecordId rid = new ORecordId ( ) ; final List < Long > txRecordPositions = new ArrayList < Long > ( ) ; for ( long beginEntry = 0 ; eof ( beginEntry ) ; beginEntry = nextEntry ( beginEntry ) ) { long offset = beginEntry ; final byte status = file . readByte ( offset ) ; offset += OBinaryProtocol . SIZE_BYTE ; if ( status != STATUS_FREE ) { offset += OBinaryProtocol . SIZE_BYTE ; final int txId = file . readInt ( offset ) ; if ( txId == iTxId ) { txRecordPositions . add ( beginEntry ) ; } } } for ( int i = txRecordPositions . size ( ) - 1 ; i >= 0 ; i -- ) { final long beginEntry = txRecordPositions . get ( i ) ; long offset = beginEntry ; final byte status = file . readByte ( offset ) ; offset += OBinaryProtocol . SIZE_BYTE ; final byte operation = file . readByte ( offset ) ; offset += OBinaryProtocol . SIZE_BYTE ; final int txId = file . readInt ( offset ) ; offset += OBinaryProtocol . SIZE_INT ; rid . clusterId = file . readShort ( offset ) ; offset += OBinaryProtocol . SIZE_SHORT ; rid . clusterPosition = file . readLong ( offset ) ; offset += OBinaryProtocol . SIZE_LONG ; final byte recordType = file . readByte ( offset ) ; offset += OBinaryProtocol . SIZE_BYTE ; final int recordVersion = file . readInt ( offset ) ; offset += OBinaryProtocol . SIZE_INT ; final int dataSegmentId = file . readInt ( offset ) ; offset += OBinaryProtocol . SIZE_INT ; final int recordSize = file . readInt ( offset ) ; offset += OBinaryProtocol . SIZE_INT ; final byte [ ] buffer ; if ( recordSize > 0 ) { buffer = new byte [ recordSize ] ; file . read ( offset , buffer , recordSize ) ; offset += recordSize ; } else buffer = null ; recoverTransactionEntry ( status , operation , txId , rid , recordType , recordVersion , buffer , dataSegmentId ) ; recordsRecovered ++ ; file . writeByte ( beginEntry , STATUS_FREE ) ; } return recordsRecovered ; }
Recover a transaction .
17,660
public static String pingJdbcEndpoint ( MuleContext muleContext , String muleJdbcDataSourceName , String tableName ) { DataSource ds = JdbcUtil . lookupDataSource ( muleContext , muleJdbcDataSourceName ) ; Connection c = null ; Statement s = null ; ResultSet rs = null ; try { c = ds . getConnection ( ) ; s = c . createStatement ( ) ; rs = s . executeQuery ( "select 1 from " + tableName ) ; } catch ( SQLException e ) { return ERROR_PREFIX + ": The table " + tableName + " was not found in the data source " + muleJdbcDataSourceName + ", reason: " + e . getMessage ( ) ; } finally { try { if ( rs != null ) rs . close ( ) ; } catch ( SQLException e ) { } try { if ( s != null ) s . close ( ) ; } catch ( SQLException e ) { } try { if ( c != null ) c . close ( ) ; } catch ( SQLException e ) { } } return OK_PREFIX + ": The table " + tableName + " was found in the data source " + muleJdbcDataSourceName ; }
Verify access to a JDBC endpoint by verifying that a specified table is accessible .
17,661
public static String pingJmsEndpoint ( MuleContext muleContext , String queueName ) { return pingJmsEndpoint ( muleContext , DEFAULT_MULE_JMS_CONNECTOR , queueName ) ; }
Verify access to a JMS endpoint by browsing a specified queue for messages .
17,662
@ SuppressWarnings ( "rawtypes" ) private static boolean isQueueEmpty ( MuleContext muleContext , String muleJmsConnectorName , String queueName ) throws JMSException { JmsConnector muleCon = ( JmsConnector ) MuleUtil . getSpringBean ( muleContext , muleJmsConnectorName ) ; Session s = null ; QueueBrowser b = null ; try { s = muleCon . getConnection ( ) . createSession ( false , Session . AUTO_ACKNOWLEDGE ) ; Queue q = s . createQueue ( queueName ) ; b = s . createBrowser ( q ) ; Enumeration e = b . getEnumeration ( ) ; return ! e . hasMoreElements ( ) ; } finally { try { if ( b != null ) b . close ( ) ; } catch ( JMSException e ) { } try { if ( s != null ) s . close ( ) ; } catch ( JMSException e ) { } } }
Browse a queue for messages
17,663
public T select ( Object item ) { if ( item == null ) { return null ; } if ( itemClass . isInstance ( item ) ) { return itemClass . cast ( item ) ; } logger . debug ( "item [{}] is not assignable to class [{}], returning null" , item , itemClass ) ; return null ; }
If the item is null return null . If the item is instance of the constructor parameter itemClass return the type cast result otherwise return null .
17,664
public BeanQuery < T > orderBy ( String orderByProperty , Comparator propertyValueComparator ) { this . comparator = new DelegatedSortOrderableComparator ( new PropertyComparator ( orderByProperty , propertyValueComparator ) ) ; return this ; }
Specify the property of the beans to be compared by the propertyValueComparator when sorting the result . If there is not a accessible public read method of the property the value of the property passed to the propertyValueComparator will be null .
17,665
public BeanQuery < T > orderBy ( Comparator ... beanComparator ) { this . comparator = new DelegatedSortOrderableComparator ( ComparatorUtils . chainedComparator ( beanComparator ) ) ; return this ; }
Using an array of Comparators applied in sequence until one returns not equal or the array is exhausted .
17,666
public T executeFrom ( Object bean ) { List < T > executeFromCollectionResult = executeFrom ( Collections . singleton ( bean ) ) ; if ( CollectionUtils . isEmpty ( executeFromCollectionResult ) ) { return null ; } else { return executeFromCollectionResult . get ( 0 ) ; } }
Execute from a bean to check does it match the filtering condition and convert it .
17,667
public List < T > execute ( ) { if ( CollectionUtils . isEmpty ( from ) ) { logger . info ( "Querying from an empty collection, returning empty list." ) ; return Collections . emptyList ( ) ; } List copied = new ArrayList ( this . from ) ; logger . info ( "Start apply predicate [{}] to collection with [{}] items." , predicate , copied . size ( ) ) ; CollectionUtils . filter ( copied , this . predicate ) ; logger . info ( "Done filtering collection, filtered result size is [{}]" , copied . size ( ) ) ; if ( null != this . comparator && copied . size ( ) > 1 ) { Comparator actualComparator = this . descSorting ? comparator . desc ( ) : comparator . asc ( ) ; logger . info ( "Start to sort the filtered collection with comparator [{}]" , actualComparator ) ; Collections . sort ( copied , actualComparator ) ; logger . info ( "Done sorting the filtered collection." ) ; } logger . info ( "Start to slect from filtered collection with selector [{}]." , selector ) ; List < T > select = this . selector . select ( copied ) ; logger . info ( "Done select from filtered collection." ) ; return select ; }
Execute this Query . If query from a null or empty collection an empty list will be returned .
17,668
public static BeanQuery < Map < String , Object > > select ( KeyValueMapSelector ... selectors ) { return new BeanQuery < Map < String , Object > > ( new CompositeSelector ( selectors ) ) ; }
Create a BeanQuery instance with multiple Selectors .
17,669
public void write ( final Writer writer ) throws ConfigurationException , IOException { Preconditions . checkNotNull ( writer ) ; @ SuppressWarnings ( "unchecked" ) final HashMap < String , Object > settings = ( HashMap < String , Object > ) fromNode ( this . getModel ( ) . getInMemoryRepresentation ( ) ) ; this . mapper . writerWithDefaultPrettyPrinter ( ) . writeValue ( writer , settings ) ; }
Writes the configuration .
17,670
private ImmutableNode toNode ( final Builder builder , final Object obj ) { assert ! ( obj instanceof List ) ; if ( obj instanceof Map ) { return mapToNode ( builder , ( Map < String , Object > ) obj ) ; } else { return valueToNode ( builder , obj ) ; } }
Creates a node for the specified object .
17,671
private ImmutableNode mapToNode ( final Builder builder , final Map < String , Object > map ) { for ( final Map . Entry < String , Object > entry : map . entrySet ( ) ) { final String key = entry . getKey ( ) ; final Object value = entry . getValue ( ) ; if ( value instanceof List ) { for ( final Object item : ( List ) value ) { addChildNode ( builder , key , item ) ; } } else { addChildNode ( builder , key , value ) ; } } return builder . create ( ) ; }
Creates a node for the specified map .
17,672
private void addChildNode ( final Builder builder , final String name , final Object value ) { assert ! ( value instanceof List ) ; final Builder childBuilder = new Builder ( ) ; childBuilder . name ( name ) ; final ImmutableNode childNode = toNode ( childBuilder , value ) ; builder . addChild ( childNode ) ; }
Adds a child node to the specified builder .
17,673
private ImmutableNode valueToNode ( final Builder builder , final Object value ) { return builder . value ( value ) . create ( ) ; }
Creates a node for the specified value .
17,674
private Object fromNode ( final ImmutableNode node ) { if ( ! node . getChildren ( ) . isEmpty ( ) ) { final Map < String , List < ImmutableNode > > children = getChildrenWithName ( node ) ; final HashMap < String , Object > map = new HashMap < > ( ) ; for ( final Map . Entry < String , List < ImmutableNode > > entry : children . entrySet ( ) ) { assert ! entry . getValue ( ) . isEmpty ( ) ; if ( entry . getValue ( ) . size ( ) == 1 ) { final ImmutableNode child = entry . getValue ( ) . get ( 0 ) ; final Object childValue = fromNode ( child ) ; map . put ( entry . getKey ( ) , childValue ) ; } else { final ArrayList < Object > list = new ArrayList < > ( ) ; for ( final ImmutableNode child : entry . getValue ( ) ) { final Object childValue = fromNode ( child ) ; list . add ( childValue ) ; } map . put ( entry . getKey ( ) , list ) ; } } return map ; } else { return node . getValue ( ) ; } }
Gets a serialization object from a node .
17,675
public ClassSelector except ( String ... propertyNames ) { if ( ArrayUtils . isEmpty ( propertyNames ) ) { return this ; } boolean updated = false ; for ( String propertyToRemove : propertyNames ) { if ( removePropertySelector ( propertyToRemove ) ) { updated = true ; } } if ( updated ) { compositeSelector = new CompositeSelector ( this . propertySelectors ) ; } return this ; }
Exclude properties from the result map .
17,676
public ClassSelector add ( String ... propertyNames ) { if ( ArrayUtils . isNotEmpty ( propertyNames ) ) { for ( String propertyNameToAdd : propertyNames ) { addPropertySelector ( propertyNameToAdd ) ; } } return this ; }
Include properties in the result map .
17,677
public ViewSelectionAttributeAssert attribute ( String attributeName ) { isNotEmpty ( ) ; ViewSelectionAttribute attributeValues = new ViewSelectionAttribute ( actual , attributeName ) ; return new ViewSelectionAttributeAssert ( attributeValues ) ; }
Creates an object for making assertions about an attribute set extracted from each view in the selection . This always fails for an empty selection .
17,678
private static Message generateHeader ( HeaderValues param ) { HeaderFields header = new HeaderFields ( ) ; setValues ( header , param ) ; Message headerMsg = header . unwrap ( ) ; for ( String comment : param . comments ) { headerMsg . addComment ( comment ) ; } return headerMsg ; }
This more general generate method is private along with the HeaderValues object until we decide what the public API should be .
17,679
public ViewSelection selectViews ( View view ) { ViewSelection result = new ViewSelection ( ) ; for ( List < Selector > selectorParts : selectorGroups ) { result . addAll ( selectViewsForGroup ( selectorParts , view ) ) ; } return result ; }
Applies this selector to the given view selecting all descendants of the view that match this selector .
17,680
public int compareTo ( final Problem o ) { final int ix = this . severity . ordinal ( ) ; final int oid = o . severity . ordinal ( ) ; return ix - oid ; }
Compare such that most severe Problems will appear last least first .
17,681
public static String fixValue ( String value ) { if ( value != null && ! value . equals ( "" ) ) { final String [ ] words = value . toLowerCase ( ) . split ( "_" ) ; value = "" ; for ( final String word : words ) { if ( word . length ( ) > 1 ) { value += word . substring ( 0 , 1 ) . toUpperCase ( ) + word . substring ( 1 ) + " " ; } else { value = word ; } } } if ( value . contains ( "\\n" ) ) { value = value . replace ( "\\n" , System . getProperty ( "line.separator" ) ) ; } return value ; }
replace under score with space replace \ n char with platform indepent line . separator
17,682
public static String removeLast ( String original , String string ) { int lastIndexOf = original . lastIndexOf ( string ) ; if ( lastIndexOf == - 1 ) { return original ; } return original . substring ( 0 , lastIndexOf ) ; }
This method create nre properties from the origianl one and remove any key with the password then call toString method on this prperties .
17,683
public static String getFirstLine ( final String message ) { if ( isEmpty ( message ) ) { return message ; } if ( message . contains ( "\n" ) ) { return message . split ( "\n" ) [ 0 ] ; } return message ; }
Gets the first line .
17,684
public static void copyToClipboard ( String text ) { final StringSelection stringSelection = new StringSelection ( text ) ; final Clipboard clipboard = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) ; clipboard . setContents ( stringSelection , stringSelection ) ; }
Copy to clipboard .
17,685
public String toQueryString ( ) { final StringBuffer buf = new StringBuffer ( ) ; final Object value1 = this . values . get ( 0 ) ; buf . append ( this . column . getName ( ) ) ; switch ( this . type ) { case STARTS_WIDTH : buf . append ( " like '" + value1 + "%'" ) ; break ; case CONTAINS : buf . append ( " like '%" + value1 + "%'" ) ; break ; case ENDS_WITH : buf . append ( " like '%" + value1 + "'" ) ; break ; case DOESNOT_CONTAINS : buf . append ( " not like '%" + value1 + "%'" ) ; break ; case MORE_THAN : buf . append ( " > '" + value1 + "'" ) ; break ; case LESS_THAN : buf . append ( " < '" + value1 + "'" ) ; break ; } return buf . toString ( ) ; }
To query string .
17,686
public static String getNaturalAnalogueSequence ( PolymerNotation polymer ) throws HELM2HandledException , PeptideUtilsException , ChemistryException { checkPeptidePolymer ( polymer ) ; return FastaFormat . generateFastaFromPeptide ( MethodsMonomerUtils . getListOfHandledMonomers ( polymer . getListMonomers ( ) ) ) ; }
method to produce for a peptide PolymerNotation the natural analogue sequence
17,687
public static String getSequence ( PolymerNotation polymer ) throws HELM2HandledException , PeptideUtilsException , ChemistryException { checkPeptidePolymer ( polymer ) ; StringBuilder sb = new StringBuilder ( ) ; List < Monomer > monomers = MethodsMonomerUtils . getListOfHandledMonomers ( polymer . getListMonomers ( ) ) ; for ( Monomer monomer : monomers ) { String id = monomer . getAlternateId ( ) ; if ( id . length ( ) > 1 ) { id = "[" + id + "]" ; } sb . append ( id ) ; } return sb . toString ( ) ; }
method to produce for a peptide PolymerNotation the sequence
17,688
private static void processOtherMappings ( ) { codeToJavaMapping . clear ( ) ; codeToJKTypeMapping . clear ( ) ; shortListOfJKTypes . clear ( ) ; Set < Class < ? > > keySet = javaToCodeMapping . keySet ( ) ; for ( Class < ? > clas : keySet ) { List < Integer > codes = javaToCodeMapping . get ( clas ) ; for ( Integer code : codes ) { codeToJavaMapping . put ( code , clas ) ; logger . debug ( " Code ({}) class ({}) name ({})" , code , clas . getSimpleName ( ) , namesMapping . get ( code ) ) ; codeToJKTypeMapping . put ( code , new JKType ( code , clas , namesMapping . get ( code ) ) ) ; } shortListOfJKTypes . add ( new JKType ( codes . get ( 0 ) , clas , namesMapping . get ( codes . get ( 0 ) ) ) ) ; } }
This method is used to avoid reconigure the mapping in the otherside again .
17,689
protected void loadDefaultConfigurations ( ) { if ( JK . getURL ( DEFAULT_LABLES_FILE_NAME ) != null ) { logger . debug ( "Load default lables from : " + DEFAULT_LABLES_FILE_NAME ) ; addLables ( JKIOUtil . readPropertiesFile ( DEFAULT_LABLES_FILE_NAME ) ) ; } }
Load default configurations .
17,690
public static < T > T cloneBean ( final Object bean ) { try { return ( T ) BeanUtils . cloneBean ( bean ) ; } catch ( IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } }
Clone bean .
17,691
public static Class < ? > getClass ( final String beanClassName ) { try { return Class . forName ( beanClassName ) ; } catch ( final ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } }
Gets the class .
17,692
public static < T > T getPropertyValue ( final Object instance , final String fieldName ) { try { return ( T ) PropertyUtils . getProperty ( instance , fieldName ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } }
Gets the property value .
17,693
public static boolean isBoolean ( final Class type ) { if ( Boolean . class . isAssignableFrom ( type ) ) { return true ; } return type . getName ( ) . equals ( "boolean" ) ; }
Checks if is boolean .
17,694
public static void setPeopertyValue ( final Object target , final String fieldName , Object value ) { JK . logger . trace ( "setPeopertyValue On class({}) on field ({}) with value ({})" , target , fieldName , value ) ; try { if ( value != null ) { Field field = getFieldByName ( target . getClass ( ) , fieldName ) ; if ( field . getType ( ) . isEnum ( ) ) { Class < ? extends Enum > clas = ( Class ) field . getType ( ) ; value = Enum . valueOf ( clas , value . toString ( ) ) ; JK . logger . debug ( "Field is enum, new value is ({}) for class ({})" , value , value . getClass ( ) ) ; } } PropertyUtils . setNestedProperty ( target , fieldName , value ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Sets the peoperty value .
17,695
public static void addItemToList ( final Object target , final String fieldName , final Object value ) { try { List list = ( List ) getFieldValue ( target , fieldName ) ; list . add ( value ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Adds the item to list .
17,696
public static Class < ? > toClass ( final String name ) { try { return Class . forName ( name ) ; } catch ( final ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } }
To class .
17,697
public static Class < ? > [ ] toClassesFromObjects ( final Object [ ] params ) { final Class < ? > [ ] classes = new Class < ? > [ params . length ] ; int i = 0 ; for ( final Object object : params ) { if ( object != null ) { classes [ i ++ ] = object . getClass ( ) ; } else { classes [ i ++ ] = Object . class ; } } return classes ; }
To classes from objects .
17,698
public static boolean isMethodDirectlyExists ( Object object , String methodName , Class < ? > ... params ) { try { Method method = object . getClass ( ) . getDeclaredMethod ( methodName , params ) ; return true ; } catch ( NoSuchMethodException e ) { return false ; } catch ( SecurityException e ) { throw new RuntimeException ( e ) ; } }
Checks if is method directly exists .
17,699
public static Object toObject ( final String xml ) { final ByteArrayInputStream out = new ByteArrayInputStream ( xml . getBytes ( ) ) ; final XMLDecoder encoder = new XMLDecoder ( out ) ; final Object object = encoder . readObject ( ) ; encoder . close ( ) ; return object ; }
To object .