idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
22,700 | protected static void appendNameAndParameters ( StringBuilder sb , String name , List < Expression > parameters ) { sb . append ( name ) ; sb . append ( "(" ) ; boolean first = true ; for ( Expression expr : parameters ) { if ( ! first ) { sb . append ( ", " ) ; } first = false ; sb . append ( expr ) ; } sb . append ( ")" ) ; } | Appends the name and parameters to the given string builder . |
22,701 | public Expression getExpectedParam ( int index ) { if ( parameters . size ( ) <= index ) { throw new IllegalArgumentException ( "Parameter index out of bounds: " + index + ". Function call: " + this ) ; } return parameters . get ( index ) ; } | Returns the parameter at the expected index . |
22,702 | public Expression get ( String name ) { if ( variables . containsKey ( name ) ) { return variables . get ( name ) ; } if ( parent == null ) { return new Value ( "" ) ; } return parent . get ( name ) ; } | Returns the value previously set for the given variable . |
22,703 | public DuplicationReport monitorDuplication ( ) { log . info ( "starting duplication monitor" ) ; DuplicationReport report = new DuplicationReport ( ) ; for ( String host : dupHosts . keySet ( ) ) { DuplicationInfo info = new DuplicationInfo ( host ) ; try { ContentStoreManager storeManager = getStoreManager ( host ) ; ContentStore primary = storeManager . getPrimaryContentStore ( ) ; String primaryStoreId = primary . getStoreId ( ) ; List < ContentStore > secondaryList = getSecondaryStores ( storeManager , primaryStoreId ) ; List < String > primarySpaces = getSpaces ( host , primary ) ; countSpaces ( host , info , primary , primarySpaces , true ) ; for ( ContentStore secondary : secondaryList ) { List < String > secondarySpaces = getSpaces ( host , secondary ) ; if ( primarySpaces . size ( ) != secondarySpaces . size ( ) ) { info . addIssue ( "The spaces listings do not match " + "between primary and secondary " + "provider: " + secondary . getStorageProviderType ( ) ) ; } countSpaces ( host , info , secondary , secondarySpaces , false ) ; } compareSpaces ( primaryStoreId , info ) ; } catch ( Exception e ) { String error = e . getClass ( ) + " exception encountered while " + "running dup monitor for host " + host + ". Exception message: " + e . getMessage ( ) ; log . error ( error ) ; info . addIssue ( error ) ; } finally { report . addDupInfo ( host , info ) ; } } return report ; } | This method performs the duplication checks . These checks compare the number of content items in identically named spaces . |
22,704 | public static int calculateThreads ( final int executorThreads , final String name ) { final int optimalThreads = Math . max ( BASE_OPTIMAL_THREADS , ( Runtime . getRuntime ( ) . availableProcessors ( ) + THREAD_OVERHEAD ) ) ; int threadsChosen = optimalThreads ; if ( executorThreads > optimalThreads ) { threadsChosen = executorThreads ; LOG . warn ( "Requested more than optimal threads. This is not necessarily an error, but you may be overallocating." ) ; } else { if ( executorThreads > 0 ) { LOG . warn ( "You requested less than optimal threads. We've ignored that." ) ; } } LOG . debug ( "For factory {}, Optimal Threads {}, Configured Threads {}" , name , optimalThreads , threadsChosen ) ; return threadsChosen ; } | Calculate optimal threads . If they exceed the specified executorThreads use optimal threads instead . Emit appropriate logging |
22,705 | public final synchronized JaxRsClientFactory addFeatureToAllClients ( Class < ? extends Feature > ... features ) { return addFeatureToGroup ( PrivateFeatureGroup . WILDCARD , features ) ; } | Register a list of features for all created clients . |
22,706 | public < T > T createClientProxy ( Class < T > proxyClass , WebTarget baseTarget ) { return factory ( ctx ) . createClientProxy ( proxyClass , baseTarget ) ; } | Create a Client proxy for the given interface type . Note that different JAX - RS providers behave slightly differently for this feature . |
22,707 | public static boolean seemsToHaveSignature ( Nanopub nanopub ) { for ( Statement st : nanopub . getPubinfo ( ) ) { if ( st . getPredicate ( ) . equals ( NanopubSignatureElement . HAS_SIGNATURE_ELEMENT ) ) return true ; if ( st . getPredicate ( ) . equals ( NanopubSignatureElement . HAS_SIGNATURE_TARGET ) ) return true ; if ( st . getPredicate ( ) . equals ( NanopubSignatureElement . HAS_SIGNATURE ) ) return true ; if ( st . getPredicate ( ) . equals ( CryptoElement . HAS_PUBLIC_KEY ) ) return true ; } return false ; } | This includes legacy signatures . Might include false positives . |
22,708 | private void workflowCuration ( JsonSimple response , JsonSimple message ) { String oid = message . getString ( null , "oid" ) ; if ( ! workflowCompleted ( oid ) ) { return ; } try { JSONArray relations = mapRelations ( oid ) ; if ( relations != null ) { JsonObject request = createTask ( response , oid , "curation-request" ) ; if ( ! relations . isEmpty ( ) ) { request . put ( "relationships" , relations ) ; } } } catch ( Exception ex ) { log . error ( "Error processing relations: " , ex ) ; return ; } } | Assess a workflow event to see how it effects curation |
22,709 | private JSONArray mapRelations ( String oid ) { JsonSimple formData = parsedFormData ( oid ) ; if ( formData == null ) { log . error ( "Error parsing form data" ) ; return null ; } JsonSimple rawData = getDataFromStorage ( oid ) ; if ( rawData == null ) { log . error ( "Error reading data from storage" ) ; return null ; } JSONArray relations = rawData . writeArray ( "relationships" ) ; boolean changed = false ; for ( String baseField : relationFields . keySet ( ) ) { JsonSimple relationConfig = relationFields . get ( baseField ) ; List < String > basePath = relationConfig . getStringList ( "path" ) ; if ( basePath == null || basePath . isEmpty ( ) ) { log . error ( "Ignoring invalid relationship '{}'. No 'path'" + " provided in configuration" , baseField ) ; continue ; } Object object = formData . getPath ( basePath . toArray ( ) ) ; if ( object instanceof JsonObject ) { JsonObject newRelation = lookForRelation ( oid , baseField , relationConfig , new JsonSimple ( ( JsonObject ) object ) ) ; if ( newRelation != null && ! isKnownRelation ( relations , newRelation ) ) { log . info ( "Adding relation: '{}' => '{}'" , baseField , newRelation . get ( "identifier" ) ) ; relations . add ( newRelation ) ; changed = true ; } } if ( object instanceof JSONArray ) { for ( Object loopObject : ( JSONArray ) object ) { if ( loopObject instanceof JsonObject ) { JsonObject newRelation = lookForRelation ( oid , baseField , relationConfig , new JsonSimple ( ( JsonObject ) loopObject ) ) ; if ( newRelation != null && ! isKnownRelation ( relations , newRelation ) ) { log . info ( "Adding relation: '{}' => '{}'" , baseField , newRelation . get ( "identifier" ) ) ; relations . add ( newRelation ) ; changed = true ; } } } } } if ( changed ) { try { saveObjectData ( rawData , oid ) ; } catch ( TransactionException ex ) { log . error ( "Error updating object '{}' in storage: " , oid , ex ) ; return null ; } } return relations ; } | Map all the relationships buried in this record s data |
22,710 | private boolean isKnownRelation ( JSONArray relations , JsonObject newRelation ) { if ( newRelation . containsKey ( "oid" ) ) { for ( Object relation : relations ) { JsonObject json = ( JsonObject ) relation ; String knownOid = ( String ) json . get ( "oid" ) ; String newOid = ( String ) newRelation . get ( "oid" ) ; if ( knownOid . equals ( newOid ) ) { log . debug ( "Known ReDBox linkage '{}'" , knownOid ) ; return true ; } } return false ; } for ( Object relation : relations ) { JsonObject json = ( JsonObject ) relation ; if ( json . containsKey ( "identifier" ) ) { String knownId = ( String ) json . get ( "identifier" ) ; String knownField = ( String ) json . get ( "field" ) ; String newId = ( String ) newRelation . get ( "identifier" ) ; String newField = ( String ) newRelation . get ( "field" ) ; if ( knownId . equals ( newId ) && knownField . equals ( newField ) ) { return true ; } } } return false ; } | Test whether the field provided is already a known relationship |
22,711 | private JsonSimple publish ( JsonSimple message , String oid ) throws TransactionException { log . debug ( "Publishing '{}'" , oid ) ; JsonSimple response = new JsonSimple ( ) ; try { DigitalObject object = storage . getObject ( oid ) ; Properties metadata = object . getMetadata ( ) ; if ( ! metadata . containsKey ( PUBLISH_PROPERTY ) ) { metadata . setProperty ( PUBLISH_PROPERTY , "true" ) ; storeProperties ( object , metadata ) ; log . info ( "Publication flag set '{}'" , oid ) ; audit ( response , oid , "Publication flag set" ) ; } else { log . info ( "Publication flag is already set '{}'" , oid ) ; } } catch ( StorageException ex ) { throw new TransactionException ( "Error setting publish property: " , ex ) ; } JsonSimple itemConfig = getConfigFromStorage ( oid ) ; if ( itemConfig == null ) { log . error ( "Error accessing item configuration!" ) ; } else { List < String > list = itemConfig . getStringList ( "transformer" , "curation" ) ; if ( list != null && ! list . isEmpty ( ) ) { for ( String id : list ) { JsonObject order = newTransform ( response , id , oid ) ; JsonObject config = ( JsonObject ) order . get ( "config" ) ; JsonObject overrides = itemConfig . getObject ( "transformerOverrides" , id ) ; if ( overrides != null ) { config . putAll ( overrides ) ; } } } } publishRelations ( response , oid ) ; return response ; } | Get the requested object ready for publication . This would typically just involve setting a flag |
22,712 | private void publishRelations ( JsonSimple response , String oid ) throws TransactionException { log . debug ( "Publishing Children of '{}'" , oid ) ; JsonSimple data = getDataFromStorage ( oid ) ; if ( data == null ) { log . error ( "Error accessing item data! '{}'" , oid ) ; emailObjectLink ( response , oid , "An error occured publishing the related objects for this" + " record. Please check the system logs." ) ; return ; } JSONArray relations = data . writeArray ( "relationships" ) ; for ( Object relation : relations ) { JsonSimple json = new JsonSimple ( ( JsonObject ) relation ) ; String broker = json . getString ( null , "broker" ) ; boolean localRecord = broker . equals ( brokerUrl ) ; String relatedId = json . getString ( null , "identifier" ) ; String relatedOid = json . getString ( null , "oid" ) ; if ( relatedOid == null && localRecord ) { String identifier = json . getString ( null , "identifier" ) ; if ( identifier == null ) { log . error ( "NULL identifer provided!" ) ; } relatedOid = idToOid ( identifier ) ; if ( relatedOid == null ) { log . error ( "Cannot resolve identifer: '{}'" , identifier ) ; } } boolean authority = json . getBoolean ( false , "authority" ) ; boolean relationPublishRequested = json . getBoolean ( false , "relationPublishedRequested" ) ; if ( authority && ! relationPublishRequested ) { boolean isCurated = json . getBoolean ( false , "isCurated" ) ; if ( isCurated ) { log . debug ( " * Publishing '{}'" , relatedId ) ; if ( localRecord ) { createTask ( response , relatedOid , "publish" ) ; } else { JsonObject task = createTask ( response , broker , relatedOid , "publish" ) ; task . remove ( "oid" ) ; task . put ( "identifier" , relatedId ) ; } log . debug ( " * Writing relationPublishedRequested for '{}'" , relatedId ) ; json . getJsonObject ( ) . put ( "relationPublishedRequested" , true ) ; saveObjectData ( data , oid ) ; } else { log . debug ( " * Ignoring non-curated relationship '{}'" , relatedId ) ; } } } } | Send out requests to all relations to publish |
22,713 | private void reharvest ( JsonSimple response , JsonSimple message ) { String oid = message . getString ( null , "oid" ) ; try { if ( oid != null ) { setRenderFlag ( oid ) ; JsonSimple itemConfig = getConfigFromStorage ( oid ) ; if ( itemConfig == null ) { log . error ( "Error accessing item configuration!" ) ; return ; } itemConfig . getJsonObject ( ) . put ( "oid" , oid ) ; scheduleTransformers ( itemConfig , response ) ; JsonObject order = newIndex ( response , oid ) ; order . put ( "forceCommit" , true ) ; createTask ( response , oid , "clear-render-flag" ) ; } else { log . error ( "Cannot reharvest without an OID!" ) ; } } catch ( Exception ex ) { log . error ( "Error during reharvest setup: " , ex ) ; } } | Generate a fairly common list of orders to transform and index an object . This mirrors the traditional tool chain . |
22,714 | private void emailObjectLink ( JsonSimple response , String oid , String message ) { String link = urlBase + "default/detail/" + oid ; String text = "This is an automated message from the " ; text += "ReDBox Curation Manager.\n\n" + message ; text += "\n\nYou can find this object here:\n" + link ; email ( response , oid , text ) ; } | Generate an order to send an email to the intended recipient with a link to an object |
22,715 | private void email ( JsonSimple response , String oid , String text ) { JsonObject object = newMessage ( response , EmailNotificationConsumer . LISTENER_ID ) ; JsonObject message = ( JsonObject ) object . get ( "message" ) ; message . put ( "to" , emailAddress ) ; message . put ( "body" , text ) ; message . put ( "oid" , oid ) ; } | Generate an order to send an email to the intended recipient |
22,716 | private void audit ( JsonSimple response , String oid , String message ) { JsonObject order = newSubscription ( response , oid ) ; JsonObject messageObject = ( JsonObject ) order . get ( "message" ) ; messageObject . put ( "eventType" , message ) ; } | Generate an order to add a message to the System s audit log |
22,717 | private void scheduleTransformers ( JsonSimple message , JsonSimple response ) { String oid = message . getString ( null , "oid" ) ; List < String > list = message . getStringList ( "transformer" , "metadata" ) ; if ( list != null && ! list . isEmpty ( ) ) { for ( String id : list ) { JsonObject order = newTransform ( response , id , oid ) ; JsonObject itemConfig = message . getObject ( "transformerOverrides" , id ) ; if ( itemConfig != null ) { JsonObject config = ( JsonObject ) order . get ( "config" ) ; config . putAll ( itemConfig ) ; } } } } | Generate orders for the list of normal transformers scheduled to execute on the tool chain |
22,718 | private void setRenderFlag ( String oid ) { try { DigitalObject object = storage . getObject ( oid ) ; Properties props = object . getMetadata ( ) ; props . setProperty ( "render-pending" , "true" ) ; storeProperties ( object , props ) ; } catch ( StorageException ex ) { log . error ( "Error accessing storage for '{}'" , oid , ex ) ; } } | Set the render flag for objects that are starting in the tool chain |
22,719 | private JsonObject createTask ( JsonSimple response , String oid , String task ) { return createTask ( response , null , oid , task ) ; } | Create a task . Tasks are basically just trivial messages that will come back to this manager for later action . |
22,720 | private JsonObject createTask ( JsonSimple response , String broker , String oid , String task ) { JsonObject object = newMessage ( response , TransactionManagerQueueConsumer . LISTENER_ID ) ; if ( broker != null ) { object . put ( "broker" , broker ) ; } JsonObject message = ( JsonObject ) object . get ( "message" ) ; message . put ( "task" , task ) ; message . put ( "oid" , oid ) ; return message ; } | Create a task . This is a more detailed option allowing for tasks being sent to remote brokers . |
22,721 | private JsonObject newIndex ( JsonSimple response , String oid ) { JsonObject order = createNewOrder ( response , TransactionManagerQueueConsumer . OrderType . INDEXER . toString ( ) ) ; order . put ( "oid" , oid ) ; return order ; } | Creation of new Orders with appropriate default nodes |
22,722 | private JsonSimple getConfigFromStorage ( String oid ) { String configOid = null ; String configPid = null ; try { DigitalObject object = storage . getObject ( oid ) ; Properties metadata = object . getMetadata ( ) ; configOid = metadata . getProperty ( "jsonConfigOid" ) ; configPid = metadata . getProperty ( "jsonConfigPid" ) ; } catch ( StorageException ex ) { log . error ( "Error accessing object '{}' in storage: " , oid , ex ) ; return null ; } if ( configOid == null || configPid == null ) { log . error ( "Unable to find configuration for OID '{}'" , oid ) ; return null ; } try { DigitalObject object = storage . getObject ( configOid ) ; Payload payload = object . getPayload ( configPid ) ; try { return new JsonSimple ( payload . open ( ) ) ; } catch ( IOException ex ) { log . error ( "Error accessing config '{}' in storage: " , configOid , ex ) ; } finally { payload . close ( ) ; } } catch ( StorageException ex ) { log . error ( "Error accessing object in storage: " , ex ) ; } return null ; } | Get the stored harvest configuration from storage for the indicated object . |
22,723 | private JsonSimple parsedFormData ( String oid ) { Payload payload = null ; try { DigitalObject object = storage . getObject ( oid ) ; payload = getDataPayload ( object ) ; } catch ( StorageException ex ) { log . error ( "Error accessing object '{}' in storage: " , oid , ex ) ; return null ; } try { try { return FormDataParser . parse ( payload . open ( ) ) ; } catch ( IOException ex ) { log . error ( "Error parsing data '{}': " , oid , ex ) ; return null ; } finally { payload . close ( ) ; } } catch ( StorageException ex ) { log . error ( "Error accessing data '{}' in storage: " , oid , ex ) ; return null ; } } | Get the form data from storage for the indicated object and parse it into a JSON structure . |
22,724 | private Properties getObjectMetadata ( String oid ) { try { DigitalObject object = storage . getObject ( oid ) ; return object . getMetadata ( ) ; } catch ( StorageException ex ) { log . error ( "Error accessing object '{}' in storage: " , oid , ex ) ; return null ; } } | Get the metadata properties for the indicated object . |
22,725 | private void saveObjectData ( JsonSimple data , String oid ) throws TransactionException { DigitalObject object = null ; try { object = storage . getObject ( oid ) ; getDataPayload ( object ) ; } catch ( StorageException ex ) { log . error ( "Error accessing object '{}' in storage: " , oid , ex ) ; throw new TransactionException ( ex ) ; } String jsonString = data . toString ( true ) ; try { updateDataPayload ( object , jsonString ) ; } catch ( Exception ex ) { log . error ( "Unable to store data '{}': " , oid , ex ) ; throw new TransactionException ( ex ) ; } } | Save the provided object data back into storage |
22,726 | public static JsonSimple parse ( String input ) throws IOException { ByteArrayInputStream bytes = new ByteArrayInputStream ( input . getBytes ( "UTF-8" ) ) ; return parse ( bytes ) ; } | A wrapper for Stream based parsing . This method accepts a String and will internally create a Stream for it . |
22,727 | public static JsonSimple parse ( InputStream input ) throws IOException { JsonSimple inputData = new JsonSimple ( input ) ; JsonSimple responseData = new JsonSimple ( ) ; JsonObject object = inputData . getJsonObject ( ) ; for ( Object key : object . keySet ( ) ) { String strKey = validString ( key ) ; if ( ! EXCLUDED_FIELDS . contains ( strKey ) ) { String data = validString ( object . get ( key ) ) ; parseField ( responseData , strKey , data ) ; } } return responseData ; } | Accept and parse raw JSON data from an InputStream . Field name String literals will be broken down into meaningful JSON data structures . |
22,728 | private static String validString ( Object data ) throws IOException { if ( data == null ) { return "" ; } if ( ! ( data instanceof String ) ) { throw new IOException ( "Invalid non-String value found!" ) ; } return ( String ) data ; } | Ensures one of the generic objects coming from the JSON library is in fact a String . |
22,729 | private static void parseField ( JsonSimple response , String field , String data ) throws IOException { String [ ] fieldParts = field . split ( "\\." ) ; JsonObject lastObject = null ; JSONArray lastArray = null ; for ( int i = 0 ; i < fieldParts . length ; i ++ ) { String segment = fieldParts [ i ] ; int number = parseInt ( segment ) ; if ( i == 0 ) { JsonObject topObject = response . getJsonObject ( ) ; if ( number != - 1 ) { throw new IOException ( "Field '" + field + "' starts with" + " an array... this is illegal form data!" ) ; } if ( i + 1 == fieldParts . length ) { topObject . put ( segment , data ) ; } else { String nextSegment = fieldParts [ i + 1 ] ; int nextNumber = parseInt ( nextSegment ) ; if ( nextNumber == - 1 ) { lastObject = getObject ( topObject , segment ) ; lastArray = null ; } else { lastObject = null ; lastArray = getArray ( topObject , segment ) ; } } } else { if ( i == ( fieldParts . length - 1 ) ) { lastObject . put ( segment , data ) ; } else { String nextSegment = fieldParts [ i + 1 ] ; int nextNumber = parseInt ( nextSegment ) ; if ( lastArray == null ) { if ( number != - 1 ) { throw new IOException ( "Field '" + field + "' has an" + " illegal syntax!" ) ; } if ( nextNumber == - 1 ) { lastObject = getObject ( lastObject , segment ) ; lastArray = null ; } else { lastArray = getArray ( lastObject , segment ) ; lastObject = null ; } } else { if ( number == - 1 ) { throw new IOException ( "Field '" + field + "' has an" + " illegal syntax!" ) ; } lastObject = getObject ( lastArray , number ) ; lastArray = null ; } } } } } | Parse an individual field into the response object . |
22,730 | private static JSONArray getArray ( JsonObject object , String key ) throws IOException { if ( object . containsKey ( key ) ) { Object existing = object . get ( key ) ; if ( ! ( existing instanceof JSONArray ) ) { throw new IOException ( "Invalid field structure, '" + key + "' expected to be an array, but incompatible " + "data type already present." ) ; } return ( JSONArray ) existing ; } else { JSONArray newObject = new JSONArray ( ) ; object . put ( key , newObject ) ; return newObject ; } } | Get a child JSON Array from an incoming JSON object . If the child does not exist it will be created . |
22,731 | private static JsonObject getObject ( JsonObject object , String key ) throws IOException { if ( object . containsKey ( key ) ) { Object existing = object . get ( key ) ; if ( ! ( existing instanceof JsonObject ) ) { throw new IOException ( "Invalid field structure, '" + key + "' expected to be an object, but incompatible " + "data type already present." ) ; } return ( JsonObject ) existing ; } else { JsonObject newObject = new JsonObject ( ) ; object . put ( key , newObject ) ; return newObject ; } } | Get a child JSON Object from an incoming JSON object . If the child does not exist it will be created . |
22,732 | private static int parseInt ( String integer ) throws IOException { try { int value = Integer . parseInt ( integer ) ; if ( value < 0 ) { throw new IOException ( "Invalid number in field name: '" + integer + "'" ) ; } return value ; } catch ( NumberFormatException ex ) { return - 1 ; } } | Parse a String to an integer . This wrapper is simply to avoid the try catch statement repeatedly . Tests for - 1 are sufficient since it is illegal in form data . Valid integers below 1 throw exceptions because of this illegality . |
22,733 | public void init ( String jsonString ) throws TransformerException { try { setConfig ( new JsonSimpleConfig ( jsonString ) ) ; } catch ( IOException e ) { throw new TransformerException ( e ) ; } } | Initializes the plugin using the specified JSON String |
22,734 | private DigitalObject process ( DigitalObject in , String jsonConfig ) throws TransformerException { String oid = in . getId ( ) ; JsonSimple workflow = null ; try { Payload workflowPayload = in . getPayload ( "workflow.metadata" ) ; workflow = new JsonSimple ( workflowPayload . open ( ) ) ; workflowPayload . close ( ) ; } catch ( StorageException ex ) { error ( "Error accessing workflow data from Object!\nOID: '" + oid + "'" , ex ) ; } catch ( IOException ex ) { error ( "Error parsing workflow data from Object!\nOID: '" + oid + "'" , ex ) ; } String step = workflow . getString ( null , "step" ) ; if ( step == null || ! step . equals ( "live" ) ) { log . warn ( "Object is not live! '{}'" , oid ) ; return in ; } String title = workflow . getString ( null , Strings . NODE_FORMDATA , "title" ) ; if ( title == null ) { error ( "No title provided in Object form data!\nOID: '" + oid + "'" ) ; } Properties metadata = null ; try { metadata = in . getMetadata ( ) ; } catch ( StorageException ex ) { error ( "Error reading Object metadata!\nOID: '" + oid + "'" , ex ) ; } return processObject ( in , workflow , metadata ) ; } | Top level wrapping method for a processing an object . |
22,735 | private DigitalObject processObject ( DigitalObject object , JsonSimple workflow , Properties metadata ) throws TransformerException { String oid = object . getId ( ) ; String title = workflow . getString ( null , Strings . NODE_FORMDATA , "title" ) ; FedoraClient fedora = null ; try { fedora = fedoraConnect ( ) ; } catch ( TransformerException ex ) { error ( "Error connecting to VITAL" , ex , oid , title ) ; } String vitalPid = metadata . getProperty ( Strings . PROP_VITAL_KEY ) ; if ( vitalPid != null ) { log . debug ( "Existing VITAL object: '{}'" , vitalPid ) ; if ( ! datastreamExists ( fedora , vitalPid , "DC" ) ) { String message = " !!! WARNING !!! The expected VITAL object '" + vitalPid + "' was not found. A new object will be created instead!" ; error ( message , null , oid , title ) ; vitalPid = null ; } } if ( vitalPid == null ) { try { vitalPid = createNewObject ( fedora , object . getId ( ) ) ; log . debug ( "New VITAL object created: '{}'" , vitalPid ) ; metadata . setProperty ( Strings . PROP_VITAL_KEY , vitalPid ) ; object . close ( ) ; } catch ( Exception ex ) { error ( "Failed to create object in VITAL" , ex , oid , title ) ; } } if ( ! waitProperties . isEmpty ( ) ) { boolean process = false ; for ( String test : waitProperties ) { String value = metadata . getProperty ( test ) ; if ( value != null ) { log . info ( "Wait condition '{}' found." , test ) ; process = true ; } } if ( ! process ) { log . info ( "No wait conditions have been met, processing halted" ) ; return object ; } } try { String isActive = metadata . getProperty ( Strings . PROP_VITAL_ACTIVE ) ; if ( isActive == null ) { log . info ( "Activating object in fedora: '{}'" , oid ) ; String cutTitle = title ; if ( cutTitle . length ( ) > 250 ) { cutTitle = cutTitle . substring ( 0 , 250 ) + "..." ; } fedora . getAPIM ( ) . modifyObject ( vitalPid , "A" , cutTitle , null , "ReDBox activating object: '" + oid + "'" ) ; metadata . setProperty ( Strings . PROP_VITAL_ACTIVE , "true" ) ; object . close ( ) ; } } catch ( Exception ex ) { error ( "Failed to activate object in VITAL" , ex , oid , title ) ; } try { processDatastreams ( fedora , object , vitalPid ) ; } catch ( Exception ex ) { error ( "Failed to send object to VITAL" , ex , oid , title ) ; } return object ; } | Middle level wrapping method for processing objects . Now we are looking at what actually needs to be done . Has the object already been put in VITAL or is it new . |
22,736 | private String createNewObject ( FedoraClient fedora , String oid ) throws Exception { InputStream in = null ; byte [ ] template = null ; try { if ( foxmlTemplate != null ) { in = new FileInputStream ( foxmlTemplate ) ; template = IOUtils . toByteArray ( in ) ; } else { in = getClass ( ) . getResourceAsStream ( "/foxml_template.xml" ) ; template = IOUtils . toByteArray ( in ) ; } } catch ( IOException ex ) { throw new Exception ( "Error accessing FOXML Template, please check system configuration!" ) ; } finally { if ( in != null ) { in . close ( ) ; } } String vitalPid = fedora . getAPIM ( ) . ingest ( template , Strings . FOXML_VERSION , "ReDBox creating new object: '" + oid + "'" ) ; log . info ( "New VITAL PID: '{}'" , vitalPid ) ; return vitalPid ; } | Create a new VITAL object and return the PID . |
22,737 | private void processDatastreams ( FedoraClient fedora , DigitalObject object , String vitalPid ) throws Exception { int sent = 0 ; for ( String ourPid : pids . keySet ( ) ) { String realPid = ourPid ; if ( ourPid . equals ( ".tfpackage" ) ) { realPid = getPackagePid ( object ) ; if ( realPid == null ) { String message = partialUploadErrorMessage ( ourPid , sent , pids . size ( ) , vitalPid ) ; throw new Exception ( message + "\n\nPackage not found." ) ; } } log . info ( "Processing PID to send to VITAL: '{}'" , ourPid ) ; JsonSimple thisPid = pids . get ( ourPid ) ; String dsId = thisPid . getString ( realPid , "dsID" ) ; String label = thisPid . getString ( dsId , "label" ) ; String status = thisPid . getString ( "A" , "status" ) ; String controlGroup = thisPid . getString ( "X" , "controlGroup" ) ; boolean versionable = thisPid . getBoolean ( true , "versionable" ) ; boolean retainIds = thisPid . getBoolean ( true , "retainIds" ) ; String [ ] altIds = { } ; if ( retainIds && datastreamExists ( fedora , vitalPid , dsId ) ) { altIds = getAltIds ( fedora , vitalPid , dsId ) ; for ( String altId : altIds ) { log . debug ( "Retaining alt ID: '{}' => {}'" , dsId , altId ) ; } } Payload payload = null ; String mimeType = null ; try { payload = object . getPayload ( realPid ) ; } catch ( StorageException ex ) { String message = partialUploadErrorMessage ( realPid , sent , pids . size ( ) , vitalPid ) ; throw new Exception ( message + "\n\nError accessing payload '" + realPid + "' : " , ex ) ; } mimeType = payload . getContentType ( ) ; if ( mimeType == null ) { mimeType = "application/octet-stream" ; } try { sendToVital ( fedora , object , realPid , vitalPid , dsId , altIds , label , mimeType , controlGroup , status , versionable ) ; } catch ( Exception ex ) { String message = partialUploadErrorMessage ( realPid , sent , pids . size ( ) , vitalPid ) ; throw new Exception ( message , ex ) ; } sent ++ ; } try { processAttachments ( fedora , object , vitalPid ) ; } catch ( Exception ex ) { throw new Exception ( "Error processing attachments: " , ex ) ; } } | Method responsible for arranging submissions to VITAL to store our datastreams . |
22,738 | private String getPackagePid ( DigitalObject object ) throws Exception { for ( String pid : object . getPayloadIdList ( ) ) { if ( pid . endsWith ( ".tfpackage" ) ) { return pid ; } } return null ; } | For the given digital object find the Fascinator package inside . |
22,739 | private String [ ] resolveAltIds ( String [ ] oldArray , String mimeType , int count ) { String key = null ; for ( String mimeTest : attachAltIds . keySet ( ) ) { if ( mimeTest . equals ( Strings . LITERAL_DEFAULT ) ) { continue ; } if ( mimeTest . endsWith ( "/" ) ) { if ( mimeType . startsWith ( mimeTest ) ) { key = mimeTest ; } } else { if ( mimeType . equals ( mimeTest ) ) { key = mimeTest ; } } } if ( key == null ) { key = Strings . LITERAL_DEFAULT ; } for ( String newId : attachAltIds . get ( key ) ) { String formatted = String . format ( newId , count ) ; oldArray = growArray ( oldArray , formatted ) ; } return oldArray ; } | For the given mime type ensure that the array of alternate identifiers is correct . If identifiers are missing they will be added to the array . |
22,740 | private String [ ] growArray ( String [ ] oldArray , String newElement ) { for ( String element : oldArray ) { if ( element . equals ( newElement ) ) { return oldArray ; } } log . debug ( "Adding ID: '{}'" , newElement ) ; int length = oldArray . length + 1 ; String [ ] newArray = new String [ length ] ; System . arraycopy ( oldArray , 0 , newArray , 0 , oldArray . length ) ; newArray [ length - 1 ] = newElement ; return newArray ; } | Check the array for the new element and if not found generate a new array containing all of the old elements plus the new . |
22,741 | private boolean datastreamExists ( FedoraClient fedora , String vitalPid , String dsPid ) { try { DatastreamDef [ ] streams = fedora . getAPIA ( ) . listDatastreams ( vitalPid , null ) ; for ( DatastreamDef stream : streams ) { if ( stream . getID ( ) . equals ( dsPid ) ) { return true ; } } } catch ( Exception ex ) { log . error ( "API Query error: " , ex ) ; } return false ; } | Test for the existence of a given datastream in VITAL . |
22,742 | private String [ ] getAltIds ( FedoraClient fedora , String vitalPid , String dsPid ) { Datastream ds = getDatastream ( fedora , vitalPid , dsPid ) ; if ( ds != null ) { return ds . getAltIDs ( ) ; } return new String [ ] { } ; } | Find and return any alternate identifiers already in use in fedora for the given datastream . |
22,743 | private String fedoraLogEntry ( DigitalObject object , String pid ) { String message = fedoraMessageTemplate . replace ( "[[PID]]" , pid ) ; return message . replace ( "[[OID]]" , object . getId ( ) ) ; } | Build a Log entry to use in Fedora . Replace all the template placeholders |
22,744 | private File getTempFile ( DigitalObject object , String pid ) throws Exception { File directory = new File ( tmpDir , object . getId ( ) ) ; File target = new File ( directory , pid ) ; if ( ! target . exists ( ) ) { target . getParentFile ( ) . mkdirs ( ) ; target . createNewFile ( ) ; } Payload payload = object . getPayload ( pid ) ; InputStream in = payload . open ( ) ; FileOutputStream out = null ; try { out = new FileOutputStream ( target ) ; IOUtils . copyLarge ( in , out ) ; } catch ( Exception ex ) { close ( out ) ; target . delete ( ) ; payload . close ( ) ; throw ex ; } close ( out ) ; payload . close ( ) ; return target ; } | Stream the data out of storage to our temp directory . |
22,745 | private byte [ ] getBytes ( DigitalObject object , String pid ) throws Exception { Payload payload = object . getPayload ( pid ) ; InputStream in = payload . open ( ) ; byte [ ] result = null ; try { result = IOUtils . toByteArray ( in ) ; } catch ( Exception ex ) { throw ex ; } finally { payload . close ( ) ; } return result ; } | Retrieve the payload from storage and return as a byte array . |
22,746 | public static HashMap < String , String > find ( HashMap < String , String > props , String path ) { if ( path == null || path . length ( ) == 0 ) return props ; HashMap < String , String > next = new HashMap < > ( ) ; String [ ] keys = path . split ( "\\." ) ; String key = keys [ 0 ] ; boolean endsWith = key . startsWith ( "*" ) ; boolean startsWith = key . endsWith ( "*" ) ; key = key . replace ( "*" , "" ) ; Iterator < String > e = props . keySet ( ) . iterator ( ) ; while ( e . hasNext ( ) ) { String name = e . next ( ) ; String [ ] names = name . split ( "\\." ) ; if ( startsWith && ! endsWith && ! names [ 0 ] . startsWith ( key ) ) continue ; else if ( ! startsWith && endsWith && ! names [ 0 ] . endsWith ( key ) ) continue ; else if ( startsWith && endsWith && ! names [ 0 ] . contains ( key ) ) continue ; else if ( ! startsWith && ! endsWith && ! names [ 0 ] . equals ( key ) ) continue ; String newName = name . substring ( name . indexOf ( "." ) + 1 ) ; next . put ( newName , props . get ( name ) ) ; } if ( ! path . contains ( "." ) ) return next ; return find ( next , path . substring ( path . indexOf ( "." ) + 1 ) ) ; } | Sucht in props nach allen Schluesseln im genannten Pfad und liefert sie zurueck . |
22,747 | public boolean run ( ) { boolean passed ; ExecutionToken t = createExecutionToken ( ) ; List < FeatureToken > features = getFeatureList ( t ) ; startTests ( t , features ) ; initializeInterpreter ( ) ; processFeatures ( t , features ) ; endTests ( t , features ) ; passed = t . getEndState ( ) == EndState . PASSED || t . getEndState ( ) == EndState . PENDING ; dispose ( ) ; return passed ; } | Run interpreter using just the base configuration and the listeners provided |
22,748 | public String getSuiteName ( ) { return configReader . isSet ( ChorusConfigProperty . SUITE_NAME ) ? concatenateName ( configReader . getValues ( ChorusConfigProperty . SUITE_NAME ) ) : "" ; } | to get the suite name we concatenate all the values provided for suite name switch |
22,749 | private BigDecimal checkDebit ( BigDecimal d , CreditDebitCode code ) { if ( d == null || code == null || code == CreditDebitCode . CRDT ) return d ; return BigDecimal . ZERO . subtract ( d ) ; } | Prueft ob es sich um einen Soll - Betrag handelt und setzt in dem Fall ein negatives Vorzeichen vor den Wert . |
22,750 | @ SuppressWarnings ( { "unchecked" , "unused" } ) public < T > T get ( String key , Class < T > type ) { try { return ( T ) state . get ( key ) ; } catch ( ClassCastException cce ) { return null ; } } | This get method will return the value if its type matches the type parameter |
22,751 | protected String getResourceSuffix ( String target ) { int index = target . lastIndexOf ( '/' ) ; if ( index > - 1 ) { target = target . substring ( index + 1 ) ; } return target ; } | just find the stylesheet name disregarding nested folder names |
22,752 | protected String trim ( String s ) { if ( s == null || s . length ( ) == 0 ) return s ; return s . trim ( ) ; } | Entfernt die Whitespaces des Textes . Manche Banken fuellen den Gegenkontoinhaber rechts auf 70 Zeichen mit Leerzeichen auf . |
22,753 | protected List < String > trim ( List < String > list ) { if ( list == null || list . size ( ) == 0 ) return list ; List < String > result = new ArrayList < String > ( ) ; for ( String s : list ) { s = trim ( s ) ; if ( s == null || s . length ( ) == 0 ) continue ; result . add ( s ) ; } return result ; } | Entfernt die Whitespaces in der Liste der Texte . |
22,754 | public synchronized void startProcess ( String configName , String processName , Properties processProperties ) throws Exception { ProcessManagerConfig runtimeConfig = getProcessManagerConfig ( configName , processProperties ) ; if ( runtimeConfig . isEnabled ( ) ) { doStart ( processName , runtimeConfig ) ; } else { log . info ( "Not starting process " + processName + " since enabled=false" ) ; } } | Starts a record Java process using properties defined in a properties file alongside the feature file |
22,755 | private void incrementPortsIfDuplicateName ( String configName , ProcessConfigBean config ) { int startedCount = getNumberOfInstancesStarted ( configName ) ; int debugPort = config . getDebugPort ( ) ; if ( debugPort != - 1 ) { config . setDebugPort ( debugPort + startedCount ) ; } int remotingPort = config . getRemotingPort ( ) ; if ( remotingPort != - 1 ) { config . setRemotingPort ( remotingPort + startedCount ) ; } } | If we already have an instance of a process with this name auto increment ports to avoid a conflict |
22,756 | public StepEndState runSteps ( ExecutionToken executionToken , StepInvokerProvider stepInvokerProvider , List < StepToken > stepList , StepCatalogue stepCatalogue , boolean skip ) { for ( StepToken step : stepList ) { StepEndState endState = processStep ( executionToken , stepInvokerProvider , step , stepCatalogue , skip ) ; switch ( endState ) { case PASSED : break ; case FAILED : skip = true ; break ; case UNDEFINED : skip = true ; break ; case PENDING : skip = true ; break ; case TIMEOUT : skip = true ; break ; case SKIPPED : case DRYRUN : break ; default : throw new RuntimeException ( "Unhandled step state " + endState ) ; } } StepEndState stepMacroEndState = StepMacro . calculateStepMacroEndState ( stepList ) ; return stepMacroEndState ; } | Process all steps in stepList |
22,757 | private void sortInvokersByPattern ( List < StepInvoker > stepInvokers ) { Collections . sort ( stepInvokers , new Comparator < StepInvoker > ( ) { public int compare ( StepInvoker o1 , StepInvoker o2 ) { return o1 . getStepPattern ( ) . toString ( ) . compareTo ( o2 . getStepPattern ( ) . toString ( ) ) ; } } ) ; } | prefer fully determinate behaviour . The only sensible solution is to sort by pattern |
22,758 | public Map < String , Map < String , Set < String > > > getTargetLanguagesMap ( ) { if ( targetLanguagesMap == null ) { assert false ; return Collections . emptyMap ( ) ; } return Collections . unmodifiableMap ( targetLanguagesMap ) ; } | Returns the map containing target languages indexed by document type and ids . This method always returns non - null map . |
22,759 | public String getSsf ( Integer id ) { if ( id < 1 || id > 25 ) throw new IllegalStateException ( "Site specific factor must be between 1 and 25." ) ; return getInput ( INPUT_SSF_PREFIX + id ) ; } | Get the specified input site - specific factor |
22,760 | public void setSsf ( Integer id , String ssf ) { if ( id < 1 || id > 25 ) throw new IllegalStateException ( "Site specific factor must be between 1 and 25." ) ; setInput ( INPUT_SSF_PREFIX + id , ssf ) ; } | Set the specified input site - specific factor |
22,761 | private void addStepInvoker ( StepInvoker stepInvoker ) { if ( connected . get ( ) ) { throw new ChorusException ( "You cannot add more steps once the WebSocketStepPublisher is connected" ) ; } stepInvokers . put ( stepInvoker . getId ( ) , stepInvoker ) ; } | Add a step to be published |
22,762 | public WebSocketStepPublisher publish ( ) { if ( connected . getAndSet ( true ) == false ) { try { log . info ( "Connecting" ) ; boolean connected = chorusWebSocketClient . connectBlocking ( ) ; if ( ! connected ) { throw new StepPublisherException ( "Failed to connect to WebSocketsManagerImpl" ) ; } ConnectMessage connect = new ConnectMessage ( chorusClientId , "" . equals ( description ) ? chorusClientId : description ) ; chorusWebSocketClient . sendMessage ( connect ) ; log . info ( "Publishing steps" ) ; stepInvokers . values ( ) . stream ( ) . forEach ( invoker -> { publishStep ( invoker ) ; } ) ; log . info ( "Sending Aligned" ) ; StepsAlignedMessage stepsAlignedMessage = new StepsAlignedMessage ( chorusClientId ) ; chorusWebSocketClient . sendMessage ( stepsAlignedMessage ) ; } catch ( Exception e ) { throw new ChorusException ( "Failed to connect and publish steps" , e ) ; } } return this ; } | Connect to the server and publish all steps |
22,763 | static public void assertEquals ( String message , float expected , float actual , float delta ) { if ( Float . compare ( expected , actual ) == 0 ) return ; if ( ! ( Math . abs ( expected - actual ) <= delta ) ) failNotEquals ( message , new Float ( expected ) , new Float ( actual ) ) ; } | Asserts that two floats are equal concerning a positive delta . If they are not an AssertionFailedError is thrown with the given message . If the expected value is infinity then the delta value is ignored . |
22,764 | static public void assertEquals ( String message , char expected , char actual ) { assertEquals ( message , new Character ( expected ) , new Character ( actual ) ) ; } | Asserts that two chars are equal . If they are not an AssertionFailedError is thrown with the given message . |
22,765 | static public void assertEquals ( String message , short expected , short actual ) { assertEquals ( message , new Short ( expected ) , new Short ( actual ) ) ; } | Asserts that two shorts are equal . If they are not an AssertionFailedError is thrown with the given message . |
22,766 | private Optional < Pattern > getDefaultValidationPattern ( Class javaType ) { return javaType . isEnum ( ) ? Optional . of ( createValidationPatternFromEnumType ( javaType ) ) : getDefaultPatternIfPrimitive ( javaType ) ; } | Try to create a sensible default for validation pattern in the case where the java type of the parameter is an enum type or a primitive or primitive wrapper type |
22,767 | private boolean containsOnly ( String s , char c ) { for ( char c2 : s . toCharArray ( ) ) { if ( c != c2 ) return false ; } return true ; } | Prueft ob der Text s nur aus dem Zeichen c besteht . |
22,768 | protected final PainGeneratorIf getPainGenerator ( ) { if ( this . generator == null ) { try { this . generator = PainGeneratorFactory . get ( this , this . getPainVersion ( ) ) ; } catch ( Exception e ) { String msg = HBCIUtils . getLocMsg ( "EXCMSG_JOB_CREATE_ERR" , this . getPainJobName ( ) ) ; throw new HBCI_Exception ( msg , e ) ; } } return this . generator ; } | Liefert den passenden SEPA - Generator . |
22,769 | public int enumerateSegs ( int startValue , boolean allowOverwrite ) { int idx = startValue ; for ( MultipleSyntaxElements s : getChildContainers ( ) ) { if ( s != null ) idx = s . enumerateSegs ( idx , allowOverwrite ) ; } return idx ; } | loop through all child - elements ; the segments found there will be sequentially enumerated starting with num startValue ; if startValue is zero the segments will not be enumerated but all given the number 0 |
22,770 | public void extractValues ( HashMap < String , String > values ) { for ( MultipleSyntaxElements l : childContainers ) { l . extractValues ( values ) ; } } | fuellt die hashtable values mit den werten der de - syntaxelemente ; dazu wird in allen anderen typen von syntaxelementen die liste der child - elemente durchlaufen und deren fillValues methode aufgerufen |
22,771 | public void validate ( ) { if ( ! needsRequestTag || haveRequestTag ) { for ( MultipleSyntaxElements l : childContainers ) { l . validate ( ) ; } setValid ( true ) ; } } | ueberpreuft ob das syntaxelement alle restriktionen einhaelt ; ist das nicht der fall so wird eine Exception ausgeloest . die meisten syntaxelemente koennen sich nicht selbst ueberpruefen sondern rufen statt dessen die validate - funktion der child - elemente auf |
22,772 | public Object invokeStep ( String remoteStepInvokerId , String stepTokenId , List < String > params ) throws Exception { try { Object [ ] args = { remoteStepInvokerId , stepTokenId , ChorusContext . getContext ( ) . getSnapshot ( ) , params } ; String [ ] signature = { "java.lang.String" , "java.lang.String" , "java.util.Map" , "java.util.List" } ; log . debug ( String . format ( "About to invoke step (%s) on MBean (%s)" , remoteStepInvokerId , objectName ) ) ; JmxStepResult r = ( JmxStepResult ) mBeanServerConnection . invoke ( objectName , "invokeStep" , args , signature ) ; Map newContextState = r . getChorusContext ( ) ; ChorusContext . resetContext ( newContextState ) ; return r . getResult ( ) ; } catch ( MBeanException e ) { throw e . getTargetException ( ) ; } } | Calls the invoke Step method on the remote MBean . The current ChorusContext will be serialized as part of this and marshalled to the remote bean . |
22,773 | public void processStartOfScope ( Scope scopeStarting , Iterable < Object > handlerInstances ) throws Exception { for ( Object handler : handlerInstances ) { Handler handlerAnnotation = handler . getClass ( ) . getAnnotation ( Handler . class ) ; Scope handlerScope = handlerAnnotation . scope ( ) ; injectResourceFieldsForScope ( scopeStarting , handler , handlerScope , handlerInstances ) ; runLifecycleMethods ( handler , handlerScope , scopeStarting , false ) ; } } | Scope is starting perform the required processing on the supplied handlers . |
22,774 | public void processEndOfScope ( Scope scopeEnding , Iterable < Object > handlerInstances ) throws Exception { for ( Object handler : handlerInstances ) { Handler handlerAnnotation = handler . getClass ( ) . getAnnotation ( Handler . class ) ; Scope scope = handlerAnnotation . scope ( ) ; runLifecycleMethods ( handler , scope , scopeEnding , true ) ; if ( scope == scopeEnding ) { disposeSpringResources ( handler , scopeEnding ) ; } } } | Scope is ending perform the required processing on the supplied handlers . |
22,775 | private Scope getMethodScope ( boolean isDestroy , Method method ) { Scope methodScope ; if ( isDestroy ) { Destroy annotation = method . getAnnotation ( Destroy . class ) ; methodScope = annotation != null ? annotation . scope ( ) : null ; } else { Initialize annotation = method . getAnnotation ( Initialize . class ) ; methodScope = annotation != null ? annotation . scope ( ) : null ; } return methodScope ; } | return the scope of a lifecycle method or null if the method is not a lifecycle method |
22,776 | private void injectResourceFields ( Object handler , Iterable < Object > handlerInstances , Scope ... scopes ) { Class < ? > featureClass = handler . getClass ( ) ; List < Field > allFields = new ArrayList < > ( ) ; addAllPublicFields ( featureClass , allFields ) ; log . trace ( "Now examining handler fields for ChorusResource annotation " + allFields ) ; HashSet < Scope > scopeSet = new HashSet < > ( Arrays . asList ( scopes ) ) ; for ( Field field : allFields ) { setChorusResource ( handler , handlerInstances , field , scopeSet ) ; } } | Here we set the values of any handler fields annotated with |
22,777 | public static SepaVersion byURN ( String urn ) { SepaVersion test = new SepaVersion ( null , 0 , urn , null , false ) ; if ( urn == null || urn . length ( ) == 0 ) return test ; for ( List < SepaVersion > types : knownVersions . values ( ) ) { for ( SepaVersion v : types ) { if ( v . equals ( test ) ) return v ; } } return test ; } | Liefert die SEPA - Version aus dem URN . |
22,778 | private static Type findType ( String type , String value ) throws IllegalArgumentException { if ( type == null || type . length ( ) == 0 ) throw new IllegalArgumentException ( "no SEPA type type given" ) ; if ( value == null || value . length ( ) == 0 ) throw new IllegalArgumentException ( "no SEPA version value given" ) ; for ( Type t : Type . values ( ) ) { if ( t . getType ( ) . equalsIgnoreCase ( type ) && t . getValue ( ) . equals ( value ) ) return t ; } throw new IllegalArgumentException ( "unknown SEPA version type: " + type + "." + value ) ; } | Liefert den enum - Type fuer den angegebenen Wert . |
22,779 | public static SepaVersion autodetect ( InputStream xml ) { try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setIgnoringComments ( true ) ; factory . setValidating ( false ) ; factory . setNamespaceAware ( true ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; Document doc = builder . parse ( xml ) ; Node root = doc . getFirstChild ( ) ; if ( root == null ) throw new IllegalArgumentException ( "XML data did not contain a root element" ) ; String uri = root . getNamespaceURI ( ) ; if ( uri == null ) return null ; return SepaVersion . byURN ( uri ) ; } catch ( IllegalArgumentException e ) { throw e ; } catch ( Exception e2 ) { throw new IllegalArgumentException ( e2 ) ; } } | Ermittelt die SEPA - Version aus dem uebergebenen XML - Stream . |
22,780 | public String getGeneratorClass ( String jobName ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( PainGeneratorIf . class . getPackage ( ) . getName ( ) ) ; sb . append ( ".Gen" ) ; sb . append ( jobName ) ; sb . append ( this . type . getValue ( ) ) ; sb . append ( new DecimalFormat ( DF_MAJOR ) . format ( this . major ) ) ; sb . append ( new DecimalFormat ( DF_MINOR ) . format ( this . minor ) ) ; return sb . toString ( ) ; } | Erzeugt den Namen der Java - Klasse des zugehoerigen SEPA - Generators . |
22,781 | public String getParserClass ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( ISEPAParser . class . getPackage ( ) . getName ( ) ) ; sb . append ( ".Parse" ) ; sb . append ( this . type . getType ( ) ) ; sb . append ( this . type . getValue ( ) ) ; sb . append ( new DecimalFormat ( DF_MAJOR ) . format ( this . major ) ) ; sb . append ( new DecimalFormat ( DF_MINOR ) . format ( this . minor ) ) ; return sb . toString ( ) ; } | Erzeugt den Namen der Java - Klasse des zugehoerigen SEPA - Parsers . |
22,782 | public boolean canGenerate ( String jobName ) { try { Class . forName ( this . getGeneratorClass ( jobName ) ) ; return true ; } catch ( ClassNotFoundException e ) { return false ; } } | Prueft ob fuer die SEPA - Version ein Generator vorhanden ist der fuer den angegebenen HBCI4Java - Job die SEPA - XML - Dateien erzeugen kann . |
22,783 | void runWithinPeriod ( Runnable runnable , ExecuteStepMessage executeStepMessage , int timeout , TimeUnit unit ) { if ( ! isRunningAStep . getAndSet ( true ) ) { this . currentlyExecutingStep = executeStepMessage ; Future < String > future = null ; try { future = scheduledExecutorService . submit ( runStepAndResetIsRunning ( runnable ) , "OK" ) ; future . get ( timeout , unit ) ; } catch ( TimeoutException e ) { future . cancel ( true ) ; log . warn ( "A step failed to execute within " + timeout + " " + unit + ", attempting to cancel the step" ) ; } catch ( Exception e ) { String ms = "Exception while executing step [" + e . getMessage ( ) + "]" ; log . error ( ms , e ) ; stepFailureConsumer . accept ( ms , executeStepMessage ) ; } } else { String message = "Cannot execute a test step, a step is already in progress [" + currentlyExecutingStep . getStepId ( ) + ", " + currentlyExecutingStep . getPattern ( ) + "]" ; log . error ( message ) ; stepFailureConsumer . accept ( message , executeStepMessage ) ; } } | Run a task on the scheduled executor so that we can try to interrupt it and time out if it fails |
22,784 | private Runnable runStepAndResetIsRunning ( Runnable runnable ) { return ( ) -> { try { runnable . run ( ) ; } catch ( Throwable t ) { log . error ( "Exeception while running a step" , t ) ; } finally { isRunningAStep . getAndSet ( false ) ; } } ; } | Wrap the runnable which executed the step and only unset currentlyExecutingStep when it has completed If the step blocks and can t be interrupted then we don t want to start any other steps |
22,785 | private static StackTraceElement findStackTraceElement ( Throwable t ) { StackTraceElement element = t . getStackTrace ( ) . length > 0 ? t . getStackTrace ( ) [ 0 ] : null ; int index = 0 ; String chorusAssertClassName = ChorusAssert . class . getName ( ) ; String junitAssertClassName = "org.junit.Assert" ; String junitLegacyClassName = "junit.framework.Assert" ; while ( element != null && ( element . getClassName ( ) . contains ( chorusAssertClassName ) || element . getClassName ( ) . contains ( junitAssertClassName ) || element . getClassName ( ) . contains ( junitLegacyClassName ) ) ) { index += 1 ; element = t . getStackTrace ( ) . length > index ? t . getStackTrace ( ) [ index ] : null ; } return element ; } | we want to skip frames with the JUnit or ChorusAssert |
22,786 | public ChorusInterpreter buildAndConfigure ( ConfigProperties config , SubsystemManager subsystemManager ) { ChorusInterpreter chorusInterpreter = new ChorusInterpreter ( listenerSupport ) ; chorusInterpreter . setHandlerClassBasePackages ( config . getValues ( ChorusConfigProperty . HANDLER_PACKAGES ) ) ; chorusInterpreter . setScenarioTimeoutMillis ( Integer . valueOf ( config . getValue ( ChorusConfigProperty . SCENARIO_TIMEOUT ) ) * 1000 ) ; chorusInterpreter . setDryRun ( config . isTrue ( ChorusConfigProperty . DRY_RUN ) ) ; chorusInterpreter . setSubsystemManager ( subsystemManager ) ; StepCatalogue stepCatalogue = createStepCatalogue ( config ) ; chorusInterpreter . setStepCatalogue ( stepCatalogue ) ; return chorusInterpreter ; } | Run the interpreter collating results into the executionToken |
22,787 | public static < T > T coerceType ( ChorusLog log , String value , Class < T > requiredType ) { T result = null ; try { if ( "null" . equals ( value ) ) { result = null ; } else if ( isStringType ( requiredType ) ) { result = ( T ) value ; } else if ( isStringBufferType ( requiredType ) ) { result = ( T ) new StringBuffer ( value ) ; } else if ( isIntType ( requiredType ) ) { result = ( T ) new Integer ( value ) ; } else if ( isLongType ( requiredType ) ) { result = ( T ) new Long ( value ) ; } else if ( isFloatType ( requiredType ) ) { result = ( T ) new Float ( value ) ; } else if ( isDoubleType ( requiredType ) ) { result = ( T ) new Double ( value ) ; } else if ( isBigDecimalType ( requiredType ) ) { result = ( T ) new BigDecimal ( value ) ; } else if ( isBigIntegerType ( requiredType ) ) { result = ( T ) new BigInteger ( value ) ; } else if ( isBooleanType ( requiredType ) && "true" . equalsIgnoreCase ( value ) || "false" . equalsIgnoreCase ( value ) ) { result = ( T ) ( Boolean ) Boolean . parseBoolean ( value ) ; } else if ( isShortType ( requiredType ) ) { result = ( T ) new Short ( value ) ; } else if ( isByteType ( requiredType ) ) { result = ( T ) new Byte ( value ) ; } else if ( isCharType ( requiredType ) && value . length ( ) == 1 ) { result = ( T ) ( Character ) value . toCharArray ( ) [ 0 ] ; } else if ( isEnumeratedType ( requiredType ) ) { result = ( T ) coerceEnum ( value , requiredType ) ; } else if ( isObjectType ( requiredType ) ) { result = ( T ) coerceObject ( value ) ; } } catch ( Throwable t ) { log . debug ( "Exception when coercing value " + value + " to a " + requiredType , t ) ; } return result ; } | Will attempt to convert the String to the required type |
22,788 | private static < T > T coerceObject ( String value ) { T result ; if ( "true" . equals ( value ) || "false" . equals ( value ) ) { result = ( T ) ( Boolean ) Boolean . parseBoolean ( value ) ; } else if ( floatPattern . matcher ( value ) . matches ( ) ) { BigDecimal bd = new BigDecimal ( value ) ; Double d = bd . doubleValue ( ) ; result = ( T ) ( ( d == Double . NEGATIVE_INFINITY || d == Double . POSITIVE_INFINITY ) ? bd : d ) ; } else if ( intPattern . matcher ( value ) . matches ( ) ) { BigInteger bd = new BigInteger ( value ) ; result = ( T ) ( bd . compareTo ( BigInteger . valueOf ( Long . MAX_VALUE ) ) == 1 ? bd : bd . longValue ( ) ) ; } else { result = ( T ) value ; } return result ; } | Rules for object coercion are probably most important for the ChorusContext Here when we set the value of a variable these rules are used to determine how the String value supplied is represented - since float pattern comes first I set the variable x with value 1 . 2 will become a float within the ChorusContext - this will give some extra utility if we add more powerful comparison methods to ChorusContext |
22,789 | private PropertyOperations mergeConfigurationAndProfileProperties ( PropertyOperations props ) { PropertyOperations result ; result = mergeConfigurationProperties ( props ) ; result = mergeProfileProperties ( result ) ; return result ; } | Some property keys may be prefixed with the name of a configuration or the name of a profile |
22,790 | private PropertyOperations addPropertiesFromDatabase ( PropertyOperations sourceProperties ) { PropertyOperations dbPropsOnly = sourceProperties . filterByKeyPrefix ( ChorusConstants . DATABASE_CONFIGS_PROPERTY_GROUP + "." ) . removeKeyPrefix ( ChorusConstants . DATABASE_CONFIGS_PROPERTY_GROUP + "." ) ; dbPropsOnly = VariableExpandingPropertyLoader . expandVariables ( dbPropsOnly , currentFeature ) ; Map < String , Properties > dbPropsByDbName = dbPropsOnly . splitKeyAndGroup ( "\\." ) . loadPropertyGroups ( ) ; PropertyOperations o = sourceProperties ; for ( Map . Entry < String , Properties > m : dbPropsByDbName . entrySet ( ) ) { log . debug ( "Creating loader for database properties " + m . getKey ( ) ) ; o = properties ( new JdbcPropertyLoader ( m . getValue ( ) ) ) . merge ( o ) ; } return o ; } | If there are any database properties defined in sourceProperties then use them to merge extra properties from the databsase |
22,791 | public boolean isFatal ( ) { if ( this . fatal ) return true ; Throwable t = this . getCause ( ) ; if ( t == this ) return false ; if ( t instanceof HBCI_Exception ) return ( ( HBCI_Exception ) t ) . isFatal ( ) ; return false ; } | Liefert true wenn die Exception oder ihr Cause als fatal eingestuft wurde . |
22,792 | public void setInput ( String key , String value ) { if ( getAllowedKeys ( ) != null && ! getAllowedKeys ( ) . contains ( key ) ) throw new IllegalStateException ( "The input key " + key + " is not allowed for lookups" ) ; _inputs . put ( key , value ) ; } | Set the value of a single input . |
22,793 | private void executeJdbcStatements ( Connection connection , String configName , String statements , String description ) { Statement stmt = createStatement ( configName , connection ) ; try { log . debug ( "Executing statement [" + description + "]" ) ; List < String > stmtsToExecute = Stream . of ( statements . split ( ";" ) ) . map ( String :: trim ) . filter ( s -> s . length ( ) > 0 ) . collect ( Collectors . toList ( ) ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "These statements will be executed:" ) ; stmtsToExecute . forEach ( s -> log . trace ( "Statement: [" + s + "]" ) ) ; } for ( String currentStatement : stmtsToExecute ) { stmt . execute ( currentStatement ) ; log . trace ( "Executing statement: " + currentStatement + " OK!" ) ; } } catch ( SQLException e ) { throw new ChorusException ( String . format ( "Failed while executing statement [%s] on database + %s [%s]" , description , configName , e . toString ( ) , e ) ) ; } } | Execute one or more SQL statements |
22,794 | public final void stop ( ) { if ( this . thread != null ) { try { if ( this . thread != null ) { this . thread . interrupt ( ) ; synchronized ( this . thread ) { this . thread . notifyAll ( ) ; } } } finally { this . thread = null ; } } } | Stoppt das Rendern . |
22,795 | public static String getNameForBLZ ( String blz ) { BankInfo info = getBankInfo ( blz ) ; if ( info == null ) return "" ; return info . getName ( ) != null ? info . getName ( ) : "" ; } | Ermittelt zu einer gegebenen Bankleitzahl den Namen des Institutes . |
22,796 | public static List < BankInfo > searchBankInfo ( String query ) { if ( query != null ) query = query . trim ( ) ; List < BankInfo > list = new LinkedList < BankInfo > ( ) ; if ( query == null || query . length ( ) < 3 ) return list ; query = query . toLowerCase ( ) ; for ( BankInfo info : banks . values ( ) ) { String blz = info . getBlz ( ) ; String bic = info . getBic ( ) ; String name = info . getName ( ) ; String loc = info . getLocation ( ) ; if ( blz != null && blz . startsWith ( query ) ) { list . add ( info ) ; continue ; } if ( bic != null && bic . toLowerCase ( ) . startsWith ( query ) ) { list . add ( info ) ; continue ; } if ( name != null && name . toLowerCase ( ) . contains ( query ) ) { list . add ( info ) ; continue ; } if ( loc != null && loc . toLowerCase ( ) . contains ( query ) ) { list . add ( info ) ; continue ; } } Collections . sort ( list , new Comparator < BankInfo > ( ) { public int compare ( BankInfo o1 , BankInfo o2 ) { if ( o1 == null || o1 . getBlz ( ) == null ) return - 1 ; if ( o2 == null || o2 . getBlz ( ) == null ) return 1 ; return o1 . getBlz ( ) . compareTo ( o2 . getBlz ( ) ) ; } } ) ; return list ; } | Liefert eine Liste von Bank - Informationen die zum angegebenen Suchbegriff passen . |
22,797 | public static String getIBANForKonto ( Konto k ) { String konto = k . number ; if ( k . subnumber != null && k . subnumber . length ( ) > 0 && k . subnumber . matches ( "[0-9]{1,8}" ) && k . number . length ( ) + k . subnumber . length ( ) <= 10 ) konto += k . subnumber ; String zeros = "0000000000" ; String filledKonto = zeros . substring ( 0 , 10 - konto . length ( ) ) + konto ; StringBuffer sb = new StringBuffer ( ) ; sb . append ( k . blz ) ; sb . append ( filledKonto ) ; sb . append ( "1314" ) ; sb . append ( "00" ) ; BigInteger mod = new BigInteger ( sb . toString ( ) ) . mod ( new BigInteger ( "97" ) ) ; String checksum = String . valueOf ( 98 - mod . intValue ( ) ) ; if ( checksum . length ( ) < 2 ) checksum = "0" + checksum ; StringBuffer result = new StringBuffer ( ) ; result . append ( "DE" ) ; result . append ( checksum ) ; result . append ( k . blz ) ; result . append ( filledKonto ) ; return result . toString ( ) ; } | Berechnet die IBAN fuer ein angegebenes deutsches Konto . |
22,798 | public static String exception2StringShort ( Exception e ) { StringBuffer st = new StringBuffer ( ) ; Throwable e2 = e ; while ( e2 != null ) { String exClass = e2 . getClass ( ) . getName ( ) ; String msg = e2 . getMessage ( ) ; if ( msg != null ) { st . setLength ( 0 ) ; st . append ( exClass ) ; st . append ( ": " ) ; st . append ( msg ) ; } e2 = e2 . getCause ( ) ; } return st . toString ( ) . trim ( ) ; } | Extrahieren der root - Exception aus einer Exception - Chain . |
22,799 | public static String data2hex ( byte [ ] data ) { StringBuffer ret = new StringBuffer ( ) ; for ( int i = 0 ; i < data . length ; i ++ ) { String st = Integer . toHexString ( data [ i ] ) ; if ( st . length ( ) == 1 ) { st = '0' + st ; } st = st . substring ( st . length ( ) - 2 ) ; ret . append ( st ) . append ( " " ) ; } return ret . toString ( ) ; } | Wandelt ein Byte - Array in eine entsprechende hex - Darstellung um . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.