idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
22,700
private String createNewObject ( FedoraClient fedora , String oid ) throws Exception { InputStream in = null ; byte [ ] template = null ; // Start by reading our FOXML template into memory try { if ( foxmlTemplate != null ) { // We have a user provided template in = new FileInputStream ( foxmlTemplate ) ; template = IOUtils . toByteArray ( in ) ; } else { // Use the built in template 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 .
245
11
22,701
private void processDatastreams ( FedoraClient fedora , DigitalObject object , String vitalPid ) throws Exception { int sent = 0 ; // Each payload we care about needs to be sent for ( String ourPid : pids . keySet ( ) ) { // Fascinator packages have unpredictable names, // so we just use the extension // eg. 'e6e174fe-3508-4c8a-8530-1d6bb644d10a.tfpackage' 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 ) ; // Get our configuration 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 ) ; } } // MIME Type 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 ( ) ; // Default to binary data 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 ) ; } // Increase our counter sent ++ ; } // End for loop // Datastreams are taken care of, now handle attachments 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 .
741
16
22,702
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 .
53
12
22,703
private String [ ] resolveAltIds ( String [ ] oldArray , String mimeType , int count ) { // First, find the valid list we want String key = null ; for ( String mimeTest : attachAltIds . keySet ( ) ) { // Ignore 'default' if ( mimeTest . equals ( Strings . LITERAL_DEFAULT ) ) { continue ; } // Is it a broad group? if ( mimeTest . endsWith ( "/" ) ) { if ( mimeType . startsWith ( mimeTest ) ) { key = mimeTest ; } // Or a specific mime type? } else { if ( mimeType . equals ( mimeTest ) ) { key = mimeTest ; } } } // Use default if not found if ( key == null ) { key = Strings . LITERAL_DEFAULT ; } // Loop through the ids we're going to use for ( String newId : attachAltIds . get ( key ) ) { // If there is a format requirement, use it String formatted = String . format ( newId , count ) ; // Modify our arrray (if we it's not there) 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 .
270
28
22,704
private String [ ] growArray ( String [ ] oldArray , String newElement ) { // Look for the element first for ( String element : oldArray ) { if ( element . equals ( newElement ) ) { // If it's already there, we're done return oldArray ; } } log . debug ( "Adding ID: '{}'" , newElement ) ; // Ok, we know we need a new array int length = oldArray . length + 1 ; String [ ] newArray = new String [ length ] ; // Copy the old array contents System . arraycopy ( oldArray , 0 , newArray , 0 , oldArray . length ) ; // And the new element, and return 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 .
160
25
22,705
private boolean datastreamExists ( FedoraClient fedora , String vitalPid , String dsPid ) { try { // Some options: // * getAPIA().listDatastreams... seems best // * getAPIM().getDatastream... causes Exceptions against new IDs // * getAPIM().getDatastreams... is limited to a single state 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 .
170
14
22,706
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 .
78
19
22,707
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
56
15
22,708
private File getTempFile ( DigitalObject object , String pid ) throws Exception { // Create file in temp space, use OID in path for uniqueness File directory = new File ( tmpDir , object . getId ( ) ) ; File target = new File ( directory , pid ) ; if ( ! target . exists ( ) ) { target . getParentFile ( ) . mkdirs ( ) ; target . createNewFile ( ) ; } // These can happily throw exceptions higher Payload payload = object . getPayload ( pid ) ; InputStream in = payload . open ( ) ; FileOutputStream out = null ; // But here, the payload must receive // a close before throwing the error try { out = new FileOutputStream ( target ) ; IOUtils . copyLarge ( in , out ) ; } catch ( Exception ex ) { close ( out ) ; target . delete ( ) ; payload . close ( ) ; throw ex ; } // We close out here, because the catch statement needed to close // before it could delete... so it can't be in 'finally' close ( out ) ; payload . close ( ) ; return target ; }
Stream the data out of storage to our temp directory .
240
11
22,709
private byte [ ] getBytes ( DigitalObject object , String pid ) throws Exception { // These can happily throw exceptions higher Payload payload = object . getPayload ( pid ) ; InputStream in = payload . open ( ) ; byte [ ] result = null ; // But here, the payload must receive // a close before throwing the error 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 .
109
13
22,710
public static HashMap < String , String > find ( HashMap < String , String > props , String path ) { // Kein Pfad angegeben. Also treffen alle. if ( path == null || path . length ( ) == 0 ) return props ; // Die neue Map fuer die naechste Runde 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 ) ) // Beginnt mit? continue ; else if ( ! startsWith && endsWith && ! names [ 0 ] . endsWith ( key ) ) // Endet mit? continue ; else if ( startsWith && endsWith && ! names [ 0 ] . contains ( key ) ) // Enthaelt? continue ; else if ( ! startsWith && ! endsWith && ! names [ 0 ] . equals ( key ) ) // Ist gleich? continue ; // Wenn wir einen Wert haben, uebernehmen wir ihn in die naechste Runde. // Wir schneiden den geprueften Teil ab String newName = name . substring ( name . indexOf ( "." ) + 1 ) ; next . put ( newName , props . get ( name ) ) ; } // Wir sind hinten angekommen if ( ! path . contains ( "." ) ) return next ; // naechste Runde return find ( next , path . substring ( path . indexOf ( "." ) + 1 ) ) ; }
Sucht in props nach allen Schluesseln im genannten Pfad und liefert sie zurueck .
454
30
22,711
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
106
11
22,712
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
53
17
22,713
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 .
57
36
22,714
@ 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
64
14
22,715
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
50
11
22,716
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 .
33
42
22,717
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 .
89
14
22,718
public synchronized void startProcess ( String configName , String processName , Properties processProperties ) throws Exception { ProcessManagerConfig runtimeConfig = getProcessManagerConfig ( configName , processProperties ) ; if ( runtimeConfig . isEnabled ( ) ) { //could be disabled in some profiles 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
94
17
22,719
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
114
19
22,720
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 ; //skip (don't execute) the rest of the steps break ; case UNDEFINED : skip = true ; //skip (don't execute) the rest of the steps break ; case PENDING : skip = true ; //skip (don't execute) the rest of the steps break ; case TIMEOUT : skip = true ; //skip (don't execute) the rest of the steps 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
245
6
22,721
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
93
16
22,722
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 .
60
23
22,723
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
57
8
22,724
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
63
8
22,725
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
69
6
22,726
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
231
8
22,727
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 .
72
44
22,728
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 .
37
27
22,729
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 .
37
27
22,730
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
56
30
22,731
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 .
42
19
22,732
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 .
113
12
22,733
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
71
41
22,734
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
39
61
22,735
public void validate ( ) { if ( ! needsRequestTag || haveRequestTag ) { for ( MultipleSyntaxElements l : childContainers ) { l . validate ( ) ; } /* wenn keine exception geworfen wurde, dann ist das aktuelle element offensichtlich valid */ 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
79
85
22,736
public Object invokeStep ( String remoteStepInvokerId , String stepTokenId , List < String > params ) throws Exception { try { //call the remote method 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 ) ; //update the local context with any changes made remotely Map newContextState = r . getChorusContext ( ) ; ChorusContext . resetContext ( newContextState ) ; //return the result which the remote step method returned 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 .
249
34
22,737
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 .
105
12
22,738
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 ) ; //dispose handler instances with a scope which matches the scopeEnding if ( scope == scopeEnding ) { disposeSpringResources ( handler , scopeEnding ) ; } } }
Scope is ending perform the required processing on the supplied handlers .
120
12
22,739
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
93
19
22,740
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
144
12
22,741
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 ; } } // keine passende Version gefunden. Dann erzeugen wir selbst eine return test ; }
Liefert die SEPA - Version aus dem URN .
123
14
22,742
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 .
150
18
22,743
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 ( ) ; // Das ist das Element mit dem Namen "Document" 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 .
203
21
22,744
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 .
139
24
22,745
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 .
142
24
22,746
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 .
48
50
22,747
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 ) { //Timed out waiting for the step to run //We should try to cancel and interrupt the thread which is running the step - although this isn't //guaranteed to succeed. future . cancel ( true ) ; log . warn ( "A step failed to execute within " + timeout + " " + unit + ", attempting to cancel the step" ) ; //Here the step server should have timed out the step and proceed already - we don't need to send a failure message } catch ( Exception e ) { String ms = "Exception while executing step [" + e . getMessage ( ) + "]" ; log . error ( ms , e ) ; stepFailureConsumer . accept ( ms , executeStepMessage ) ; } } else { //server will time out this step 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
336
22
22,748
private Runnable runStepAndResetIsRunning ( Runnable runnable ) { return ( ) -> { try { runnable . run ( ) ; } catch ( Throwable t ) { //we're in control of the runnable and it should catch it's own execeptions, but just in case it doesn'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
107
41
22,749
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" ; //junit may not be in classpath so don't use Assert.class.getName() String junitLegacyClassName = "junit.framework.Assert" ; //need to support alternative (legacy?) junit 3 style 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
246
14
22,750
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
195
10
22,751
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 ) //be stricter than Boolean.parseValue || "false" . equalsIgnoreCase ( value ) ) { //do not accept 'wibble' as a boolean false value //dont create new Booleans (there are only 2 possible values) 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 ) ) { //attempt to convert the String to the most appropriate value result = ( T ) coerceObject ( value ) ; } } catch ( Throwable t ) { //Only log at debug since this failure may be an 'expected' NumberFormatException for example //There may be another handler method which provides a matching type and this is expected to fail //Even if something else has gone wrong with the conversion, we don't want to propagate errors since //this causes unpredictable output from the interpreter, we simply want the step not to be matched in this case log . debug ( "Exception when coercing value " + value + " to a " + requiredType , t ) ; } return result ; }
Will attempt to convert the String to the required type
609
10
22,752
private static < T > T coerceObject ( String value ) { T result ; //try boolean first if ( "true" . equals ( value ) || "false" . equals ( value ) ) { result = ( T ) ( Boolean ) Boolean . parseBoolean ( value ) ; } //then float numbers else if ( floatPattern . matcher ( value ) . matches ( ) ) { //handle overflow by converting to BigDecimal BigDecimal bd = new BigDecimal ( value ) ; Double d = bd . doubleValue ( ) ; result = ( T ) ( ( d == Double . NEGATIVE_INFINITY || d == Double . POSITIVE_INFINITY ) ? bd : d ) ; } //then int numbers else if ( intPattern . matcher ( value ) . matches ( ) ) { //handle overflow by converting to BigInteger BigInteger bd = new BigInteger ( value ) ; result = ( T ) ( bd . compareTo ( BigInteger . valueOf ( Long . MAX_VALUE ) ) == 1 ? bd : bd . longValue ( ) ) ; } //else just pass the String value to the Object parameter 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
261
78
22,753
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
46
19
22,754
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 ( ) ) ; //current properties which may be from properties files or classpath take precedence over db properties so merge them on top 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
254
23
22,755
public boolean isFatal ( ) { if ( this . fatal ) // dann brauchen wir den Cause nicht mehr checken return true ; Throwable t = this . getCause ( ) ; if ( t == this ) return false ; // sind wir selbst if ( t instanceof HBCI_Exception ) return ( ( HBCI_Exception ) t ) . isFatal ( ) ; return false ; }
Liefert true wenn die Exception oder ihr Cause als fatal eingestuft wurde .
94
25
22,756
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 .
72
8
22,757
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
264
7
22,758
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 .
65
8
22,759
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 .
55
21
22,760
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 ( ) ; // Anhand der BLZ? if ( blz != null && blz . startsWith ( query ) ) { list . add ( info ) ; continue ; } // Anhand der BIC? if ( bic != null && bic . toLowerCase ( ) . startsWith ( query ) ) { list . add ( info ) ; continue ; } // Anhand des Namens? if ( name != null && name . toLowerCase ( ) . contains ( query ) ) { list . add ( info ) ; continue ; } // Anhand des Orts? if ( loc != null && loc . toLowerCase ( ) . contains ( query ) ) { list . add ( info ) ; continue ; } } Collections . sort ( list , new Comparator < BankInfo > ( ) { /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @ Override 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 .
415
27
22,761
public static String getIBANForKonto ( Konto k ) { String konto = k . number ; // Die Unterkonto-Nummer muss mit eingerechnet werden. // Aber nur, wenn sie numerisch ist. Bei irgendeiner Bank wurde // "EUR" als Unterkontonummer verwendet. Das geht natuerlich nicht, // weil damit nicht gerechnet werden kann // Wir machen das auch nur dann, wenn beide Nummern zusammen max. // 10 Zeichen ergeben 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 ; ///////////////// // Pruefziffer berechnen // Siehe http://www.iban.de/iban-pruefsumme.html String zeros = "0000000000" ; String filledKonto = zeros . substring ( 0 , 10 - konto . length ( ) ) + konto ; // 10-stellig mit Nullen fuellen StringBuffer sb = new StringBuffer ( ) ; sb . append ( k . blz ) ; sb . append ( filledKonto ) ; sb . append ( "1314" ) ; // hartcodiert fuer "DE sb . append ( "00" ) ; // fest vorgegeben BigInteger mod = new BigInteger ( sb . toString ( ) ) . mod ( new BigInteger ( "97" ) ) ; // "97" ist fest vorgegeben in ISO // 7064/Modulo 97-10 String checksum = String . valueOf ( 98 - mod . intValue ( ) ) ; // "98" ist fest vorgegeben in ISO 7064/Modulo 97-10 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 .
531
23
22,762
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 .
130
16
22,763
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 = ' ' + st ; } st = st . substring ( st . length ( ) - 2 ) ; ret . append ( st ) . append ( " " ) ; } return ret . toString ( ) ; }
Wandelt ein Byte - Array in eine entsprechende hex - Darstellung um .
114
25
22,764
private static int [ ] string2Ints ( String st , int target_length ) { int [ ] numbers = new int [ target_length ] ; int st_len = st . length ( ) ; char ch ; for ( int i = 0 ; i < st_len ; i ++ ) { ch = st . charAt ( i ) ; numbers [ target_length - st_len + i ] = ch - ' ' ; } return numbers ; }
Used to convert a blz or an account number to an array of ints one array element per digit .
96
22
22,765
public static BigDecimal string2BigDecimal ( String st ) { BigDecimal result = new BigDecimal ( st ) ; result . setScale ( 2 , BigDecimal . ROUND_HALF_EVEN ) ; return result ; }
Konvertiert einen String in einen BigDecimal - Wert mit zwei Nachkommastellen .
54
27
22,766
static CloudResourceBundle loadBundle ( ServiceAccount serviceAccount , String bundleId , Locale locale ) { CloudResourceBundle crb = null ; ServiceClient client = ServiceClient . getInstance ( serviceAccount ) ; try { Map < String , String > resStrings = client . getResourceStrings ( bundleId , locale . toLanguageTag ( ) , false ) ; crb = new CloudResourceBundle ( resStrings ) ; } catch ( ServiceException e ) { logger . info ( "Could not fetch resource data for " + locale + " from the translation bundle " + bundleId + ": " + e . getMessage ( ) ) ; } return crb ; }
Package local factory method creating a new CloundResourceBundle instance for the specified service account bundle ID and locale .
144
23
22,767
public void checkDirectivesForKeyword ( DirectiveParser directiveParser , KeyWord keyWord ) throws ParseException { checkNoStepDirectiveBeforeKeyword ( directiveParser , keyWord ) ; checkForInvalidKeywordDirective ( directiveParser , keyWord ) ; }
If a keyword supports directives then we can have one more more keyword directives but no step directives before a keyword
56
21
22,768
public void checkForUnprocessedDirectives ( ) throws ParseException { List < LineNumberAndDirective > remaining = new LinkedList <> ( ) ; remaining . addAll ( bufferedKeyWordDirectives ) ; remaining . addAll ( bufferedStepDirectives ) ; if ( ! remaining . isEmpty ( ) ) { LineNumberAndDirective exampleError = remaining . get ( 0 ) ; throw new ParseException ( "Invalid trailing directive [" + exampleError . getDirective ( ) + "]" , exampleError . getLine ( ) ) ; } }
this catches for any unprocessed directives at the end of parsing
121
13
22,769
public ChorusHandlerJmxExporter export ( ) { if ( Boolean . getBoolean ( JMX_EXPORTER_ENABLED_PROPERTY ) ) { //export this object as an MBean if ( exported . getAndSet ( true ) == false ) { try { log . info ( String . format ( "Exporting ChorusHandlerJmxExporter with jmx name (%s)" , JMX_EXPORTER_NAME ) ) ; MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; mbs . registerMBean ( this , new ObjectName ( JMX_EXPORTER_NAME ) ) ; } catch ( Exception e ) { throw new ChorusException ( String . format ( "Failed to export ChorusHandlerJmxExporter with jmx name (%s)" , JMX_EXPORTER_NAME ) , e ) ; } } } else { log . info ( String . format ( "Will not export ChorusHandlerJmxExporter : '%s' system property must be set to true." , JMX_EXPORTER_ENABLED_PROPERTY ) ) ; } return this ; }
Call this method once all handlers are fully initialized to register the chorus remoting JMX bean and make all chorus handlers accessible remotely
253
25
22,770
protected MultipleSyntaxElements createAndAppendNewChildContainer ( Node ref , Document document ) { MultipleSyntaxElements ret = null ; if ( ( ( Element ) ref ) . getAttribute ( "minnum" ) . equals ( "0" ) ) { log . trace ( "will not create container " + getPath ( ) + " -> " + ( ( Element ) ref ) . getAttribute ( "type" ) + " " + "with minnum=0" ) ; } else { ret = super . createAndAppendNewChildContainer ( ref , document ) ; } return ret ; }
diesen ) .
128
4
22,771
private String [ ] getRefSegId ( Node segref , Document document ) { String segname = ( ( Element ) segref ) . getAttribute ( "type" ) ; // versuch, daten aus dem cache zu lesen String [ ] ret = new String [ ] { "" , "" } ; // segid noch nicht im cache Element segdef = document . getElementById ( segname ) ; NodeList valueElems = segdef . getElementsByTagName ( "value" ) ; int len = valueElems . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { // alle value-elemente durchlaufen und seghead.code und // seghead.version ermitteln Node valueNode = valueElems . item ( i ) ; if ( valueNode . getNodeType ( ) == Node . ELEMENT_NODE ) { String pathAttr = ( ( Element ) valueNode ) . getAttribute ( "path" ) ; if ( pathAttr . equals ( "SegHead.code" ) ) { // code gefunden ret [ 0 ] = valueNode . getFirstChild ( ) . getNodeValue ( ) ; } else if ( pathAttr . equals ( "SegHead.version" ) ) { // version gefunden ret [ 1 ] = valueNode . getFirstChild ( ) . getNodeValue ( ) ; } } } return ret ; }
erfolgen muss .
320
6
22,772
public static < T extends Enum < T > > Pattern createValidationPatternFromEnumType ( Class < T > enumType ) { String regEx = Stream . of ( enumType . getEnumConstants ( ) ) . map ( Enum :: name ) . collect ( Collectors . joining ( "|" , "(?i)" , "" ) ) ; //Enum constants may contain $ which needs to be escaped regEx = regEx . replace ( "$" , "\\$" ) ; return Pattern . compile ( regEx ) ; }
Create a regular expression which will match any of the values from the supplied enum type
116
16
22,773
private AccountReport22 createDay ( BTag tag ) throws Exception { AccountReport22 report = new AccountReport22 ( ) ; if ( tag != null ) { report . getBal ( ) . add ( this . createSaldo ( tag . start , true ) ) ; report . getBal ( ) . add ( this . createSaldo ( tag . end , false ) ) ; } if ( tag != null && tag . my != null ) { CashAccount36 acc = new CashAccount36 ( ) ; AccountIdentification4Choice id = new AccountIdentification4Choice ( ) ; id . setIBAN ( tag . my . iban ) ; acc . setId ( id ) ; acc . setCcy ( tag . my . curr ) ; BranchAndFinancialInstitutionIdentification5 svc = new BranchAndFinancialInstitutionIdentification5 ( ) ; FinancialInstitutionIdentification8 inst = new FinancialInstitutionIdentification8 ( ) ; svc . setFinInstnId ( inst ) ; inst . setBICFI ( tag . my . bic ) ; report . setAcct ( acc ) ; } return report ; }
Erzeugt den Header des Buchungstages .
239
12
22,774
private CashBalance8 createSaldo ( Saldo saldo , boolean start ) throws Exception { CashBalance8 bal = new CashBalance8 ( ) ; BalanceType13 bt = new BalanceType13 ( ) ; bt . setCdOrPrtry ( new BalanceType10Choice ( ) ) ; bt . getCdOrPrtry ( ) . setCd ( start ? "PRCD" : "CLBD" ) ; bal . setTp ( bt ) ; ActiveOrHistoricCurrencyAndAmount amt = new ActiveOrHistoricCurrencyAndAmount ( ) ; bal . setAmt ( amt ) ; if ( saldo != null && saldo . value != null ) { amt . setCcy ( saldo . value . getCurr ( ) ) ; amt . setValue ( saldo . value . getBigDecimalValue ( ) ) ; } long ts = saldo != null && saldo . timestamp != null ? saldo . timestamp . getTime ( ) : 0 ; // Startsaldo ist in CAMT der Endsaldo vom Vortag. Daher muessen wir noch einen Tag abziehen if ( start && ts > 0 ) ts -= 24 * 60 * 60 * 1000L ; DateAndDateTime2Choice date = new DateAndDateTime2Choice ( ) ; date . setDt ( this . createCalendar ( ts ) ) ; bal . setDt ( date ) ; return bal ; }
Erzeugt ein Saldo - Objekt .
313
13
22,775
private XMLGregorianCalendar createCalendar ( Long timestamp ) throws Exception { DatatypeFactory df = DatatypeFactory . newInstance ( ) ; GregorianCalendar cal = new GregorianCalendar ( ) ; cal . setTimeInMillis ( timestamp != null ? timestamp . longValue ( ) : System . currentTimeMillis ( ) ) ; return df . newXMLGregorianCalendar ( cal ) ; }
Erzeugt ein Calendar - Objekt .
90
12
22,776
@ Step ( ".*wait (?:for )?([0-9]*) seconds?.*" ) @ Documentation ( order = 10 , description = "Wait for a number of seconds" , example = "And I wait for 6 seconds" ) public void waitForSeconds ( int seconds ) { try { Thread . sleep ( seconds * 1000 ) ; } catch ( InterruptedException e ) { log . error ( "Thread interrupted while sleeping" , e ) ; } }
Simple timer to make the calling thread sleep
98
8
22,777
public static XMLGregorianCalendar createCalendar ( String isoDate ) throws Exception { if ( isoDate == null ) { SimpleDateFormat format = new SimpleDateFormat ( DATETIME_FORMAT ) ; isoDate = format . format ( new Date ( ) ) ; } DatatypeFactory df = DatatypeFactory . newInstance ( ) ; return df . newXMLGregorianCalendar ( isoDate ) ; }
Erzeugt ein neues XMLCalender - Objekt .
91
18
22,778
public static String format ( XMLGregorianCalendar cal , String format ) { if ( cal == null ) return null ; if ( format == null ) format = DATE_FORMAT ; SimpleDateFormat df = new SimpleDateFormat ( format ) ; return df . format ( cal . toGregorianCalendar ( ) . getTime ( ) ) ; }
Formatiert den XML - Kalender im angegebenen Format .
74
16
22,779
public static Date toDate ( XMLGregorianCalendar cal ) { if ( cal == null ) return null ; return cal . toGregorianCalendar ( ) . getTime ( ) ; }
Liefert ein Date - Objekt fuer den Kalender .
40
16
22,780
public static Integer maxIndex ( HashMap < String , String > properties ) { Integer max = null ; for ( String key : properties . keySet ( ) ) { Matcher m = INDEX_PATTERN . matcher ( key ) ; if ( m . matches ( ) ) { int index = Integer . parseInt ( m . group ( 1 ) ) ; if ( max == null || index > max ) { max = index ; } } } return max ; }
Ermittelt den maximalen Index aller indizierten Properties . Nicht indizierte Properties werden ignoriert .
98
30
22,781
public static String insertIndex ( String key , Integer index ) { if ( index == null ) return key ; int pos = key . indexOf ( ' ' ) ; if ( pos >= 0 ) { return key . substring ( 0 , pos ) + ' ' + index + ' ' + key . substring ( pos ) ; } else { return key + ' ' + index + ' ' ; } }
Fuegt einen Index in den Property - Key ein . Wurde kein Index angegeben wird der Key unveraendert zurueckgeliefert .
84
41
22,782
public static Value sumBtgValueObject ( HashMap < String , String > properties ) { Integer maxIndex = maxIndex ( properties ) ; BigDecimal btg = sumBtgValue ( properties , maxIndex ) ; String curr = properties . get ( insertIndex ( "btg.curr" , maxIndex == null ? null : 0 ) ) ; return new Value ( btg , curr ) ; }
Liefert ein Value - Objekt mit den Summen des Auftrages .
88
20
22,783
public static String getProperty ( HashMap < String , String > props , String name , String defaultValue ) { String value = props . get ( name ) ; return value != null && value . length ( ) > 0 ? value : defaultValue ; }
Liefert den Wert des Properties oder den Default - Wert . Der Default - Wert wird nicht nur bei NULL verwendet sondern auch bei Leerstring .
52
45
22,784
protected PrintWriter getPrintWriter ( ) { if ( printWriter == null || printStream != ChorusOut . out ) { printWriter = new PrintWriter ( ChorusOut . out ) ; printStream = ChorusOut . out ; } return printWriter ; }
This is an extension point to change Chorus output
55
10
22,785
public Object invoke ( final String stepTokenId , final List < String > args ) { final AtomicReference resultRef = new AtomicReference ( ) ; PolledAssertion p = new PolledAssertion ( ) { protected void validate ( ) throws Exception { Object r = wrappedInvoker . invoke ( stepTokenId , args ) ; resultRef . set ( r ) ; } protected int getPollPeriodMillis ( ) { return ( int ) pollFrequency ; } } ; retryAttempts = doTest ( p , timeUnit , length ) ; Object result = resultRef . get ( ) ; return result ; }
Invoke the method
130
4
22,786
private String waitForPattern ( long timeout , TailLogBufferedReader bufferedReader , Pattern pattern , boolean searchWithinLines , long timeoutInSeconds ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; String result ; label : while ( true ) { while ( bufferedReader . ready ( ) ) { int c = bufferedReader . read ( ) ; if ( c != - 1 ) { if ( c == ' ' || c == ' ' ) { if ( sb . length ( ) > 0 ) { Matcher m = pattern . matcher ( sb ) ; boolean match = searchWithinLines ? m . find ( ) : m . matches ( ) ; if ( match ) { result = sb . toString ( ) ; break label ; } else { sb . setLength ( 0 ) ; } } } else { sb . append ( ( char ) c ) ; } } } //nothing more to read, does the current output match the pattern? if ( sb . length ( ) > 0 && searchWithinLines ) { Matcher m = pattern . matcher ( sb ) ; if ( m . find ( ) ) { result = m . group ( 0 ) ; break label ; } } try { Thread . sleep ( 10 ) ; //avoid a busy loop since we are using nonblocking ready() / read() } catch ( InterruptedException e ) { } checkTimeout ( timeout , timeoutInSeconds ) ; if ( process . isStopped ( ) && ! bufferedReader . ready ( ) ) { ChorusAssert . fail ( process . isExitWithFailureCode ( ) ? "Process stopped with error code " + process . getExitCode ( ) + " while waiting for match" : "Process stopped while waiting for match" ) ; } } return result ; }
read ahead without blocking and attempt to match the pattern
384
10
22,787
static BankInfo parse ( String text ) { BankInfo info = new BankInfo ( ) ; if ( text == null || text . length ( ) == 0 ) return info ; String [ ] cols = text . split ( "\\|" ) ; info . setName ( getValue ( cols , 0 ) ) ; info . setLocation ( getValue ( cols , 1 ) ) ; info . setBic ( getValue ( cols , 2 ) ) ; info . setChecksumMethod ( getValue ( cols , 3 ) ) ; info . setRdhAddress ( getValue ( cols , 4 ) ) ; info . setPinTanAddress ( getValue ( cols , 5 ) ) ; info . setRdhVersion ( HBCIVersion . byId ( getValue ( cols , 6 ) ) ) ; info . setPinTanVersion ( HBCIVersion . byId ( getValue ( cols , 7 ) ) ) ; return info ; }
Parst die BankInfo - Daten aus einer Zeile der blz . properties .
206
20
22,788
private static String getValue ( String [ ] cols , int idx ) { if ( cols == null || idx >= cols . length ) return null ; return cols [ idx ] ; }
Liefert den Wert aus der angegebenen Spalte .
44
18
22,789
public GroupedPropertyLoader splitKeyAndGroup ( final String keyDelimiter ) { return group ( new BiFunction < String , String , Tuple3 < String , String , String > > ( ) { public Tuple3 < String , String , String > apply ( String key , String value ) { String [ ] keyTokens = key . split ( keyDelimiter , 2 ) ; if ( keyTokens . length == 1 ) { keyTokens = new String [ ] { "" , keyTokens [ 0 ] } ; } return Tuple3 . tuple3 ( keyTokens [ 0 ] , keyTokens [ 1 ] , value ) ; } } ) ; }
Split the key into 2 and use the first token to group
137
12
22,790
@ Override public void execute ( ) throws BuildException { Java javaTask = ( Java ) getProject ( ) . createTask ( "java" ) ; javaTask . setTaskName ( getTaskName ( ) ) ; javaTask . setClassname ( "org.chorusbdd.chorus.Main" ) ; javaTask . setClasspath ( classpath ) ; //if log4j config is set then pass this on to new process String value = System . getProperty ( "log4j.configuration" ) ; if ( value != null ) { Environment . Variable sysp = new Environment . Variable ( ) ; sysp . setKey ( "log4j.configuration" ) ; sysp . setValue ( value ) ; javaTask . addSysproperty ( sysp ) ; } //provide the verbose flag if ( verbose ) { javaTask . createArg ( ) . setValue ( "-verbose" ) ; } //set the feature file args javaTask . createArg ( ) . setValue ( "-f" ) ; for ( File featureFile : featureFiles ) { System . out . println ( "Found feature " + featureFile ) ; javaTask . createArg ( ) . setFile ( featureFile ) ; } System . out . println ( "Classpath " + classpath ) ; //set the base packges args javaTask . createArg ( ) . setValue ( "-h" ) ; for ( String basePackage : handlerBasePackages . split ( "," ) ) { javaTask . createArg ( ) . setValue ( basePackage . trim ( ) ) ; } javaTask . setFork ( true ) ; int exitStatus = javaTask . executeJava ( ) ; if ( exitStatus != 0 ) { String failMessage = "Chorus feature failed, see test results for details." ; if ( failOnTestFailure ) { throw new BuildException ( failMessage ) ; } else { log ( failMessage , Project . MSG_ERR ) ; } } else { log ( "Chorus features all passed" , Project . MSG_INFO ) ; } }
Launches Chorus and runs the Interpreter over the speficied feature files
442
18
22,791
public void addConfiguredFileset ( FileSet fs ) { File dir = fs . getDir ( ) ; DirectoryScanner ds = fs . getDirectoryScanner ( ) ; String [ ] fileNames = ds . getIncludedFiles ( ) ; for ( String fileName : fileNames ) { featureFiles . add ( new File ( dir , fileName ) ) ; } }
Used to set the list of feature files that will be processed
81
12
22,792
protected void marshal ( JAXBElement e , OutputStream os , boolean validate ) throws Exception { JAXBContext jaxbContext = JAXBContext . newInstance ( e . getDeclaredType ( ) ) ; Marshaller marshaller = jaxbContext . createMarshaller ( ) ; // Wir verwenden hier hart UTF-8. Siehe http://www.onlinebanking-forum.de/forum/topic.php?p=107420#real107420 marshaller . setProperty ( Marshaller . JAXB_ENCODING , ENCODING ) ; // Siehe https://groups.google.com/d/msg/hbci4java/RYHCai_TzHM/72Bx51B9bXUJ if ( System . getProperty ( "sepa.pain.formatted" , "false" ) . equalsIgnoreCase ( "true" ) ) marshaller . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , Boolean . TRUE ) ; SepaVersion version = this . getSepaVersion ( ) ; if ( version != null ) { String schemaLocation = version . getSchemaLocation ( ) ; if ( schemaLocation != null ) { LOG . fine ( "appending schemaLocation " + schemaLocation ) ; marshaller . setProperty ( Marshaller . JAXB_SCHEMA_LOCATION , schemaLocation ) ; } String file = version . getFile ( ) ; if ( file != null ) { if ( validate ) { Source source = null ; InputStream is = this . getClass ( ) . getClassLoader ( ) . getResourceAsStream ( file ) ; if ( is != null ) { source = new StreamSource ( is ) ; } else { // Fallback auf File-Objekt File f = new File ( file ) ; if ( f . isFile ( ) && f . canRead ( ) ) source = new StreamSource ( f ) ; } if ( source == null ) throw new HBCI_Exception ( "schema validation activated against " + file + " - but schema file " + "could not be found" ) ; LOG . fine ( "activating schema validation against " + file ) ; SchemaFactory schemaFactory = SchemaFactory . newInstance ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; Schema schema = schemaFactory . newSchema ( source ) ; marshaller . setSchema ( schema ) ; } } } marshaller . marshal ( e , os ) ; }
Schreibt die Bean mittels JAXB in den Strean .
561
17
22,793
public static QRCode tryParse ( String hhd , String msg ) { try { return new QRCode ( hhd , msg ) ; } catch ( Exception e ) { return null ; } }
Versucht die Daten als QR - Code zu parsen .
43
16
22,794
private String decode ( byte [ ] bytes ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < bytes . length ; ++ i ) { sb . append ( Integer . toString ( bytes [ i ] , 10 ) ) ; } return sb . toString ( ) ; }
Decodiert die Bytes als String .
68
10
22,795
public Map < String , Object > getServiceCredentials ( ) { if ( serviceCredentials == null ) { return null ; } return Collections . unmodifiableMap ( serviceCredentials ) ; }
Returns the credentials used for accessing the machine translation service .
44
11
22,796
public Properties loadPropertiesForSubGroup ( ConfigurationManager configurationManager , String handlerPrefix , String groupName ) { PropertyOperations handlerProps = properties ( loadProperties ( configurationManager , handlerPrefix ) ) ; PropertyOperations defaultProps = handlerProps . filterByAndRemoveKeyPrefix ( ChorusConstants . DEFAULT_PROPERTIES_GROUP + "." ) ; PropertyOperations configProps = handlerProps . filterByAndRemoveKeyPrefix ( groupName + "." ) ; PropertyOperations merged = defaultProps . merge ( configProps ) ; return merged . loadProperties ( ) ; }
Get properties for a specific config for a handler which maintains properties grouped by configNames
136
16
22,797
private String replaceVariablesWithPatterns ( String pattern ) { int group = 0 ; Matcher findVariablesMatcher = variablePattern . matcher ( pattern ) ; while ( findVariablesMatcher . find ( ) ) { String variable = findVariablesMatcher . group ( 0 ) ; pattern = pattern . replaceFirst ( variable , "(.+)" ) ; variableToGroupNumber . put ( variable , ++ group ) ; } return pattern ; }
find and replace any variables in the form
95
8
22,798
public boolean processStep ( StepToken scenarioStep , List < StepMacro > macros , boolean alreadymatched ) { boolean stepMacroMatched = doProcessStep ( scenarioStep , macros , 0 , alreadymatched ) ; return stepMacroMatched ; }
Process a scenario step adding child steps if it matches this StepMacro
53
14
22,799
private String replaceVariablesInMacroStep ( Matcher macroMatcher , String action ) { for ( Map . Entry < String , Integer > e : variableToGroupNumber . entrySet ( ) ) { action = action . replace ( e . getKey ( ) , "<$" + e . getValue ( ) + ">" ) ; } return action ; }
replace the variables using regular expresson group syntax
76
9