idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
16,800 | public static String last ( String string , char separator ) { if ( string == null ) { return null ; } if ( string . isEmpty ( ) ) { return "" ; } return string . substring ( string . lastIndexOf ( separator ) + 1 ) ; } | Get last string sequence following given character . If separator character is missing from the source string returns entire string . Return null if string argument is null and empty if empty . |
16,801 | public static String removeTrailing ( String string , char c ) { if ( string == null ) { return null ; } final int lastCharIndex = string . length ( ) - 1 ; return string . charAt ( lastCharIndex ) == c ? string . substring ( 0 , lastCharIndex ) : string ; } | Remove trailing character if exists . |
16,802 | public static String load ( InputStream inputStream , Integer ... maxCount ) throws IOException { return load ( new InputStreamReader ( inputStream , "UTF-8" ) , maxCount ) ; } | Load string from UTF - 8 bytes stream then closes it . |
16,803 | public static String load ( File file , Integer ... maxCount ) throws IOException { return load ( new FileReader ( file ) , maxCount ) ; } | Load string from UTF - 8 file content . |
16,804 | public static String load ( Reader reader , Integer ... maxCount ) throws IOException { long maxCountValue = maxCount . length > 0 ? maxCount [ 0 ] : Long . MAX_VALUE ; StringWriter writer = new StringWriter ( ) ; try { char [ ] buffer = new char [ 1024 ] ; for ( ; ; ) { int readChars = reader . read ( buffer , 0 , ( int ) Math . min ( buffer . length , maxCountValue ) ) ; if ( readChars <= 0 ) { break ; } writer . write ( buffer , 0 , readChars ) ; maxCountValue -= readChars ; } } finally { Files . close ( reader ) ; Files . close ( writer ) ; } return writer . toString ( ) ; } | Load string from character stream then closes it . |
16,805 | public static String md5 ( String text ) { MessageDigest md ; try { md = MessageDigest . getInstance ( "MD5" ) ; } catch ( NoSuchAlgorithmException e ) { throw new BugError ( "Java runtime without MD5 support." ) ; } md . update ( text . getBytes ( ) ) ; byte [ ] md5 = md . digest ( ) ; char [ ] buffer = new char [ 32 ] ; for ( int i = 0 ; i < 16 ; i ++ ) { buffer [ i * 2 ] = HEXA [ ( md5 [ i ] & 0xf0 ) >> 4 ] ; buffer [ i * 2 + 1 ] = HEXA [ md5 [ i ] & 0x0f ] ; } return new String ( buffer ) ; } | Generate text MD5 hash into hexadecimal format . Returned string will be exactly 32 characters long . This function is designed but not limited to store password into databases . Anyway be aware that MD5 is not a strong enough hash function to be used on public transfers . |
16,806 | public static String getProtocol ( String url ) { if ( url == null ) { return null ; } int protocolSeparatorIndex = url . indexOf ( "://" ) ; if ( protocolSeparatorIndex == - 1 ) { return null ; } return url . substring ( 0 , protocolSeparatorIndex ) . toLowerCase ( ) ; } | Get URL protocol - lower case or null if given URL does not contains one . Returns null if given URL argument is null or empty . |
16,807 | public static void swap ( short [ ] shortArray1 , short [ ] shortArray2 , int index ) { XORSwap . swap ( shortArray1 , index , shortArray2 , index ) ; } | Swap the elements of short long arrays at the same position |
16,808 | public TableMetadataBuilder withColumns ( List < ColumnMetadata > columnsMetadata ) { for ( ColumnMetadata colMetadata : columnsMetadata ) { columns . put ( colMetadata . getName ( ) , colMetadata ) ; } return this ; } | Add new columns . The columns previously created are not removed . |
16,809 | public TableMetadataBuilder addIndex ( IndexType indType , String indexName , String ... fields ) throws ExecutionException { IndexName indName = new IndexName ( tableName . getName ( ) , tableName . getName ( ) , indexName ) ; Map < ColumnName , ColumnMetadata > columnsMetadata = new HashMap < ColumnName , ColumnMetadata > ( fields . length ) ; for ( String field : fields ) { ColumnMetadata cMetadata = columns . get ( new ColumnName ( tableName , field ) ) ; if ( cMetadata == null ) { throw new ExecutionException ( "Trying to index a not existing column: " + field ) ; } columnsMetadata . put ( new ColumnName ( tableName , field ) , cMetadata ) ; } IndexMetadata indMetadata = new IndexMetadata ( indName , columnsMetadata , indType , null ) ; indexes . put ( indName , indMetadata ) ; return this ; } | Add an index . Must be called after including columns because columnMetadata is recovered from the tableMetadata . Options in indexMetadata will be null . |
16,810 | public TableMetadataBuilder addIndex ( IndexMetadata indexMetadata ) { indexes . put ( indexMetadata . getName ( ) , indexMetadata ) ; return this ; } | Add an index . |
16,811 | public TableMetadataBuilder withPartitionKey ( String ... fields ) { for ( String field : fields ) { partitionKey . add ( new ColumnName ( tableName , field ) ) ; } return this ; } | Set the partition key . |
16,812 | public TableMetadataBuilder withClusterKey ( String ... fields ) { for ( String field : fields ) { clusterKey . add ( new ColumnName ( tableName , field ) ) ; } return this ; } | Set the cluster key . |
16,813 | public TableMetadata build ( boolean isPKRequired ) { if ( isPKRequired && partitionKey . isEmpty ( ) ) { this . withPartitionKey ( columns . keySet ( ) . iterator ( ) . next ( ) . getName ( ) ) ; } return new TableMetadata ( tableName , options , new LinkedHashMap < > ( columns ) , indexes , clusterName , partitionKey , clusterKey ) ; } | Builds the table metadata . |
16,814 | public boolean patternOverflow ( ) { BitArray lin = new BitArray ( width ) ; bits . forEach ( ( i ) -> lin . set ( column ( i ) , true ) ) ; return lin . isSet ( 0 ) && lin . isSet ( width - 1 ) ; } | Returns true if pattern overflows line |
16,815 | public float patternLineCoverage ( ) { BitArray lin = new BitArray ( width ) ; bits . forEach ( ( i ) -> lin . set ( column ( i ) , true ) ) ; return ( float ) lin . count ( ) / ( float ) width ; } | Returns 1 . 0 if all columns have set bits or less |
16,816 | public float patternSquareness ( ) { int patternStart = patternStart ( ) ; int patternEnd = patternEnd ( ) ; int sy = line ( patternStart ) ; int ey = line ( patternEnd ) ; int sx = column ( patternStart ) ; int ex = column ( patternEnd ) ; float actCnt = 0 ; int w = ex - sx + 1 ; int h = ey - sy + 1 ; for ( int ii = 0 ; ii < h ; ii ++ ) { for ( int jj = 0 ; jj < w ; jj ++ ) { if ( getColor ( sx + jj , sy + ii ) ) { actCnt ++ ; } } } float allCnt = getSetCount ( ) ; return actCnt / allCnt ; } | Returns 1 . 0 if pattern is square or less if not . |
16,817 | public String getHyperlink ( ) { String strMailTo = this . getString ( ) ; if ( strMailTo != null ) if ( strMailTo . length ( ) > 0 ) strMailTo = BaseApplication . MAIL_TO + ":" + strMailTo ; return strMailTo ; } | Get the HTML mailto Hyperlink . |
16,818 | public static < T extends Comparable < ? super T > > List < T > sorted ( List < T > list ) { List < T > result = new ArrayList < > ( list ) ; Collections . sort ( result ) ; return result ; } | Sorts the given list in ascending natural order . The algorithm is stable which means equal elements don t get reordered . |
16,819 | @ SuppressWarnings ( "unchecked" ) public static < T > List < T > sorted ( List < T > list , Comparator < ? super T > comparator ) { List < T > result = new ArrayList < > ( list ) ; Collections . sort ( result , comparator ) ; return result ; } | Sorts the given list using the given comparator . The algorithm is stable which means equal elements don t get reordered . |
16,820 | public static < T > List < T > addFirst ( List < T > to , T what ) { List < T > data = safeList ( to ) ; data . add ( 0 , what ) ; return data ; } | Add element to start of list |
16,821 | public static < T > Collection < T > filter ( Collection < T > data , Filter < T > filter ) { if ( ! Utils . isEmpty ( data ) ) { Iterator < T > iterator = data . iterator ( ) ; while ( iterator . hasNext ( ) ) { T item = iterator . next ( ) ; if ( ! filter . accept ( item ) ) { iterator . remove ( ) ; } } } return data ; } | Removes items which not accepted by filter |
16,822 | public static < T > List < T > filtered ( Collection < T > data , Filter < T > filter ) { List < T > list = new ArrayList < > ( ) ; if ( ! Utils . isEmpty ( data ) ) { for ( T item : data ) { if ( filter . accept ( item ) ) { list . add ( item ) ; } } } return list ; } | Returns new List without items which not accepted by filter |
16,823 | public UserInfo getUserTemplate ( ) { if ( userControl == null ) userControl = new UserControl ( this . getOwner ( ) . findRecordOwner ( ) ) ; if ( userControl != null ) if ( ( userControl . getEditMode ( ) == DBConstants . EDIT_CURRENT ) || ( userControl . getEditMode ( ) == DBConstants . EDIT_IN_PROGRESS ) ) { UserInfo userInfo = ( UserInfo ) ( ( ReferenceField ) userControl . getField ( UserControl . TEMPLATE_USER_ID ) ) . getReference ( ) ; if ( userInfo != null ) if ( ( userInfo . getEditMode ( ) == DBConstants . EDIT_CURRENT ) || ( userInfo . getEditMode ( ) == DBConstants . EDIT_IN_PROGRESS ) ) return userInfo ; } return null ; } | GetUserTemplate Method . |
16,824 | public void addNextField ( FieldInfo field ) { if ( ( ( m_iFieldsTypes & MODIFIED_ONLY ) == MODIFIED_ONLY ) && ( ! field . isModified ( ) ) ) this . addNextData ( DATA_SKIP ) ; else this . addNextData ( field . getData ( ) ) ; } | Add this field to the buffer . |
16,825 | public int bufferToFields ( FieldList record , boolean bDisplayOption , int iMoveMode ) { this . resetPosition ( ) ; int iFieldCount = record . getFieldCount ( ) ; int iErrorCode = Constants . NORMAL_RETURN ; int iTempError ; for ( int iFieldSeq = Constants . MAIN_FIELD ; iFieldSeq <= iFieldCount + Constants . MAIN_FIELD - 1 ; iFieldSeq ++ ) { FieldInfo field = record . getField ( iFieldSeq ) ; if ( this . skipField ( field ) ) iTempError = field . initField ( bDisplayOption ) ; else iTempError = this . getNextField ( field , bDisplayOption , iMoveMode ) ; if ( iTempError != Constants . NORMAL_RETURN ) iErrorCode = iTempError ; } return iErrorCode ; } | Move the output buffer to all the fields . This is a utility method that populates the record . |
16,826 | public int bufferToFields ( FieldList record , int iFieldsTypes , boolean bDisplayOption , int iMoveMode ) { m_iFieldsTypes = iFieldsTypes ; return this . bufferToFields ( record , bDisplayOption , iMoveMode ) ; } | Move the output buffer to all the fields . This is the same as the bufferToFields method specifying the fieldTypes to move . |
16,827 | public void fieldsToBuffer ( FieldList record , int iFieldsTypes ) { m_iFieldsTypes = iFieldsTypes ; if ( this . getHeaderCount ( ) == 0 ) this . clearBuffer ( ) ; int fieldCount = record . getFieldCount ( ) ; for ( int iFieldSeq = Constants . MAIN_FIELD ; iFieldSeq <= fieldCount + Constants . MAIN_FIELD - 1 ; iFieldSeq ++ ) { FieldInfo field = record . getField ( iFieldSeq ) ; if ( ! this . skipField ( field ) ) this . addNextField ( field ) ; } this . finishBuffer ( ) ; } | Move all the fields to the output buffer . This is the same as the fieldsToBuffer method specifying the fieldTypes to move . |
16,828 | public boolean skipField ( FieldInfo field ) { boolean bSkipField = true ; if ( ( m_iFieldsTypes & DATA_TYPE_MASK ) == ALL_FIELDS ) bSkipField = false ; if ( ( m_iFieldsTypes & DATA_TYPE_MASK ) == SELECTED_FIELDS ) if ( field . isSelected ( ) ) bSkipField = false ; if ( ( m_iFieldsTypes & DATA_TYPE_MASK ) == PHYSICAL_FIELDS ) if ( ! field . isVirtual ( ) ) bSkipField = false ; if ( ( m_iFieldsTypes & DATA_TYPE_MASK ) == DATA_FIELDS ) if ( field . isSelected ( ) ) if ( ! field . isVirtual ( ) ) bSkipField = false ; return bSkipField ; } | Do I skip this field based on the m_iFieldsTypes flag? |
16,829 | public boolean compareToBuffer ( FieldList record ) { boolean bBufferEqual = true ; this . resetPosition ( ) ; int iFieldCount = record . getFieldCount ( ) ; for ( int iFieldSeq = Constants . MAIN_FIELD ; iFieldSeq <= iFieldCount + Constants . MAIN_FIELD - 1 ; iFieldSeq ++ ) { FieldInfo field = record . getField ( iFieldSeq ) ; if ( ! this . skipField ( field ) ) bBufferEqual = this . compareNextToField ( field ) ; if ( ! bBufferEqual ) break ; } return bBufferEqual ; } | Compare this output buffer to all the fields . This is a utility method that compares the record . |
16,830 | public boolean compareNextToField ( FieldInfo field ) { Object objNext = this . getNextData ( ) ; if ( objNext == DATA_ERROR ) return false ; if ( objNext == DATA_EOF ) return false ; if ( objNext == DATA_SKIP ) return true ; Object objField = field . getData ( ) ; if ( ( objNext == null ) || ( objField == null ) ) { if ( ( objNext == null ) && ( objField == null ) ) return true ; return false ; } return objNext . equals ( objField ) ; } | Compare this fields with the next data in the buffer . This is a utility method that compares the record . |
16,831 | public String getNextString ( ) { Object data = this . getNextData ( ) ; if ( data instanceof String ) return ( String ) data ; return null ; } | Get next next string . |
16,832 | private void init ( ) throws IndexerException { if ( ! loaded ) { loaded = true ; String storageType = config . getString ( null , "storage" , "type" ) ; try { storage = PluginManager . getStorage ( storageType ) ; storage . init ( config . toString ( ) ) ; } catch ( PluginException pe ) { throw new IndexerException ( pe ) ; } usernameMap = new HashMap < String , String > ( ) ; passwordMap = new HashMap < String , String > ( ) ; solr = initCore ( "solr" ) ; anotar = initCore ( "anotar" ) ; solrServerMap = new HashMap < String , SolrServer > ( ) ; JsonObject indexerConfig = config . getObject ( "indexer" ) ; List < String > hardcodedValues = Arrays . asList ( "type" , "properties" , "useCache" , "buffer" , "solr" , "anotar" ) ; for ( Object key : indexerConfig . keySet ( ) ) { if ( key instanceof String ) { String keyString = ( String ) key ; if ( ! hardcodedValues . contains ( keyString ) ) { solrServerMap . put ( keyString , initCore ( keyString ) ) ; } } } anotarAutoCommit = config . getBoolean ( true , "indexer" , "anotar" , "autocommit" ) ; propertiesId = config . getString ( DEFAULT_METADATA_PAYLOAD , "indexer" , "propertiesId" ) ; customParams = new HashMap < String , String > ( ) ; scriptCache = new HashMap < String , PyObject > ( ) ; groovyScriptCache = new HashMap < String , String > ( ) ; configCache = new HashMap < String , JsonSimpleConfig > ( ) ; useCache = config . getBoolean ( true , "indexer" , "useCache" ) ; } loaded = true ; } | Private method wrapped by the above two methods to perform the actual initialization after the JSON config is accessed . |
16,833 | public void search ( SearchRequest request , OutputStream response , String format ) throws IndexerException { SolrSearcher searcher = new SolrSearcher ( ( ( CommonsHttpSolrServer ) solr ) . getBaseURL ( ) ) ; String username = usernameMap . get ( "solr" ) ; String password = passwordMap . get ( "solr" ) ; if ( username != null && password != null ) { searcher . authenticate ( username , password ) ; } InputStream result ; try { request . addParam ( "wt" , format ) ; result = searcher . get ( request . getQuery ( ) , request . getParamsMap ( ) , false ) ; IOUtils . copy ( result , response ) ; result . close ( ) ; } catch ( IOException ioe ) { throw new IndexerException ( ioe ) ; } } | Perform a Solr search and stream the results into the provided output format |
16,834 | public void remove ( String oid ) throws IndexerException { log . debug ( "Deleting " + oid + " from index" ) ; try { solr . deleteByQuery ( "storage_id:\"" + oid + "\"" ) ; solr . commit ( ) ; } catch ( SolrServerException sse ) { throw new IndexerException ( sse ) ; } catch ( IOException ioe ) { throw new IndexerException ( ioe ) ; } } | Remove the specified object from the index |
16,835 | public void annotateRemove ( String oid ) throws IndexerException { log . debug ( "Deleting " + oid + " from Anotar index" ) ; try { anotar . deleteByQuery ( "rootUri:\"" + oid + "\"" ) ; anotar . commit ( ) ; } catch ( SolrServerException sse ) { throw new IndexerException ( sse ) ; } catch ( IOException ioe ) { throw new IndexerException ( ioe ) ; } } | Remove all annotations from the index against an object |
16,836 | public void index ( String oid ) throws IndexerException { try { DigitalObject object = storage . getObject ( oid ) ; String [ ] oldManifest = { } ; oldManifest = object . getPayloadIdList ( ) . toArray ( oldManifest ) ; for ( String payloadId : oldManifest ) { Payload payload = object . getPayload ( payloadId ) ; if ( ! payload . getLabel ( ) . matches ( "version_tfpackage_.*" ) ) { index ( object , payload ) ; } } } catch ( StorageException ex ) { throw new IndexerException ( ex ) ; } } | Index an object and all of its payloads |
16,837 | private String indexByGroovyScript ( DigitalObject object , Payload payload , String confOid , String rulesOid , Properties props ) throws RuleException { try { if ( engine == null ) { SimpleBindings bindings = new SimpleBindings ( ) ; ScriptEngineManager manager = new ScriptEngineManager ( ) ; engine = manager . getEngineByName ( "groovy" ) ; } JsonSimpleConfig jsonConfig = getConfigFile ( confOid ) ; SimpleBindings bindings = new SimpleBindings ( ) ; Map < String , List < String > > fields = new HashMap < String , List < String > > ( ) ; bindings . put ( "fields" , fields ) ; bindings . put ( "jsonConfig" , jsonConfig ) ; bindings . put ( "indexer" , this ) ; bindings . put ( "object" , object ) ; bindings . put ( "payload" , payload ) ; bindings . put ( "params" , props ) ; bindings . put ( "log" , log ) ; Reader script = getGroovyObject ( rulesOid ) ; engine . setBindings ( bindings , ScriptContext . ENGINE_SCOPE ) ; SolrInputDocument document = ( SolrInputDocument ) engine . eval ( script ) ; StringWriter documentString = new StringWriter ( ) ; ClientUtils . writeXML ( document , documentString ) ; return documentString . toString ( ) ; } catch ( Exception e ) { throw new RuleException ( e ) ; } } | Index a payload using the provided data using a groovy script |
16,838 | public void sendIndexToBuffer ( String index , Map < String , List < String > > fields ) { String doc = pyUtils . solrDocument ( fields ) ; addToBuffer ( index , doc ) ; } | Send the document to buffer directly |
16,839 | private void sendToIndex ( String message ) { try { getMessaging ( ) . queueMessage ( SolrWrapperQueueConsumer . QUEUE_ID , message ) ; } catch ( MessagingException ex ) { log . error ( "Unable to send message: " , ex ) ; } } | To put events to subscriber queue |
16,840 | private void annotate ( DigitalObject object , Payload payload ) throws IndexerException { String pid = payload . getId ( ) ; if ( propertiesId . equals ( pid ) ) { return ; } try { Properties props = new Properties ( ) ; props . setProperty ( "metaPid" , pid ) ; String doc = indexByPythonScript ( object , payload , null , ANOTAR_RULES_OID , props ) ; if ( doc != null ) { doc = "<add>" + doc + "</add>" ; anotar . request ( new DirectXmlRequest ( "/update" , doc ) ) ; if ( anotarAutoCommit ) { anotar . commit ( ) ; } } } catch ( Exception e ) { log . error ( "Indexing failed!\n-----\n" , e ) ; } } | Index a specific annotation |
16,841 | private String indexByPythonScript ( DigitalObject object , Payload payload , String confOid , String rulesOid , Properties props ) throws IOException , RuleException { try { JsonSimpleConfig jsonConfig = getConfigFile ( confOid ) ; Map < String , Object > bindings = new HashMap < String , Object > ( ) ; Map < String , List < String > > fields = new HashMap < String , List < String > > ( ) ; bindings . put ( "fields" , fields ) ; bindings . put ( "jsonConfig" , jsonConfig ) ; bindings . put ( "indexer" , this ) ; bindings . put ( "object" , object ) ; bindings . put ( "payload" , payload ) ; bindings . put ( "params" , props ) ; bindings . put ( "pyUtils" , getPyUtils ( ) ) ; bindings . put ( "log" , log ) ; PyObject script = getPythonObject ( rulesOid ) ; if ( script . __findattr__ ( SCRIPT_ACTIVATE_METHOD ) != null ) { script . invoke ( SCRIPT_ACTIVATE_METHOD , Py . java2py ( bindings ) ) ; object . close ( ) ; } else { log . warn ( "Activation method not found!" ) ; } return getPyUtils ( ) . solrDocument ( fields ) ; } catch ( Exception e ) { throw new RuleException ( e ) ; } } | Index a payload using the provided data using a python script |
16,842 | private PyObject getPythonObject ( String oid ) { PyObject rulesObject = deCachePythonObject ( oid ) ; if ( rulesObject != null ) { return rulesObject ; } InputStream inStream ; if ( oid . equals ( ANOTAR_RULES_OID ) ) { inStream = getClass ( ) . getResourceAsStream ( "/anotar.py" ) ; log . debug ( "First time parsing rules script: 'ANOTAR'" ) ; rulesObject = evalScript ( inStream , "anotar.py" ) ; cachePythonObject ( oid , rulesObject ) ; return rulesObject ; } else { DigitalObject object ; Payload payload ; try { object = storage . getObject ( oid ) ; String scriptName = object . getSourceId ( ) ; payload = object . getPayload ( scriptName ) ; inStream = payload . open ( ) ; log . debug ( "First time parsing rules script: '{}'" , oid ) ; rulesObject = evalScript ( inStream , scriptName ) ; payload . close ( ) ; cachePythonObject ( oid , rulesObject ) ; return rulesObject ; } catch ( StorageException ex ) { log . error ( "Rules file could not be retrieved! '{}'" , oid , ex ) ; return null ; } } } | Evaluate the rules file stored under the provided object ID . If caching is configured the compiled python object will be cached to speed up subsequent access . |
16,843 | private JsonSimpleConfig getConfigFile ( String oid ) { if ( oid == null ) { return null ; } JsonSimpleConfig configFile = deCacheConfig ( oid ) ; if ( configFile != null ) { return configFile ; } try { DigitalObject object = storage . getObject ( oid ) ; Payload payload = object . getPayload ( object . getSourceId ( ) ) ; log . debug ( "First time parsing config file: '{}'" , oid ) ; configFile = new JsonSimpleConfig ( payload . open ( ) ) ; payload . close ( ) ; cacheConfig ( oid , configFile ) ; return configFile ; } catch ( IOException ex ) { log . error ( "Rules file could not be parsed! '{}'" , oid , ex ) ; return null ; } catch ( StorageException ex ) { log . error ( "Rules file could not be retrieved! '{}'" , oid , ex ) ; return null ; } } | Retrieve and parse the config file stored under the provided object ID . If caching is configured the instantiated config object will be cached to speed up subsequent access . |
16,844 | private PyObject evalScript ( InputStream inStream , String scriptName ) { PythonInterpreter python = new PythonInterpreter ( ) ; python . execfile ( inStream , scriptName ) ; PyObject scriptClass = python . get ( SCRIPT_CLASS_NAME ) ; python . cleanup ( ) ; return scriptClass . __call__ ( ) ; } | Evaluate and return a Python script . |
16,845 | private void cachePythonObject ( String oid , PyObject pyObject ) { if ( useCache && pyObject != null ) { scriptCache . put ( oid , pyObject ) ; } } | Add a python object to the cache if caching if configured |
16,846 | private PyObject deCachePythonObject ( String oid ) { if ( useCache && scriptCache . containsKey ( oid ) ) { return scriptCache . get ( oid ) ; } return null ; } | Return a python object from the cache if configured |
16,847 | private void cacheConfig ( String oid , JsonSimpleConfig config ) { if ( useCache && config != null ) { configCache . put ( oid , config ) ; } } | Add a config class to the cache if caching if configured |
16,848 | private JsonSimpleConfig deCacheConfig ( String oid ) { if ( useCache && configCache . containsKey ( oid ) ) { return configCache . get ( oid ) ; } return null ; } | Return a config class from the cache if configured |
16,849 | public static Stopwatch create ( VoidCallable callable ) { Stopwatch stopwatch = new Stopwatch ( ) ; stopwatch . callable = callable ; return stopwatch ; } | Creates Stopwatch around passed callable . |
16,850 | public static Stopwatch createStarted ( VoidCallable callable ) { Stopwatch stopwatch = new Stopwatch ( ) ; stopwatch . callable = callable ; stopwatch . start ( ) ; return stopwatch ; } | Creates Stopwatch around passed callable and invokes callable . |
16,851 | public Stopwatch start ( ) { nanosStart = System . nanoTime ( ) ; callable . call ( ) ; ended = true ; nanosEnd = System . nanoTime ( ) ; return this ; } | Invokes passed callable and measures time . |
16,852 | public static RenamedPathResource renameResource ( String path , Resource . Readable resource ) { return new RenamedPathResource ( path , resource ) ; } | Create a resource with alternate name |
16,853 | public static < R extends Resource > Optional < R > findResource ( Stream < R > stream , String path ) { return findFirstResource ( stream . filter ( r -> r . getPath ( ) . equals ( path ) ) ) ; } | Finds the first resource in stream that matches given path . |
16,854 | public Reason wait ( T waiter ) { return wait ( waiter , Long . MAX_VALUE , TimeUnit . MILLISECONDS ) ; } | Adds waiter to queue and waits until releaseAll method call or thread is interrupted . |
16,855 | public void moveThisFile ( LineNumberReader reader , File fileDestDir , String strDestName ) { try { File fileDest = new File ( fileDestDir , strDestName ) ; fileDest . createNewFile ( ) ; FileOutputStream fileOut = new FileOutputStream ( fileDest ) ; m_writer = new PrintWriter ( fileOut ) ; this . moveSourceToDest ( reader , m_writer ) ; m_writer . close ( ) ; fileOut . close ( ) ; } catch ( FileNotFoundException ex ) { ex . printStackTrace ( ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } } | MoveThisFile Method . |
16,856 | public void free ( ) { super . free ( ) ; try { if ( m_con != null ) m_con . close ( ) ; } catch ( SOAPException ex ) { ex . printStackTrace ( ) ; } } | Free all the resources belonging to this class . |
16,857 | public SOAPMessage setSOAPBody ( SOAPMessage msg , BaseMessage message ) { try { if ( msg == null ) msg = fac . createMessage ( ) ; SOAPPart soappart = msg . getSOAPPart ( ) ; SOAPEnvelope envelope = soappart . getEnvelope ( ) ; SOAPBody body = envelope . getBody ( ) ; DOMResult result = new DOMResult ( body ) ; if ( ( ( BaseXmlTrxMessageOut ) message . getExternalMessage ( ) ) . copyMessageToResult ( result ) ) { msg . saveChanges ( ) ; return msg ; } } catch ( Throwable e ) { e . printStackTrace ( ) ; Utility . getLogger ( ) . warning ( "Error in constructing or sending message " + e . getMessage ( ) ) ; } return null ; } | This utility method sticks this message into this soap message s body . |
16,858 | public SOAPElement getElement ( SOAPElement element , String strElementName ) { Iterator < ? > iterator = element . getChildElements ( ) ; while ( iterator . hasNext ( ) ) { javax . xml . soap . Node elMessageType = ( javax . xml . soap . Node ) iterator . next ( ) ; if ( elMessageType instanceof SOAPElement ) { if ( strElementName == null ) return ( SOAPElement ) elMessageType ; if ( strElementName . equalsIgnoreCase ( ( ( SOAPElement ) elMessageType ) . getElementName ( ) . getLocalName ( ) ) ) return ( SOAPElement ) elMessageType ; } } return null ; } | Get the element . |
16,859 | public static String messageToString ( SOAPMessage soapMessage ) { String strTextMessage = null ; if ( soapMessage != null ) { try { ByteArrayOutputStream ba = new ByteArrayOutputStream ( ) ; PrintStream os = new PrintStream ( ba ) ; soapMessage . writeTo ( os ) ; os . flush ( ) ; ByteArrayInputStream is = new ByteArrayInputStream ( ba . toByteArray ( ) ) ; Reader reader = new InputStreamReader ( is ) ; BufferedReader br = new BufferedReader ( reader ) ; StringBuffer sb = new StringBuffer ( ) ; String string = null ; while ( ( string = br . readLine ( ) ) != null ) { sb . append ( string ) ; sb . append ( '\n' ) ; } strTextMessage = sb . toString ( ) ; } catch ( SOAPException ex ) { ex . printStackTrace ( ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } } return strTextMessage ; } | Convert this SOAP message to a text string . |
16,860 | public void printSource ( Source src , PrintStream out ) { TransformerFactory tFact = TransformerFactory . newInstance ( ) ; try { Transformer transformer = tFact . newTransformer ( ) ; Result result = new StreamResult ( out ) ; transformer . transform ( src , result ) ; } catch ( TransformerConfigurationException ex ) { ex . printStackTrace ( ) ; } catch ( TransformerException ex ) { ex . printStackTrace ( ) ; } } | A utility method to print this source tree to the given stream . |
16,861 | public File downloadFileNew ( File inputUrl , File outputFile ) { OutputStream out = null ; InputStream fis = null ; HttpParams httpParameters = new BasicHttpParams ( ) ; int timeoutConnection = 2500 ; HttpConnectionParams . setConnectionTimeout ( httpParameters , timeoutConnection ) ; int timeoutSocket = 2500 ; HttpConnectionParams . setSoTimeout ( httpParameters , timeoutSocket ) ; File dir = outputFile . getParentFile ( ) ; dir . mkdirs ( ) ; try { HttpGet httpRequest = new HttpGet ( stringFromFile ( inputUrl ) ) ; DefaultHttpClient httpClient = new DefaultHttpClient ( httpParameters ) ; HttpResponse response = httpClient . execute ( httpRequest ) ; int statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; if ( statusCode == HttpStatus . SC_OK ) { HttpEntity entity = response . getEntity ( ) ; out = new BufferedOutputStream ( new FileOutputStream ( outputFile ) ) ; long total = entity . getContentLength ( ) ; fis = entity . getContent ( ) ; if ( total > 1 || true ) startTalker ( total ) ; else { throw new IOException ( "Content null" ) ; } long progress = 0 ; byte [ ] buffer = new byte [ 1024 ] ; int length = 0 ; while ( ( length = fis . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , length ) ; progressTalker ( length ) ; progress += length ; } finishTalker ( progress ) ; } } catch ( Exception e ) { cancelTalker ( e ) ; e . printStackTrace ( ) ; return null ; } finally { try { if ( out != null ) { out . flush ( ) ; out . close ( ) ; } if ( fis != null ) fis . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return outputFile ; } | still has issues ... |
16,862 | public void contextInitialized ( ServletContextEvent event ) { this . event = event ; this . serverContainer = getServerContainer ( event ) ; super . contextInitialized ( event ) ; } | On contextInitialized additional obtain the WebSocket ServerContainer . |
16,863 | protected ServerContainer getServerContainer ( ServletContextEvent servletContextEvent ) { ServletContext context = servletContextEvent . getServletContext ( ) ; return ( ServerContainer ) context . getAttribute ( "javax.websocket.server.ServerContainer" ) ; } | Return the WebSocket ServerContainer from the servletContext . |
16,864 | private void registerWebSockets ( Injector injector ) { Map < Key < ? > , Binding < ? > > allBindings = injector . getAllBindings ( ) ; for ( Map . Entry < Key < ? > , Binding < ? > > entry : allBindings . entrySet ( ) ) { final Binding < ? > binding = entry . getValue ( ) ; binding . acceptScopingVisitor ( new DefaultBindingScopingVisitor ( ) { public Object visitEagerSingleton ( ) { registerWebSocketEndpoint ( binding ) ; return null ; } } ) ; } } | Find any Guice eager singletons that are WebSocket endpoints and register them with the servlet container . |
16,865 | protected void registerWebSocketEndpoint ( Binding < ? > binding ) { Object instance = binding . getProvider ( ) . get ( ) ; Class < ? > instanceClass = instance . getClass ( ) ; ServerEndpoint serverEndpoint = instanceClass . getAnnotation ( ServerEndpoint . class ) ; if ( serverEndpoint != null ) { try { log . debug ( "registering ServerEndpoint [{}] with servlet container" , instanceClass ) ; BasicWebSocketConfigurator configurator = new BasicWebSocketConfigurator ( instance ) ; serverContainer . addEndpoint ( new BasicWebSocketEndpointConfig ( instanceClass , serverEndpoint , configurator ) ) ; } catch ( Exception e ) { log . error ( "Error registering WebSocket Singleton " + instance + " with the servlet container" , e ) ; } } } | Check if the binding is a WebSocket endpoint . If it is then register the webSocket server endpoint with the servlet container . |
16,866 | public Map < String , Object > addConfigProperty ( Map < String , Object > properties , String key , String defaultValue ) { if ( this . getProperty ( key ) != null ) properties . put ( key , this . getProperty ( key ) ) ; else if ( defaultValue != null ) properties . put ( key , defaultValue ) ; return properties ; } | Add this property if it exists in the OSGi config file . |
16,867 | protected List < String > getTopicIds ( ) { LinkedList < String > topicIds = new LinkedList < String > ( ) ; for ( final Entry < String , SpecTopic > specTopicEntry : topics . entrySet ( ) ) { topicIds . add ( specTopicEntry . getKey ( ) ) ; } return topicIds ; } | Gets all of the Content Specification Unique Topic ID s that are used in the process . |
16,868 | public void appendSpecTopic ( final SpecTopic specTopic ) { topics . add ( specTopic ) ; nodes . add ( specTopic ) ; if ( specTopic . getParent ( ) != null && specTopic . getParent ( ) instanceof Level ) { ( ( Level ) specTopic . getParent ( ) ) . removeSpecTopic ( specTopic ) ; } specTopic . setParent ( this ) ; } | Adds a Content Specification Topic to the Level . If the Topic already has a parent then it is removed from that parent and added to this level . |
16,869 | public void appendChild ( final Node child ) { if ( child instanceof Level ) { levels . add ( ( Level ) child ) ; nodes . add ( child ) ; if ( child . getParent ( ) != null ) { child . removeParent ( ) ; } child . setParent ( this ) ; } else if ( child instanceof SpecTopic ) { appendSpecTopic ( ( SpecTopic ) child ) ; } else if ( child instanceof CommonContent ) { commonContents . add ( ( CommonContent ) child ) ; nodes . add ( child ) ; if ( child . getParent ( ) != null ) { child . removeParent ( ) ; } child . setParent ( this ) ; } else { nodes . add ( child ) ; if ( child . getParent ( ) != null ) { child . removeParent ( ) ; } child . setParent ( this ) ; } } | Adds a Child Element to the Level . If the Child Element already has a parent then it is removed from that parent and added to this level . |
16,870 | public void removeChild ( final Node child ) { if ( child instanceof Level ) { levels . remove ( child ) ; nodes . remove ( child ) ; child . setParent ( null ) ; } else if ( child instanceof SpecTopic ) { removeSpecTopic ( ( SpecTopic ) child ) ; } else if ( child instanceof CommonContent ) { commonContents . remove ( child ) ; nodes . remove ( child ) ; child . setParent ( null ) ; } else { nodes . remove ( child ) ; child . setParent ( null ) ; } } | Removes a Child element from the level and removes the level as the Child s parent . |
16,871 | public boolean insertBefore ( final Node newNode , final Node oldNode ) { if ( oldNode == null || newNode == null ) { return false ; } int index = nodes . indexOf ( oldNode ) ; if ( index != - 1 ) { if ( newNode . getParent ( ) != null ) { newNode . removeParent ( ) ; } newNode . setParent ( this ) ; if ( newNode instanceof Level ) { levels . add ( ( Level ) newNode ) ; } else if ( newNode instanceof SpecTopic ) { topics . add ( ( SpecTopic ) newNode ) ; } if ( index == 0 ) { nodes . addFirst ( newNode ) ; } else { nodes . add ( index - 1 , newNode ) ; } return true ; } else { return false ; } } | Inserts a node before the another node in the level . |
16,872 | protected Integer getTotalNumberOfChildren ( ) { Integer numChildrenNodes = 0 ; for ( Level childLevel : levels ) { numChildrenNodes += childLevel . getTotalNumberOfChildren ( ) ; } return nodes . size ( ) + numChildrenNodes ; } | Gets the total number of Children nodes for the level and its child levels . |
16,873 | public boolean hasSpecTopics ( ) { if ( getSpecTopics ( ) . size ( ) > 0 ) { return true ; } for ( final Level childLevel : levels ) { if ( childLevel . hasSpecTopics ( ) ) { return true ; } } return false ; } | Checks to see if this level or any of its children contain SpecTopics . |
16,874 | public boolean hasCommonContents ( ) { if ( getNumberOfCommonContents ( ) > 0 ) { return true ; } for ( final Level childLevel : levels ) { if ( childLevel . hasCommonContents ( ) ) { return true ; } } return false ; } | Checks to see if this level or any of its children contain CommonContent . |
16,875 | public boolean hasRevisionSpecTopics ( ) { for ( final SpecTopic specTopic : getSpecTopics ( ) ) { if ( specTopic . getRevision ( ) != null ) { return true ; } } for ( final Level childLevel : getChildLevels ( ) ) { if ( childLevel . hasRevisionSpecTopics ( ) ) { return true ; } } return false ; } | Checks to see if this level or any of its children contain SpecTopics that represent a revision . |
16,876 | public boolean isSpecNodeInLevelByTargetID ( final String targetId ) { final SpecNode foundTopic = getClosestSpecNodeByTargetId ( targetId , false ) ; return foundTopic != null ; } | Checks to see if a SpecNode exists within this level or its children . |
16,877 | public static < T > T loadFromXMLFile ( Class < T > configClass , File file ) throws Exception { Persister persister = new Persister ( ) ; return persister . read ( configClass , file ) ; } | Loads config values from XML file maps them to configuration class fields and returns the result instance . |
16,878 | protected final boolean compareKeys ( K k1 , K k2 ) { return k1 == k2 || ( k1 != null && k1 . equals ( k2 ) ) ; } | Basic logic to compare two keys for equality |
16,879 | public String processInterfaceType ( DescriptionType descriptionType , InterfaceType interfaceType , boolean addAddress ) { String interfaceName = interfaceType . getName ( ) ; String allAddress = DBConstants . BLANK ; for ( Object nextElement : interfaceType . getOperationOrFaultOrFeature ( ) ) { Object interfaceOperationType = null ; if ( nextElement instanceof JAXBElement ) interfaceOperationType = ( ( JAXBElement ) nextElement ) . getValue ( ) ; if ( interfaceOperationType instanceof InterfaceOperationType ) { String address = this . processInterfaceOperationType ( descriptionType , interfaceName , ( InterfaceOperationType ) interfaceOperationType , addAddress ) ; if ( allAddress != null ) { if ( allAddress == DBConstants . BLANK ) allAddress = address ; else if ( ! allAddress . equalsIgnoreCase ( address ) ) allAddress = null ; } } } return allAddress ; } | ProcessInterfaceType Method . |
16,880 | public RemoteReceiveQueue createRemoteReceiveQueue ( String strQueueName , String strQueueType ) throws RemoteException { BaseTransport transport = this . createProxyTransport ( CREATE_REMOTE_RECEIVE_QUEUE ) ; transport . addParam ( MessageConstants . QUEUE_NAME , strQueueName ) ; transport . addParam ( MessageConstants . QUEUE_TYPE , strQueueType ) ; String strID = ( String ) transport . sendMessageAndGetReply ( ) ; return new ReceiveQueueProxy ( this , strID ) ; } | Create a new remote receive queue . |
16,881 | public RemoteSendQueue createRemoteSendQueue ( String strQueueName , String strQueueType ) throws RemoteException { BaseTransport transport = this . createProxyTransport ( CREATE_REMOTE_SEND_QUEUE ) ; transport . addParam ( MessageConstants . QUEUE_NAME , strQueueName ) ; transport . addParam ( MessageConstants . QUEUE_TYPE , strQueueType ) ; String strID = ( String ) transport . sendMessageAndGetReply ( ) ; return new SendQueueProxy ( this , strID ) ; } | Create a new remote send queue . |
16,882 | public void put ( Object objValue ) { Class < ? > classData = this . getNativeClassType ( ) ; try { objValue = DataConverters . convertObjectToDatatype ( objValue , classData , null ) ; } catch ( Exception ex ) { objValue = null ; } if ( this . getMessage ( ) != null ) this . getMessage ( ) . putNative ( this . getFullKey ( null ) , objValue ) ; } | Put the value for this param in the map . If it is not the correct object type convert it first . |
16,883 | public void putString ( String strValue ) { Class < ? > classData = this . getNativeClassType ( ) ; Object objValue = null ; try { objValue = DataConverters . convertObjectToDatatype ( strValue , classData , null ) ; } catch ( Exception ex ) { objValue = null ; } if ( this . getMessage ( ) != null ) this . getMessage ( ) . putNative ( this . getFullKey ( null ) , objValue ) ; } | Convert this external data format to the raw object and put it in the map . Typically this method is overridden to handle specific params . |
16,884 | public static X509Certificate getCertfromPEM ( String certFile ) throws IOException , CertificateException , NoSuchProviderException { InputStream inStrm = new FileInputStream ( certFile ) ; X509Certificate cert = getCertfromPEM ( inStrm ) ; return cert ; } | Reads a certificate in PEM - format from a file . The file may contain other things the first certificate in the file is read . |
16,885 | public static X509Certificate getCertfromPEM ( byte [ ] pemBytes ) throws IOException , CertificateException , NoSuchProviderException { InputStream inStrm = new java . io . ByteArrayInputStream ( pemBytes ) ; X509Certificate cert = getCertfromPEM ( inStrm ) ; return cert ; } | Reads a certificate in PEM - format from a byte array . The array may contain other things the first certificate in the array is read . |
16,886 | public static X509Certificate getCertfromPEM ( InputStream certStream ) throws IOException , CertificateException , NoSuchProviderException { String beginKey = "-----BEGIN CERTIFICATE-----" ; String endKey = "-----END CERTIFICATE-----" ; BufferedReader bufRdr = new BufferedReader ( new InputStreamReader ( certStream ) ) ; ByteArrayOutputStream ostr = new ByteArrayOutputStream ( ) ; PrintStream opstr = new PrintStream ( ostr ) ; String temp ; while ( ( temp = bufRdr . readLine ( ) ) != null && ! temp . equals ( beginKey ) ) continue ; if ( temp == null ) throw new IOException ( "Error in " + certStream . toString ( ) + ", missing " + beginKey + " boundary" ) ; while ( ( temp = bufRdr . readLine ( ) ) != null && ! temp . equals ( endKey ) ) opstr . print ( temp ) ; if ( temp == null ) throw new IOException ( "Error in " + certStream . toString ( ) + ", missing " + endKey + " boundary" ) ; opstr . close ( ) ; byte [ ] certbuf = Base64 . decode ( ostr . toByteArray ( ) ) ; CertificateFactory cf = CertificateFactory . getInstance ( "X.509" , "SC" ) ; X509Certificate x509cert = ( X509Certificate ) cf . generateCertificate ( new ByteArrayInputStream ( certbuf ) ) ; return x509cert ; } | Reads a certificate in PEM - format from an InputStream . The stream may contain other things the first certificate in the stream is read . |
16,887 | private boolean iRequestedHandoff ( String workUnit ) { String destinationNode = cluster . getHandoffResult ( workUnit ) ; return ( destinationNode != null ) && cluster . myWorkUnits . contains ( workUnit ) && ! destinationNode . equals ( "" ) && ! cluster . isMe ( destinationNode ) ; } | Determines if this node requested handoff of a work unit to someone else . I have requested handoff of a work unit if it s currently a member of my active set and its destination node is another node in the cluster . |
16,888 | private Runnable shutdownAfterHandoff ( final String workUnit ) { final Cluster cluster = this . cluster ; final Logger log = LOG ; return new Runnable ( ) { public void run ( ) { String str = cluster . getHandoffResult ( workUnit ) ; log . info ( "Shutting down {} following handoff to {}." , workUnit , ( str == null ) ? "(None)" : str ) ; cluster . shutdownWork ( workUnit , false ) ; if ( cluster . hasState ( NodeState . Draining ) && cluster . myWorkUnits . isEmpty ( ) ) { cluster . shutdown ( ) ; } } } ; } | Builds a runnable to shut down a work unit after a configurable delay once handoff has completed . If the cluster has been instructed to shut down and the last work unit has been handed off this task also directs this Ordasity instance to shut down . |
16,889 | public void finishHandoff ( final String workUnit ) throws InterruptedException { String unitId = cluster . workUnitMap . get ( workUnit ) ; LOG . info ( "Handoff of {} to me acknowledged. Deleting claim ZNode for {} and waiting for {} to shutdown work." , workUnit , workUnit , ( ( unitId == null ) ? "(None)" : unitId ) ) ; final String path = cluster . workUnitClaimPath ( workUnit ) ; Stat stat = ZKUtils . exists ( cluster . zk , path , new Watcher ( ) { public void process ( WatchedEvent event ) { completeHandoff ( workUnit , path ) ; } } ) ; if ( stat == null ) { LOG . warn ( "Peer already deleted znode of {}" , workUnit ) ; completeHandoff ( workUnit , path ) ; } } | Completes the process of handing off a work unit from one node to the current one . Attempts to establish a final claim to the node handed off to me in ZooKeeper and repeats execution of the task every two seconds until it is complete . |
16,890 | public static SSLServerSocketChannel open ( SocketAddress address ) throws IOException { try { return open ( address , SSLContext . getDefault ( ) ) ; } catch ( NoSuchAlgorithmException ex ) { throw new IOException ( ex ) ; } } | Creates and binds SSLServerSocketChannel using default SSLContext . |
16,891 | public static Hash merge ( Hash a , Hash b ) { try { MessageDigest digest = MessageDigest . getInstance ( "SHA-256" ) ; digest . update ( a . bytes ) ; return Hash . createFromSafeArray ( digest . digest ( digest . digest ( b . bytes ) ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } } | Merge two Hashes into one for Merkle Tree calculation |
16,892 | public static byte [ ] hash ( byte [ ] data , int offset , int len ) { try { MessageDigest a = MessageDigest . getInstance ( "SHA-256" ) ; a . update ( data , offset , len ) ; return a . digest ( ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } } | SHA256 hash of arbitrary data |
16,893 | public String toUuidString ( ) { String [ ] items = new String [ ] { contentAsHex ( 0 , 4 ) , contentAsHex ( 4 , 6 ) , contentAsHex ( 6 , 8 ) , contentAsHex ( 8 , 10 ) , contentAsHex ( 10 , 16 ) } ; String result = StringUtils . join ( items , "-" ) ; return result . toLowerCase ( ) ; } | UUID created from the first 128 bits of SHA256 |
16,894 | public static MutableTimecode valueOf ( String timecode ) throws IllegalArgumentException { MutableTimecode tc = new MutableTimecode ( ) ; return ( MutableTimecode ) tc . parse ( timecode ) ; } | Returns a MutableTimecode instance for given Timecode storage string . Will return an invalid timecode in case the storage string represents an invalid Timecode |
16,895 | protected DoubleMatrix getMatrix ( int n ) { Map < Integer , DoubleMatrix > degreeMap = matrixCache . get ( this . getClass ( ) ) ; if ( degreeMap == null ) { degreeMap = new HashMap < > ( ) ; matrixCache . put ( this . getClass ( ) , degreeMap ) ; } DoubleMatrix m = degreeMap . get ( n ) ; if ( m == null ) { m = createMatrix ( n ) ; m . decompose ( ) ; degreeMap . put ( n , m ) ; } return m ; } | Returns class cached DoubleMatrix with decompose already called . |
16,896 | protected void ignoreDuplicatedChangeItemRequests ( ) { if ( getItems ( ) != null ) { final List < RESTCSRelatedNodeCollectionItemV1 > items = new ArrayList < RESTCSRelatedNodeCollectionItemV1 > ( getItems ( ) ) ; for ( int i = 0 ; i < items . size ( ) ; ++ i ) { final RESTCSRelatedNodeCollectionItemV1 child1 = items . get ( i ) ; final RESTCSRelatedNodeV1 childItem1 = child1 . getItem ( ) ; if ( childItem1 . getId ( ) == null ) continue ; final boolean add1 = child1 . getState ( ) . equals ( ADD_STATE ) ; final boolean remove1 = child1 . getState ( ) . equals ( REMOVE_STATE ) ; final boolean update1 = child1 . getState ( ) . equals ( UPDATE_STATE ) ; for ( int j = i + 1 ; j < items . size ( ) ; ++ j ) { final RESTCSRelatedNodeCollectionItemV1 child2 = items . get ( j ) ; final RESTCSRelatedNodeV1 childItem2 = child2 . getItem ( ) ; if ( childItem2 . getId ( ) == null ) continue ; final boolean relationshipIdEqual = childItem1 . getRelationshipId ( ) == null && childItem2 . getRelationshipId ( ) == null || childItem1 . getRelationshipId ( ) != null && childItem1 . getRelationshipId ( ) . equals ( childItem2 . getRelationshipId ( ) ) ; if ( childItem1 . getId ( ) . equals ( childItem2 . getId ( ) ) && relationshipIdEqual ) { final boolean add2 = child2 . getState ( ) . equals ( ADD_STATE ) ; final boolean remove2 = child2 . getState ( ) . equals ( REMOVE_STATE ) ; final boolean update2 = child2 . getState ( ) . equals ( UPDATE_STATE ) ; final boolean typeEqual = childItem1 . getRelationshipType ( ) == null && childItem2 . getRelationshipType ( ) == null || childItem1 . getRelationshipType ( ) != null && childItem1 . getRelationshipType ( ) . equals ( childItem2 . getRelationshipType ( ) ) ; if ( ( add1 && add2 ) || ( remove1 && remove2 ) || ( update1 && update2 ) ) { if ( typeEqual ) { getItems ( ) . remove ( child1 ) ; } else { getItems ( ) . remove ( child1 ) ; getItems ( ) . remove ( child2 ) ; } } if ( ( add1 && remove2 ) || ( remove1 && add2 ) || ( update1 && remove2 ) || ( update2 && remove1 ) || ( update1 && add2 ) || ( update2 && add1 ) ) { getItems ( ) . remove ( child1 ) ; getItems ( ) . remove ( child2 ) ; } } } } } } | This method will clear out any child items that are marked for both add and remove or duplicated add and remove requests . Override this method to deal with collections where the children are not uniquely identified by only their id . |
16,897 | public int setString ( String strField , boolean bDisplayOption , int iMoveMode ) { NumberField numberField = ( NumberField ) this . getNextConverter ( ) ; int iErrorCode = super . setString ( strField , DBConstants . DONT_DISPLAY , iMoveMode ) ; if ( strField . length ( ) == 0 ) numberField . displayField ( ) ; if ( ( iErrorCode != DBConstants . NORMAL_RETURN ) || strField . length ( ) == 0 ) return iErrorCode ; double doubleValue = this . getValue ( ) ; if ( doubleValue != 0 ) doubleValue = 1 / doubleValue ; iErrorCode = this . setValue ( doubleValue , bDisplayOption , DBConstants . SCREEN_MOVE ) ; return iErrorCode ; } | Convert and move string to this field . Get the recriprical of this string and set the string . |
16,898 | public static WorkQueue getWorkQueue ( Type type , int nThreads ) { switch ( type ) { case Simple : return new SimpleWorkQueue ( nThreads ) ; case Multi : return new MultiWorkQueue ( nThreads ) ; default : return new MultiWorkQueue ( nThreads ) ; } } | Returns a thread - backed queue . |
16,899 | public void run ( ) { if ( ! state . compareAndSet ( State . CREATED , State . PENDING ) ) { throw new IllegalStateException ( "Can only run a promise in the CREATED state" ) ; } T result ; try { result = supplier . get ( ) ; state . set ( State . COMPLETED ) ; observer . next ( result ) ; observer . completed ( true ) ; } catch ( Exception e ) { state . set ( State . ERROR ) ; observer . error ( e ) ; observer . completed ( false ) ; } observer = null ; } | This method calls the supplier and on successful completion informs the fulfilled consumers of the return value . If the supplier throws an exception the rejected consumers are informed . In either case when the call to the supplier completes the settled consumers are informed with an Optional containing the supplied value on success . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.