idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
22,800 | 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 - '0' ; } return numbers ; } | Used to convert a blz or an account number to an array of ints one array element per digit . |
22,801 | 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 . |
22,802 | 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 . |
22,803 | 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 |
22,804 | 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 |
22,805 | public ChorusHandlerJmxExporter export ( ) { if ( Boolean . getBoolean ( JMX_EXPORTER_ENABLED_PROPERTY ) ) { 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 |
22,806 | 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 ) . |
22,807 | private String [ ] getRefSegId ( Node segref , Document document ) { String segname = ( ( Element ) segref ) . getAttribute ( "type" ) ; String [ ] ret = new String [ ] { "" , "" } ; Element segdef = document . getElementById ( segname ) ; NodeList valueElems = segdef . getElementsByTagName ( "value" ) ; int len = valueElems . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { Node valueNode = valueElems . item ( i ) ; if ( valueNode . getNodeType ( ) == Node . ELEMENT_NODE ) { String pathAttr = ( ( Element ) valueNode ) . getAttribute ( "path" ) ; if ( pathAttr . equals ( "SegHead.code" ) ) { ret [ 0 ] = valueNode . getFirstChild ( ) . getNodeValue ( ) ; } else if ( pathAttr . equals ( "SegHead.version" ) ) { ret [ 1 ] = valueNode . getFirstChild ( ) . getNodeValue ( ) ; } } } return ret ; } | erfolgen muss . |
22,808 | public static < T extends Enum < T > > Pattern createValidationPatternFromEnumType ( Class < T > enumType ) { String regEx = Stream . of ( enumType . getEnumConstants ( ) ) . map ( Enum :: name ) . collect ( Collectors . joining ( "|" , "(?i)" , "" ) ) ; regEx = regEx . replace ( "$" , "\\$" ) ; return Pattern . compile ( regEx ) ; } | Create a regular expression which will match any of the values from the supplied enum type |
22,809 | 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 . |
22,810 | 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 ; 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 . |
22,811 | 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 . |
22,812 | @ 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 |
22,813 | 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 . |
22,814 | 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 . |
22,815 | public static Date toDate ( XMLGregorianCalendar cal ) { if ( cal == null ) return null ; return cal . toGregorianCalendar ( ) . getTime ( ) ; } | Liefert ein Date - Objekt fuer den Kalender . |
22,816 | 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 . |
22,817 | 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 . |
22,818 | 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 . |
22,819 | 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 . |
22,820 | 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 |
22,821 | 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 |
22,822 | 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 == '\n' || c == '\r' ) { 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 ) ; } } } if ( sb . length ( ) > 0 && searchWithinLines ) { Matcher m = pattern . matcher ( sb ) ; if ( m . find ( ) ) { result = m . group ( 0 ) ; break label ; } } try { Thread . sleep ( 10 ) ; } 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 |
22,823 | 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 . |
22,824 | 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 . |
22,825 | 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 |
22,826 | public void execute ( ) throws BuildException { Java javaTask = ( Java ) getProject ( ) . createTask ( "java" ) ; javaTask . setTaskName ( getTaskName ( ) ) ; javaTask . setClassname ( "org.chorusbdd.chorus.Main" ) ; javaTask . setClasspath ( classpath ) ; 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 ) ; } if ( verbose ) { javaTask . createArg ( ) . setValue ( "-verbose" ) ; } javaTask . createArg ( ) . setValue ( "-f" ) ; for ( File featureFile : featureFiles ) { System . out . println ( "Found feature " + featureFile ) ; javaTask . createArg ( ) . setFile ( featureFile ) ; } System . out . println ( "Classpath " + classpath ) ; 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 |
22,827 | 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 |
22,828 | protected void marshal ( JAXBElement e , OutputStream os , boolean validate ) throws Exception { JAXBContext jaxbContext = JAXBContext . newInstance ( e . getDeclaredType ( ) ) ; Marshaller marshaller = jaxbContext . createMarshaller ( ) ; marshaller . setProperty ( Marshaller . JAXB_ENCODING , ENCODING ) ; 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 { 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 . |
22,829 | 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 . |
22,830 | 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 . |
22,831 | public Map < String , Object > getServiceCredentials ( ) { if ( serviceCredentials == null ) { return null ; } return Collections . unmodifiableMap ( serviceCredentials ) ; } | Returns the credentials used for accessing the machine translation service . |
22,832 | 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 |
22,833 | 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 |
22,834 | 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 |
22,835 | 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 |
22,836 | private String replaceGroupsInMacroStep ( Matcher macroMatcher , String action ) { Matcher groupMatcher = groupPattern . matcher ( action ) ; while ( groupMatcher . find ( ) ) { String match = groupMatcher . group ( ) ; String groupString = match . substring ( 2 , match . length ( ) - 1 ) ; int groupId = Integer . parseInt ( groupString ) ; if ( groupId > macroMatcher . groupCount ( ) ) { throw new ChorusException ( "Capture group with index " + groupId + " in StepMacro step '" + action + "' did not have a matching capture group in the pattern '" + pattern . toString ( ) + "'" ) ; } String replacement = macroMatcher . group ( groupId ) ; replacement = RegexpUtils . escapeRegexReplacement ( replacement ) ; log . trace ( "Replacing group " + match + " with " + replacement + " in action " + action ) ; action = action . replaceFirst ( "<\\$" + groupId + ">" , replacement ) ; } return action ; } | capturing group from the macroMatcher |
22,837 | public static StepEndState calculateStepMacroEndState ( List < StepToken > executedSteps ) { StepEndState stepMacroEndState = StepEndState . PASSED ; for ( StepToken s : executedSteps ) { if ( s . getEndState ( ) != StepEndState . PASSED ) { stepMacroEndState = s . getEndState ( ) ; break ; } } return stepMacroEndState ; } | The end state of a step macro step is derived from the child steps If all child steps are PASSED then the step macro will be PASSED otherwise the step macro end state is taken from the first child step which was not PASSED |
22,838 | private boolean isBooleanSwitchProperty ( ExecutionProperty property ) { return property . hasDefaults ( ) && property . getDefaults ( ) . length == 1 && property . getDefaults ( ) [ 0 ] . equals ( "false" ) ; } | This is a property with a boolean value which defaults to false |
22,839 | public static boolean alg_24 ( int [ ] blz , int [ ] number ) { int [ ] weights = { 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 } ; int crc = 0 ; int idx = 0 ; switch ( number [ 0 ] ) { case 3 : case 4 : case 5 : case 6 : number [ 0 ] = 0 ; break ; case 9 : number [ 0 ] = number [ 1 ] = number [ 2 ] = 0 ; break ; default : break ; } for ( int i = 0 ; i < 9 ; i ++ ) { if ( number [ i ] > 0 ) { idx = i ; break ; } } for ( int i = idx , j = 0 ; i < 9 ; i ++ , j ++ ) { crc += ( ( weights [ j ] * number [ i ] ) + weights [ j ] ) % 11 ; } return ( ( crc % 10 ) == number [ 9 ] ) ; } | code by Gerd Balzuweit |
22,840 | private List < HashMap < String , String > > createSegmentListFromMessage ( String msg ) { List < HashMap < String , String > > segmentList = new ArrayList < HashMap < String , String > > ( ) ; boolean quoteNext = false ; int startPosi = 0 ; for ( int i = 0 ; i < msg . length ( ) ; i ++ ) { char ch = msg . charAt ( i ) ; if ( ! quoteNext && ch == '@' ) { int idx = msg . indexOf ( "@" , i + 1 ) ; String len_st = msg . substring ( i + 1 , idx ) ; i += Integer . parseInt ( len_st ) + 1 + len_st . length ( ) ; } else if ( ! quoteNext && ch == '\'' ) { HashMap < String , String > segmentInfo = new HashMap < > ( ) ; segmentInfo . put ( "code" , msg . substring ( startPosi , msg . indexOf ( ":" , startPosi ) ) ) ; segmentInfo . put ( "start" , Integer . toString ( startPosi ) ) ; segmentInfo . put ( "length" , Integer . toString ( i - startPosi + 1 ) ) ; segmentList . add ( segmentInfo ) ; startPosi = i + 1 ; } quoteNext = ! quoteNext && ch == '?' ; } return segmentList ; } | Liste mit segmentInfo - Properties aus der Nachricht erzeugen |
22,841 | private static Gson createGson ( String className ) { GsonBuilder builder = new GsonBuilder ( ) ; builder . setDateFormat ( "yyyy-MM-dd'T'HH:mm:ss.SSSX" ) ; builder . registerTypeAdapter ( TranslationStatus . class , new EnumWithFallbackAdapter < TranslationStatus > ( TranslationStatus . UNKNOWN ) ) ; builder . registerTypeAdapter ( TranslationRequestStatus . class , new EnumWithFallbackAdapter < TranslationRequestStatus > ( TranslationRequestStatus . UNKNOWN ) ) ; builder . registerTypeAdapter ( new TypeToken < EnumMap < TranslationStatus , Integer > > ( ) { } . getType ( ) , new EnumMapInstanceCreator < TranslationStatus , Integer > ( TranslationStatus . class ) ) ; builder . registerTypeAdapterFactory ( new NullMapValueTypeAdapterFactory ( ) ) ; return builder . create ( ) ; } | Creates a new Gson object |
22,842 | public void writeToStdIn ( String text , boolean newLine ) { if ( outputStream == null ) { outputStream = new BufferedOutputStream ( process . getOutputStream ( ) ) ; outputWriter = new BufferedWriter ( new OutputStreamWriter ( outputStream ) ) ; } try { outputWriter . write ( text ) ; if ( newLine ) { outputWriter . newLine ( ) ; } outputWriter . flush ( ) ; outputStream . flush ( ) ; } catch ( IOException e ) { getLog ( ) . debug ( "Error when writing to process in for " + this , e ) ; ChorusAssert . fail ( "IOException when writing line to process" ) ; } } | Write the text to the std in of the process |
22,843 | private void suppressLog4jLogging ( ) { if ( ! log4jLoggingSuppressed . getAndSet ( true ) ) { Logger logger = Logger . getLogger ( "org.apache.http" ) ; logger . setLevel ( Level . ERROR ) ; logger . addAppender ( new ConsoleAppender ( ) ) ; } } | We don t want this in the Chorus interpreter output by default |
22,844 | private void suppressSeleniumJavaUtilLogging ( ) { if ( ! seleniumLoggingSuppressed . getAndSet ( true ) ) { try { Properties properties = new Properties ( ) ; properties . setProperty ( "org.openqa.selenium.remote.ProtocolHandshake.level" , "OFF" ) ; properties . setProperty ( "org.openqa.selenium.remote.ProtocolHandshake.useParentHandlers" , "false" ) ; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; properties . store ( byteArrayOutputStream , "seleniumLoggingProperties" ) ; byte [ ] bytes = byteArrayOutputStream . toByteArray ( ) ; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream ( bytes ) ; LogManager . getLogManager ( ) . readConfiguration ( byteArrayInputStream ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } | We don t want that in the Chorus interpreter output by default |
22,845 | public void setSuiteIdsUsingZeroBasedIndex ( ) { synchronized ( cachedSuites ) { List < WebAgentTestSuite > s = new ArrayList < > ( cachedSuites . values ( ) ) ; cachedSuites . clear ( ) ; for ( int index = 0 ; index < s . size ( ) ; index ++ ) { WebAgentTestSuite suite = s . get ( index ) ; cachedSuites . put ( suite . getTestSuiteName ( ) + "-" + index , suite ) ; } } } | A testing hook to set the cached suites to have predictable keys |
22,846 | public void setSegVersion ( int version ) { if ( version < 1 ) { log . warn ( "tried to change segment version for task " + this . jobName + " explicit, but no version given" ) ; return ; } if ( version == this . segVersion ) return ; log . info ( "changing segment version for task " + this . jobName + " explicit from " + this . segVersion + " to " + version ) ; String oldName = this . name ; this . segVersion = version ; this . name = this . jobName + version ; String [ ] names = this . llParams . keySet ( ) . toArray ( new String [ 0 ] ) ; for ( String s : names ) { if ( ! s . startsWith ( oldName ) ) continue ; String value = this . llParams . get ( s ) ; String newName = s . replaceFirst ( oldName , this . name ) ; this . llParams . remove ( s ) ; this . llParams . put ( newName , value ) ; } constraints . forEach ( ( frontendName , values ) -> { for ( String [ ] value : values ) { if ( ! value [ 0 ] . startsWith ( oldName ) ) continue ; value [ 0 ] = value [ 0 ] . replaceFirst ( oldName , this . name ) ; } } ) ; } | Legt die Versionsnummer des Segments manuell fest . Ist u . a . noetig um HKTAN - Segmente in genau der Version zu senden in der auch die HITANS empfangen wurden . Andernfalls koennte es passieren dass wir ein HKTAN mit einem TAN - Verfahren senden welches in dieser HKTAN - Version gar nicht von der Bank unterstuetzt wird . Das ist ein Dirty - Hack ich weiss ; ) Falls das noch IRGENDWO anders verwendet wird muss man hoellisch aufpassen dass alle Stellen wo this . name bzw . this . segVersion direkt oder indirekt verwendet wurde ebenfalls beruecksichtigt werden . |
22,847 | public Konto getOrderAccount ( ) { String prefix = this . getName ( ) + ".My." ; String number = this . getLowlevelParam ( prefix + "number" ) ; String iban = this . getLowlevelParam ( prefix + "iban" ) ; if ( ( number == null || number . length ( ) == 0 ) && ( iban == null || iban . length ( ) == 0 ) ) { prefix = this . getName ( ) + ".KTV." ; number = this . getLowlevelParam ( prefix + "number" ) ; iban = this . getLowlevelParam ( prefix + "iban" ) ; if ( ( number == null || number . length ( ) == 0 ) && ( iban == null || iban . length ( ) == 0 ) ) return null ; } Konto k = new Konto ( ) ; k . number = number ; k . iban = iban ; k . bic = this . getLowlevelParam ( prefix + "bic" ) ; k . subnumber = this . getLowlevelParam ( prefix + "subnumber" ) ; k . blz = this . getLowlevelParam ( prefix + "KIK.blz" ) ; k . country = this . getLowlevelParam ( prefix + "KIK.country" ) ; return k ; } | Liefert das Auftraggeber - Konto wie es ab HKTAN5 erforderlich ist . |
22,848 | void put ( HashMap < String , String > props , Names name , String value ) { if ( value == null ) return ; props . put ( name . getValue ( ) , value ) ; } | Speichert den Wert in den Properties . |
22,849 | public DocumentTranslationRequestDataChangeSet setTargetLanguagesMap ( Map < String , Map < String , Set < String > > > targetLanguagesMap ) { if ( targetLanguagesMap == null ) { throw new NullPointerException ( "The input map is null." ) ; } this . targetLanguagesMap = targetLanguagesMap ; return this ; } | Sets a map containing target languages indexed by document ids . This method adopts the input map without creating a safe copy . |
22,850 | public EndState getEndState ( ) { EndState result = EndState . PASSED ; for ( ScenarioToken s : scenarios ) { if ( s . getEndState ( ) == EndState . FAILED ) { result = EndState . FAILED ; break ; } } if ( result != EndState . FAILED ) { for ( ScenarioToken s : scenarios ) { if ( s . getEndState ( ) == EndState . PENDING ) { result = EndState . PENDING ; } } } return result ; } | fail if any scenarios failed otherwise pending if any pending or passed |
22,851 | public boolean propagateValue ( String destPath , String valueString , boolean tryToCreate , boolean allowOverwrite ) { boolean ret = false ; if ( destPath . equals ( getPath ( ) ) ) { if ( this . value != null ) { if ( ! allowOverwrite ) { throw new OverwriteException ( getPath ( ) , value . toString ( ) , valueString ) ; } } setValue ( valueString ) ; ret = true ; } return ret ; } | setzen des wertes des de |
22,852 | private void parseValue ( StringBuffer res , HashMap < String , String > predefs , char preDelim , HashMap < String , String > valids ) { int len = res . length ( ) ; if ( preDelim != ( char ) 0 && res . charAt ( 0 ) != preDelim ) { if ( len == 0 ) { throw new ParseErrorException ( HBCIUtils . getLocMsg ( "EXCMSG_ENDOFSTRG" , getPath ( ) ) ) ; } throw new PredelimErrorException ( getPath ( ) , Character . toString ( preDelim ) , Character . toString ( res . charAt ( 0 ) ) ) ; } this . value = SyntaxDEFactory . createSyntaxDE ( getType ( ) , getPath ( ) , res , minsize , maxsize ) ; String valueString = value . toString ( 0 ) ; String predefined = predefs . get ( getPath ( ) ) ; if ( predefined != null ) { if ( ! valueString . equals ( predefined ) ) { throw new ParseErrorException ( HBCIUtils . getLocMsg ( "EXCMSG_PREDEFERR" , new Object [ ] { getPath ( ) , predefined , value } ) ) ; } } boolean atLeastOne = false ; boolean ok = false ; if ( valids != null ) { String header = getPath ( ) + ".value" ; for ( String key : valids . keySet ( ) ) { if ( key . startsWith ( header ) && key . indexOf ( "." , header . length ( ) ) == - 1 ) { atLeastOne = true ; String validValue = valids . get ( key ) ; if ( valueString . equals ( validValue ) ) { ok = true ; break ; } } } } if ( atLeastOne && ! ok ) { throw new NoValidValueException ( getPath ( ) , valueString ) ; } } | anlegen eines de beim parsen funktioniert analog zum anlegen eines de bei der message - synthese |
22,853 | static ObjectMapper getMapper ( ) { ObjectMapper mapper = new ObjectMapper ( ) ; mapper . setSerializationInclusion ( Include . NON_NULL ) ; mapper . setVisibility ( PropertyAccessor . ALL , JsonAutoDetect . Visibility . NONE ) ; mapper . setVisibility ( PropertyAccessor . FIELD , JsonAutoDetect . Visibility . ANY ) ; mapper . configure ( SerializationFeature . WRITE_DATES_AS_TIMESTAMPS , false ) ; DateFormat dateFormat = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" ) ; mapper . setDateFormat ( dateFormat ) ; return mapper ; } | Return the internal ObjectMapper |
22,854 | public Map < String , Set < String > > getTargetLanguagesByBundle ( ) { if ( targetLanguagesByBundle == null ) { assert false ; return Collections . emptyMap ( ) ; } return Collections . unmodifiableMap ( targetLanguagesByBundle ) ; } | Returns the map containing target languages indexed by bundle IDs . This method always returns non - null map . |
22,855 | private void setMsgSizeValue ( int value , boolean allowOverwrite ) { String absPath = getPath ( ) + ".MsgHead.msgsize" ; SyntaxElement msgsizeElem = getElement ( absPath ) ; if ( msgsizeElem == null ) throw new NoSuchPathException ( absPath ) ; int size = ( ( DE ) msgsizeElem ) . getMinSize ( ) ; char [ ] zeros = new char [ size ] ; Arrays . fill ( zeros , '0' ) ; DecimalFormat df = new DecimalFormat ( String . valueOf ( zeros ) ) ; if ( ! propagateValue ( absPath , df . format ( value ) , DONT_TRY_TO_CREATE , allowOverwrite ) ) throw new NoSuchPathException ( absPath ) ; } | setzen des feldes nachrichtengroesse im nachrichtenkopf einer nachricht |
22,856 | static String [ ] getClasspathFileNames ( ) throws IOException { ChorusLog log = ChorusLogFactory . getLog ( ClasspathScanner . class ) ; log . debug ( "Getting file names " + Thread . currentThread ( ) . getName ( ) ) ; long start = System . currentTimeMillis ( ) ; if ( classpathNames == null ) { classpathNames = findClassNames ( ) ; log . debug ( "Getting file names took " + ( System . currentTimeMillis ( ) - start ) + " millis" ) ; } return classpathNames ; } | Returns the fully qualified class names of all the classes in the classpath . Checks directories and zip files . The FilenameFilter will be applied only to files that are in the zip files and the directories . In other words the filter will not be used to sort directories . |
22,857 | static TokenLifeCycleManager getInstance ( final String iamEndpoint , final String apiKey ) { if ( iamEndpoint == null || iamEndpoint . isEmpty ( ) ) { throw new IllegalArgumentException ( "Cannot initialize with null or empty IAM endpoint." ) ; } if ( apiKey == null || apiKey . isEmpty ( ) ) { throw new IllegalArgumentException ( "Cannot initialize with null or empty IAM apiKey." ) ; } return getInstanceUnchecked ( iamEndpoint , apiKey ) ; } | Get an instance of TokenLifeCylceManager . Single instance is maintained for each unique pair of iamEndpoint and apiKey . The method is thread safe . |
22,858 | static TokenLifeCycleManager getInstance ( final String jsonCredentials ) { final JsonObject credentials = new JsonParser ( ) . parse ( jsonCredentials ) . getAsJsonObject ( ) ; if ( credentials . get ( "apikey" ) == null || credentials . get ( "apikey" ) . isJsonNull ( ) || credentials . get ( "apikey" ) . getAsString ( ) . isEmpty ( ) ) { throw new IllegalArgumentException ( "IAM API Key value is either not available, or null or is empty in credentials JSON." ) ; } if ( credentials . get ( "iam_endpoint" ) == null || credentials . get ( "iam_endpoint" ) . isJsonNull ( ) || credentials . get ( "iam_endpoint" ) . getAsString ( ) . isEmpty ( ) ) { throw new IllegalArgumentException ( "IAM endpoint Key value is either not available, or null or is empty in credentials JSON." ) ; } final String apiKey = credentials . get ( "apikey" ) . getAsString ( ) ; final String iamEndpoint = credentials . get ( "iam_endpoint" ) . getAsString ( ) ; return getInstanceUnchecked ( iamEndpoint , apiKey ) ; } | Get an instance of TokenLifeCylceManager . Single instance is maintained for each unique pair of iamEndpoint and apiKey . The method and the returned instance is thread safe . |
22,859 | private static BigInteger adjustJ ( BigInteger J , BigInteger modulus ) { byte [ ] ba = J . toByteArray ( ) ; int last = ba [ ba . length - 1 ] ; if ( ( last & 0x0F ) == 0x0C ) { return J ; } BigInteger twelve = new BigInteger ( "12" ) ; byte [ ] modulus2 = modulus . subtract ( twelve ) . toByteArray ( ) ; int last2 = modulus2 [ modulus2 . length - 1 ] ; if ( ( last & 0x0F ) == ( last2 & 0x0F ) ) { return modulus . subtract ( J ) ; } return null ; } | entweder x oder n - x zurueckgeben |
22,860 | public static List < String > getNames ( String nameList ) { String [ ] names = nameList . split ( "," ) ; List < String > results = new LinkedList < > ( ) ; for ( String p : names ) { String configName = p . trim ( ) ; if ( configName . length ( ) > 0 ) { results . add ( configName ) ; } } return results ; } | Get a List of process names from a comma separated list |
22,861 | public void applyParams ( AbstractHBCIJob task , AbstractHBCIJob hktan , HBCITwoStepMechanism hbciTwoStepMechanism ) { String code = task . getHBCICode ( ) ; Job job = this . getData ( code ) ; if ( job == null ) { log . info ( "have no challenge data for " + code + ", will not apply challenge params" ) ; return ; } HHDVersion version = HHDVersion . find ( hbciTwoStepMechanism ) ; log . debug ( "using hhd version " + version ) ; HhdVersion hhd = job . getVersion ( version . getChallengeVersion ( ) ) ; if ( hhd == null ) { log . info ( "have no challenge data for " + code + " in " + version + ", will not apply challenge params" ) ; return ; } String klass = hhd . getKlass ( ) ; log . debug ( "using challenge klass " + klass ) ; hktan . setParam ( "challengeklass" , klass ) ; List < Param > params = hhd . getParams ( ) ; for ( int i = 0 ; i < params . size ( ) ; ++ i ) { int num = i + 1 ; Param param = params . get ( i ) ; if ( ! param . isComplied ( hbciTwoStepMechanism ) ) { log . debug ( "skipping challenge parameter " + num + " (" + param . path + "), condition " + param . conditionName + "=" + param . conditionValue + " not complied" ) ; continue ; } String value = param . getValue ( task ) ; if ( value == null || value . length ( ) == 0 ) { log . debug ( "challenge parameter " + num + " (" + param . path + ") is empty" ) ; continue ; } log . debug ( "adding challenge parameter " + num + " " + param . path + "=" + value ) ; hktan . setParam ( "ChallengeKlassParam" + num , value ) ; } } | Uebernimmt die Challenge - Parameter in den HKTAN - Geschaeftsvorfall . |
22,862 | private Optional < String > findClientIdForWebSocket ( WebSocket conn ) { return clientIdToSocket . entrySet ( ) . stream ( ) . filter ( e -> e . getValue ( ) == conn ) . map ( Map . Entry :: getKey ) . findFirst ( ) ; } | Unless a client has sent a CONNECT message we will not have a client Id associated with the socket |
22,863 | private void mergeProperties ( Map < ExecutionConfigSource , Map < ExecutionProperty , List < String > > > sourceToPropertiesMap ) { for ( ExecutionConfigSource s : propertySources ) { Map < ExecutionProperty , List < String > > properties = sourceToPropertiesMap . get ( s ) ; for ( ExecutionProperty p : properties . keySet ( ) ) { List < String > valuesFromSource = properties . get ( p ) ; if ( valuesFromSource != null && ! valuesFromSource . isEmpty ( ) ) { List < String > vals = getOrCreatePropertyValues ( p ) ; mergeValues ( valuesFromSource , p , vals ) ; } } } } | deermine the final set of properties according to PropertySourceMode for each property |
22,864 | public boolean isTrue ( ExecutionProperty property ) { return isSet ( property ) && propertyMap . get ( property ) . size ( ) == 1 && "true" . equalsIgnoreCase ( propertyMap . get ( property ) . get ( 0 ) ) ; } | for boolean properties is the property set true |
22,865 | @ Initialize ( scope = Scope . SCENARIO ) public void initializeContextVariables ( ) { Properties p = new HandlerConfigLoader ( ) . loadProperties ( configurationManager , "context" ) ; for ( Map . Entry e : p . entrySet ( ) ) { ChorusContext . getContext ( ) . put ( e . getKey ( ) . toString ( ) , e . getValue ( ) . toString ( ) ) ; } } | Load any context properties defined in handler configuration files |
22,866 | void updateBPD ( HashMap < String , String > result ) { log . debug ( "extracting BPD from results" ) ; HashMap < String , String > newBPD = new HashMap < > ( ) ; result . keySet ( ) . forEach ( key -> { if ( key . startsWith ( "BPD." ) ) { newBPD . put ( key . substring ( ( "BPD." ) . length ( ) ) , result . get ( key ) ) ; } } ) ; if ( newBPD . size ( ) != 0 ) { newBPD . put ( BPD_KEY_HBCIVERSION , passport . getHBCIVersion ( ) ) ; newBPD . put ( BPD_KEY_LASTUPDATE , String . valueOf ( System . currentTimeMillis ( ) ) ) ; passport . setBPD ( newBPD ) ; log . info ( "installed new BPD with version " + passport . getBPDVersion ( ) ) ; passport . getCallback ( ) . status ( HBCICallback . STATUS_INST_BPD_INIT_DONE , passport . getBPD ( ) ) ; } } | gets the BPD out of the result and store it in the passport field |
22,867 | void extractKeys ( HashMap < String , String > result ) { boolean foundChanges = false ; try { log . debug ( "extracting public institute keys from results" ) ; for ( int i = 0 ; i < 3 ; i ++ ) { String head = HBCIUtils . withCounter ( "SendPubKey" , i ) ; String keyType = result . get ( head + ".KeyName.keytype" ) ; if ( keyType == null ) continue ; String keyCountry = result . get ( head + ".KeyName.KIK.country" ) ; String keyBLZ = result . get ( head + ".KeyName.KIK.blz" ) ; String keyUserId = result . get ( head + ".KeyName.userid" ) ; String keyNum = result . get ( head + ".KeyName.keynum" ) ; String keyVersion = result . get ( head + ".KeyName.keyversion" ) ; log . info ( "found key " + keyCountry + "_" + keyBLZ + "_" + keyUserId + "_" + keyType + "_" + keyNum + "_" + keyVersion ) ; byte [ ] keyExponent = result . get ( head + ".PubKey.exponent" ) . getBytes ( CommPinTan . ENCODING ) ; byte [ ] keyModulus = result . get ( head + ".PubKey.modulus" ) . getBytes ( CommPinTan . ENCODING ) ; KeyFactory fac = KeyFactory . getInstance ( "RSA" ) ; KeySpec spec = new RSAPublicKeySpec ( new BigInteger ( + 1 , keyModulus ) , new BigInteger ( + 1 , keyExponent ) ) ; Key key = fac . generatePublic ( spec ) ; if ( keyType . equals ( "S" ) ) { passport . setInstSigKey ( new HBCIKey ( keyCountry , keyBLZ , keyUserId , keyNum , keyVersion , key ) ) ; foundChanges = true ; } else if ( keyType . equals ( "V" ) ) { passport . setInstEncKey ( new HBCIKey ( keyCountry , keyBLZ , keyUserId , keyNum , keyVersion , key ) ) ; foundChanges = true ; } } } catch ( Exception e ) { String msg = HBCIUtils . getLocMsg ( "EXCMSG_EXTR_IKEYS_ERR" ) ; throw new HBCI_Exception ( msg , e ) ; } if ( foundChanges ) { passport . getCallback ( ) . status ( HBCICallback . STATUS_INST_GET_KEYS_DONE , null ) ; } } | gets the server public keys from the result and store them in the passport |
22,868 | private boolean isBPDExpired ( ) { Map < String , String > bpd = passport . getBPD ( ) ; log . info ( "[BPD] max age: " + maxAge + " days" ) ; long maxMillis = - 1L ; try { int days = Integer . parseInt ( maxAge ) ; if ( days == 0 ) { log . info ( "[BPD] auto-expiry disabled" ) ; return false ; } if ( days > 0 ) maxMillis = days * 24 * 60 * 60 * 1000L ; } catch ( NumberFormatException e ) { log . error ( e . getMessage ( ) , e ) ; return false ; } long lastUpdate = 0L ; if ( bpd != null ) { String lastUpdateProperty = bpd . get ( BPD_KEY_LASTUPDATE ) ; try { lastUpdate = lastUpdateProperty != null ? Long . parseLong ( lastUpdateProperty ) : lastUpdate ; } catch ( NumberFormatException e ) { log . error ( e . getMessage ( ) , e ) ; return false ; } log . info ( "[BPD] last update: " + ( lastUpdate == 0 ? "never" : new Date ( lastUpdate ) ) ) ; } long now = System . currentTimeMillis ( ) ; if ( maxMillis < 0 || ( now - lastUpdate ) > maxMillis ) { log . info ( "[BPD] expired, will be updated now" ) ; return true ; } return false ; } | Prueft ob die BPD abgelaufen sind und neu geladen werden muessen . |
22,869 | void fetchBPDAnonymous ( ) { Map < String , String > bpd = passport . getBPD ( ) ; String hbciVersionOfBPD = ( bpd != null ) ? bpd . get ( BPD_KEY_HBCIVERSION ) : null ; final String version = passport . getBPDVersion ( ) ; if ( version . equals ( "0" ) || isBPDExpired ( ) || hbciVersionOfBPD == null || ! hbciVersionOfBPD . equals ( passport . getHBCIVersion ( ) ) ) { try { if ( ! version . equals ( "0" ) ) { log . info ( "resetting BPD version from " + version + " to 0" ) ; passport . getBPD ( ) . put ( "BPA.version" , "0" ) ; } passport . getCallback ( ) . status ( HBCICallback . STATUS_INST_BPD_INIT , null ) ; log . info ( "fetching BPD" ) ; HBCIMsgStatus msgStatus = anonymousDialogInit ( ) ; updateBPD ( msgStatus . getData ( ) ) ; if ( ! msgStatus . isDialogClosed ( ) ) { anonymousDialogEnd ( msgStatus . getData ( ) ) ; } if ( ! msgStatus . isOK ( ) ) { log . error ( "fetching BPD failed" ) ; throw new ProcessException ( HBCIUtils . getLocMsg ( "ERR_INST_BPDFAILED" ) , msgStatus ) ; } } catch ( HBCI_Exception e ) { if ( e . isFatal ( ) ) throw e ; } catch ( Exception e ) { log . info ( "FAILED! - maybe this institute does not support anonymous logins" ) ; log . info ( "we will nevertheless go on" ) ; } } log . debug ( "checking if requested hbci parameters are supported" ) ; if ( passport . getBPD ( ) != null ) { if ( ! Arrays . asList ( passport . getSuppVersions ( ) ) . contains ( passport . getHBCIVersion ( ) ) ) { String msg = HBCIUtils . getLocMsg ( "EXCMSG_VERSIONNOTSUPP" ) ; throw new InvalidUserDataException ( msg ) ; } } else { log . warn ( "can not check if requested parameters are supported" ) ; } } | Aktualisiert die BPD bei Bedarf . |
22,870 | private List < FeatureToken > getFeaturesWithConfigurations ( List < String > configurationNames , FeatureToken parsedFeature ) { List < FeatureToken > results = new ArrayList < > ( ) ; if ( parsedFeature != null ) { if ( configurationNames == null ) { results . add ( parsedFeature ) ; } else { createFeaturesWithConfigurations ( configurationNames , parsedFeature , results ) ; } } return results ; } | If parsedFeature has no configurations then we can return a single item list containg the parsedFeature If configurations are present we need to return a list with one feature per supported configuration |
22,871 | private List < String > extractTagsAndResetLastTagsLineField ( ) { String tags = lastTagsLine ; List < String > result = extractTags ( tags ) ; resetLastTagsLine ( ) ; return result ; } | Extracts the tags from the lastTagsLine field before setting it to null . |
22,872 | public TranslationRequestDataChangeSet setTargetLanguagesByBundle ( Map < String , Set < String > > targetLanguagesByBundle ) { if ( targetLanguagesByBundle == null ) { throw new NullPointerException ( "The input map is null." ) ; } this . targetLanguagesByBundle = targetLanguagesByBundle ; return this ; } | Sets a map containing target languages indexed by bundle IDs . This method adopts the input map without creating a safe copy . |
22,873 | private void addFeaturesRecursively ( File directory , List < File > targetList , FileFilter fileFilter ) { File [ ] files = directory . listFiles ( ) ; Arrays . sort ( files , new Comparator < File > ( ) { public int compare ( File o1 , File o2 ) { return o1 . getName ( ) . compareTo ( o2 . getName ( ) ) ; } } ) ; for ( File f : files ) { if ( f . isDirectory ( ) ) { addFeaturesRecursively ( f , targetList , fileFilter ) ; } else if ( fileFilter . accept ( f ) ) { targetList . add ( f ) ; } } } | Recursively scans subdirectories adding all feature files to the targetList . |
22,874 | public int await ( TimeUnit unit , long length ) { int pollPeriodMillis = getPollPeriodMillis ( ) ; long startTime = System . currentTimeMillis ( ) ; long expireTime = startTime + unit . toMillis ( length ) ; int iteration = 0 ; boolean success = false ; while ( true ) { iteration ++ ; try { validate ( ) ; success = true ; break ; } catch ( Throwable r ) { if ( r instanceof FailImmediatelyException ) { throw ( FailImmediatelyException ) r ; } else if ( r . getCause ( ) instanceof FailImmediatelyException ) { throw ( FailImmediatelyException ) r . getCause ( ) ; } } sleepUntil ( startTime + ( pollPeriodMillis * iteration ) ) ; if ( System . currentTimeMillis ( ) >= expireTime ) { break ; } } if ( ! success ) { try { validate ( ) ; } catch ( Throwable e ) { propagateAsError ( e ) ; } } return iteration ; } | Wait for the assertions to pass for the specified time limit |
22,875 | public int check ( TimeUnit timeUnit , long count ) { int pollPeriodMillis = getPollPeriodMillis ( ) ; long startTime = System . currentTimeMillis ( ) ; long expireTime = startTime + timeUnit . toMillis ( count ) ; int iteration = 0 ; while ( true ) { iteration ++ ; try { validate ( ) ; } catch ( Throwable t ) { propagateAsError ( t ) ; } sleepUntil ( startTime + ( pollPeriodMillis * iteration ) ) ; if ( System . currentTimeMillis ( ) >= expireTime ) { break ; } } return iteration ; } | check that the assertions pass for the whole duration of the period specified |
22,876 | private void propagateAsError ( Throwable t ) { if ( t instanceof InvocationTargetException ) { t = t . getCause ( ) ; } if ( Error . class . isAssignableFrom ( t . getClass ( ) ) ) { throw ( Error ) t ; } throw new PolledAssertionError ( t ) ; } | Otherwise wrap with a PolledAssertionError and throw |
22,877 | public static Object stripDeep ( Object decorated ) { Object stripped = stripShallow ( decorated ) ; if ( stripped == decorated ) { return stripped ; } else { return stripDeep ( stripped ) ; } } | Strips all decorations from the decorated object . |
22,878 | public static < T > void writeObject ( final T entity , final Object destination , final String comment ) { try { JAXBContext jaxbContext ; if ( entity instanceof JAXBElement ) { jaxbContext = JAXBContext . newInstance ( ( ( JAXBElement ) entity ) . getValue ( ) . getClass ( ) ) ; } else { jaxbContext = JAXBContext . newInstance ( entity . getClass ( ) ) ; } Marshaller marshaller = jaxbContext . createMarshaller ( ) ; marshaller . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , true ) ; if ( StringUtils . isNotBlank ( comment ) ) { marshaller . setProperty ( "com.sun.xml.bind.xmlHeaders" , comment ) ; } if ( destination instanceof java . io . OutputStream ) { marshaller . marshal ( entity , ( OutputStream ) destination ) ; } else if ( destination instanceof java . io . File ) { marshaller . marshal ( entity , ( java . io . File ) destination ) ; } else if ( destination instanceof java . io . Writer ) { marshaller . marshal ( entity , ( java . io . Writer ) destination ) ; } else { throw new IllegalArgumentException ( "Unsupported destination." ) ; } } catch ( final JAXBException e ) { throw new SwidException ( "Cannot write object." , e ) ; } } | Write XML entity to the given destination . |
22,879 | public static < T > String writeObjectToString ( final T entity ) { ByteArrayOutputStream destination = new ByteArrayOutputStream ( ) ; writeObject ( entity , destination , null ) ; return destination . toString ( ) ; } | Write XML entity to the string . |
22,880 | public static String generateRegId ( final String domainCreationDate , final String reverseDomainName ) { return generateRegId ( domainCreationDate , reverseDomainName , null ) ; } | Generate RegId . |
22,881 | public static String generateRegId ( final String domainCreationDate , final String reverseDomainName , final String suffix ) { if ( StringUtils . isBlank ( domainCreationDate ) ) { throw new SwidException ( "domainCreationDate isn't defined" ) ; } if ( StringUtils . isBlank ( reverseDomainName ) ) { throw new SwidException ( "reverseDomainName isn't defined" ) ; } StringBuilder res = new StringBuilder ( ) . append ( "regid" ) . append ( DELIMITER ) . append ( domainCreationDate ) . append ( DELIMITER ) . append ( reverseDomainName ) ; if ( StringUtils . isNotBlank ( suffix ) ) { res . append ( "," ) . append ( suffix ) ; } return res . toString ( ) ; } | Generate RegId with additional suffix . |
22,882 | public void setGenerator ( final IdGenerator generator ) { if ( generator != null ) { this . idGenerator = generator ; swidTag . setId ( idGenerator . nextId ( ) ) ; } } | Set element identifier generator . |
22,883 | public void validate ( ) { if ( swidTag . getEntitlementRequiredIndicator ( ) == null ) { throw new SwidException ( "'entitlement_required_indicator' is not set" ) ; } if ( swidTag . getProductTitle ( ) == null ) { throw new SwidException ( "'product_title' is not set" ) ; } if ( swidTag . getProductVersion ( ) == null ) { throw new SwidException ( "'product_version' is not set" ) ; } if ( swidTag . getSoftwareCreator ( ) == null ) { throw new SwidException ( "'software_creator' is not set" ) ; } if ( swidTag . getSoftwareLicensor ( ) == null ) { throw new SwidException ( "'software_licensor' is not set" ) ; } if ( swidTag . getSoftwareId ( ) == null ) { throw new SwidException ( "'software_id' is not set" ) ; } if ( swidTag . getTagCreator ( ) == null ) { throw new SwidException ( "'tag_creator' is not set" ) ; } } | Validate whether processor configuration is valid . |
22,884 | public void write ( final SoftwareIdentificationTagComplexType swidTag , final java . io . OutputStream output ) { JAXBUtils . writeObject ( objectFactory . createSoftwareIdentificationTag ( swidTag ) , output , getComment ( ) ) ; } | Write the object into an output stream . |
22,885 | public void write ( final SoftwareIdentificationTagComplexType swidTag , final File file ) { JAXBUtils . writeObject ( objectFactory . createSoftwareIdentificationTag ( swidTag ) , file , getComment ( ) ) ; } | Write the object into a file . |
22,886 | public void write ( final SoftwareIdentificationTagComplexType swidTag , final java . io . Writer writer ) { JAXBUtils . writeObject ( objectFactory . createSoftwareIdentificationTag ( swidTag ) , writer , getComment ( ) ) ; } | Write the object into a Writer . |
22,887 | public static URLConnection post ( String url , String encodedCredentials , String jsonPayloadObject , Charset charset , ProxyConfig proxy , TrustStoreConfig customTrustStore , ConnectionSettings connectionSettings ) throws Exception { if ( url == null || encodedCredentials == null || jsonPayloadObject == null ) { throw new IllegalArgumentException ( "arguments cannot be null" ) ; } byte [ ] bytes = jsonPayloadObject . getBytes ( charset ) ; URLConnection conn = getConnection ( url , proxy ) ; if ( customTrustStore != null && customTrustStore . getTrustStorePath ( ) != null && conn instanceof HttpsURLConnection ) { KeyStore trustStore = TrustStoreManagerService . getInstance ( ) . getTrustStoreManager ( ) . loadTrustStore ( customTrustStore . getTrustStorePath ( ) , customTrustStore . getTrustStoreType ( ) , customTrustStore . getTrustStorePassword ( ) ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; tmf . init ( trustStore ) ; SSLContext ctx = SSLContext . getInstance ( "TLS" ) ; ctx . init ( null , tmf . getTrustManagers ( ) , null ) ; SSLSocketFactory sslSocketFactory = ctx . getSocketFactory ( ) ; ( ( HttpsURLConnection ) conn ) . setSSLSocketFactory ( sslSocketFactory ) ; } conn . setDoOutput ( true ) ; conn . setUseCaches ( false ) ; ( ( HttpURLConnection ) conn ) . setFixedLengthStreamingMode ( bytes . length ) ; conn . setRequestProperty ( "Authorization" , "Basic " + encodedCredentials ) ; conn . setRequestProperty ( "Content-Type" , "application/json" ) ; conn . setRequestProperty ( "Accept" , "application/json, text/plain" ) ; if ( connectionSettings . getReadTimeout ( ) != null ) { conn . setReadTimeout ( connectionSettings . getReadTimeout ( ) ) ; } if ( connectionSettings . getConnectTimeout ( ) != null ) { conn . setConnectTimeout ( connectionSettings . getConnectTimeout ( ) ) ; } conn . setRequestProperty ( "aerogear-sender" , "AeroGear Java Sender" ) ; ( ( HttpURLConnection ) conn ) . setRequestMethod ( "POST" ) ; OutputStream out = null ; try { out = conn . getOutputStream ( ) ; out . write ( bytes ) ; } finally { if ( out != null ) { out . close ( ) ; } } return conn ; } | Returns URLConnection that posts the given JSON to the given UnifiedPush Server URL . |
22,888 | private void submitPayload ( String url , HttpRequestUtil . ConnectionSettings connectionSettings , String jsonPayloadObject , String pushApplicationId , String masterSecret , MessageResponseCallback callback , List < String > redirectUrls ) { if ( redirectUrls . contains ( url ) ) { throw new PushSenderException ( "The site contains an infinite redirect loop! Duplicate url: " + url ) ; } else { redirectUrls . add ( url ) ; } HttpURLConnection httpURLConnection = null ; try { final String credentials = pushApplicationId + ':' + masterSecret ; final String encoded = Base64 . encodeBytes ( credentials . getBytes ( UTF_8 ) ) ; httpURLConnection = ( HttpURLConnection ) HttpRequestUtil . post ( url , encoded , jsonPayloadObject , UTF_8 , proxy , customTrustStore , connectionSettings ) ; final int statusCode = httpURLConnection . getResponseCode ( ) ; logger . log ( Level . INFO , String . format ( "HTTP Response code from UnifiedPush Server: %s" , statusCode ) ) ; if ( isRedirect ( statusCode ) ) { String redirectURL = httpURLConnection . getHeaderField ( "Location" ) ; logger . log ( Level . INFO , String . format ( "Performing redirect to '%s'" , redirectURL ) ) ; submitPayload ( redirectURL , pushConfiguration . getConnectionSettings ( ) , jsonPayloadObject , pushApplicationId , masterSecret , callback , redirectUrls ) ; } else if ( statusCode >= 400 ) { logger . log ( Level . SEVERE , "The Unified Push Server returned status code: " + statusCode ) ; throw new PushSenderHttpException ( statusCode ) ; } else { if ( callback != null ) { callback . onComplete ( ) ; } } } catch ( PushSenderHttpException pshe ) { throw pshe ; } catch ( Exception e ) { logger . log ( Level . INFO , "Error happening while trying to send the push delivery request" , e ) ; throw new PushSenderException ( e . getMessage ( ) , e ) ; } finally { if ( httpURLConnection != null ) { httpURLConnection . disconnect ( ) ; } } } | The actual method that does the real send and connection handling |
22,889 | public void prePersist ( ) { this . createdAt = getCurrentTime ( ) ; if ( this . createdBy == null || this . createdBy . trim ( ) . length ( ) < 1 ) { this . createdBy = getUserName ( ) ; } } | Called by JPA container before sql insert . |
22,890 | private static String concatOverrides ( String annotation , Collection < String > attributeOverrides ) { if ( attributeOverrides == null || attributeOverrides . size ( ) < 1 ) { return annotation ; } if ( annotation == null ) { annotation = "" ; } else { Matcher overrideMatcher ; while ( ( overrideMatcher = PATTERN_ATTR_OVERRIDE . matcher ( annotation ) ) . find ( ) ) { if ( ! ( attributeOverrides instanceof ArrayList ) ) { attributeOverrides = new ArrayList < String > ( attributeOverrides ) ; } ( ( ArrayList ) attributeOverrides ) . add ( 0 , overrideMatcher . group ( 1 ) ) ; annotation = annotation . substring ( 0 , overrideMatcher . start ( ) ) + annotation . substring ( overrideMatcher . end ( ) ) ; } } Matcher overridesMatcher = PATTERN_ATTR_OVERRIDES . matcher ( annotation ) ; if ( ! overridesMatcher . find ( ) ) { annotation = ( annotation . length ( ) < 1 ? "" : annotation + "\n " ) + "@" + AttributeOverrides . class . getName ( ) + "({})" ; } for ( String addOverride : attributeOverrides ) { overridesMatcher = PATTERN_ATTR_OVERRIDES . matcher ( annotation ) ; if ( ! overridesMatcher . find ( ) ) { throw new IllegalStateException ( ) ; } if ( StringUtils . isNotEmpty ( overridesMatcher . group ( 2 ) ) ) { addOverride = ", " + addOverride ; } annotation = annotation . substring ( 0 , overridesMatcher . start ( 3 ) ) + addOverride + annotation . substring ( overridesMatcher . start ( 3 ) ) ; } return annotation ; } | merges given collection of javax . persistence . AttributeOverride elements into an optionally existing javax . persistence . AttributeOverrides annotation with optionally pre - existing javax . persistence . AttributeOverride elements . |
22,891 | public static void schemaExportPerform ( String [ ] sqlCommands , List exporters , SchemaExport schemaExport ) { if ( schemaExportPerform == null ) { try { schemaExportPerform = SchemaExport . class . getMethod ( "performApi" , String [ ] . class , List . class , String . class ) ; } catch ( NoSuchMethodException e ) { LOG . error ( "cannot find api method inserted by patch" , e ) ; } } String [ ] wrapArr = new String [ 1 ] ; for ( String sqlCommand : sqlCommands ) { for ( String singleSql : splitSQL ( sqlCommand ) ) { SqlStatement ddlStmt = prepareDDL ( singleSql ) ; wrapArr [ 0 ] = ddlStmt . getSql ( ) ; boolean emptyStatement = isEmptyStatement ( singleSql ) ; try { List passedExporters = new ArrayList ( ) ; passedExporters . add ( null ) ; for ( Object exporter : exporters ) { passedExporters . set ( 0 , exporter ) ; boolean databaseExporter = exporter . getClass ( ) . getSimpleName ( ) . equals ( "DatabaseExporter" ) ; if ( ! databaseExporter || ! emptyStatement ) { schemaExportPerform . invoke ( schemaExport , new Object [ ] { wrapArr , passedExporters , databaseExporter ? null : ddlStmt . getDelimiter ( ) } ) ; } } } catch ( InvocationTargetException e ) { if ( e . getCause ( ) instanceof SQLException && ! emptyStatement ) { LOG . warn ( "failed executing sql: {}" , singleSql ) ; LOG . warn ( "failure: {}" , e . getCause ( ) . getMessage ( ) ) ; } } catch ( Exception e ) { LOG . error ( "cannot call patched api method in SchemaExport" , e ) ; } } } } | Hibernate 4 . 3 . 5 |
22,892 | public void run ( ) { stopped = false ; try { try { serverSocket = new ServerSocket ( port ) ; serverSocket . setSoTimeout ( TIMEOUT ) ; } finally { startupBarrier . countDown ( ) ; } while ( ! isStopped ( ) ) { if ( ! semaphore . tryAcquire ( ) ) { throw new IllegalStateException ( "Could not get semaphore, number of possible threads is too low." ) ; } try { final Socket socket ; try { socket = serverSocket . accept ( ) ; } catch ( @ SuppressWarnings ( "unused" ) Exception e ) { continue ; } BufferedReader input = new BufferedReader ( new InputStreamReader ( socket . getInputStream ( ) , "UTF-8" ) ) ; PrintWriter out = new PrintWriter ( socket . getOutputStream ( ) ) ; synchronized ( this ) { List < SmtpMessage > messages = handleTransaction ( out , input ) ; receivedMail . addAll ( messages ) ; } socket . close ( ) ; } finally { semaphore . release ( ) ; } } } catch ( Exception e ) { log . log ( Level . SEVERE , "Caught exception: " , e ) ; } finally { if ( serverSocket != null ) { try { serverSocket . close ( ) ; } catch ( IOException e ) { log . log ( Level . SEVERE , "Caught exception: " , e ) ; } } } } | Main loop of the SMTP server . |
22,893 | public synchronized void stop ( ) { stopped = true ; try { serverSocket . close ( ) ; semaphore . acquireUninterruptibly ( MAXIMUM_CONCURRENT_READERS ) ; } catch ( IOException e ) { log . log ( Level . SEVERE , "Caught exception: " , e ) ; } } | Stops the server . Server is shutdown after processing of the current request is complete . |
22,894 | private List < SmtpMessage > handleTransaction ( PrintWriter out , BufferedReader input ) throws IOException { SmtpState smtpState = SmtpState . CONNECT ; SmtpRequest smtpRequest = new SmtpRequest ( SmtpActionType . CONNECT , "" , smtpState ) ; SmtpResponse smtpResponse = smtpRequest . execute ( ) ; sendResponse ( out , smtpResponse ) ; smtpState = smtpResponse . getNextState ( ) ; List < SmtpMessage > msgList = new ArrayList < > ( ) ; SmtpMessage msg = new SmtpMessage ( ) ; while ( smtpState != SmtpState . CONNECT ) { String line = input . readLine ( ) ; if ( line == null ) { break ; } SmtpRequest request = SmtpRequest . createRequest ( line , smtpState ) ; SmtpResponse response = request . execute ( ) ; smtpState = response . getNextState ( ) ; sendResponse ( out , response ) ; String params = request . getParams ( ) ; msg . store ( response , params ) ; if ( smtpState == SmtpState . QUIT ) { msgList . add ( msg ) ; msg = new SmtpMessage ( ) ; } } return msgList ; } | Handle an SMTP transaction i . e . all activity between initial connect and QUIT command . |
22,895 | private static void sendResponse ( PrintWriter out , SmtpResponse smtpResponse ) { if ( smtpResponse . getCode ( ) > 0 ) { int code = smtpResponse . getCode ( ) ; String message = smtpResponse . getMessage ( ) ; out . print ( code + " " + message + "\r\n" ) ; out . flush ( ) ; } } | Send response to client . |
22,896 | public static SafeCloseSmtpServer start ( int port ) { SafeCloseSmtpServer server = new SafeCloseSmtpServer ( port ) ; Thread t = new Thread ( server , "Mock SMTP Server Thread" ) ; t . start ( ) ; try { server . startupBarrier . await ( ) ; } catch ( InterruptedException e ) { log . log ( Level . WARNING , "Interrupted" , e ) ; } return server ; } | Creates an instance of SimpleSmtpServer and starts it . |
22,897 | public static Integer findFree ( int lowIncluse , int highInclusive ) { int low = Math . max ( 1 , Math . min ( lowIncluse , highInclusive ) ) ; int high = Math . min ( 65535 , Math . max ( lowIncluse , highInclusive ) ) ; Integer result = null ; int split = RandomUtils . nextInt ( low , high + 1 ) ; for ( int port = split ; port <= high ; port ++ ) { if ( isFree ( port ) ) { result = port ; break ; } } if ( result == null ) { for ( int port = low ; port < split ; port ++ ) { if ( isFree ( port ) ) { result = port ; break ; } } } return result ; } | Returns a free port in the defined range returns null if none is available . |
22,898 | public static void addDefaultHeader ( String key , String value ) { if ( isNotBlank ( key ) && isNotBlank ( value ) ) { if ( defaultHeader == null ) { defaultHeader = new HashMap < String , String > ( ) ; } defaultHeader . put ( key , value ) ; } } | Added default headers will always be send can still be overriden using the builder . |
22,899 | public static HttpBuilder request ( String protocol , String host , Integer port , String path ) { return defaults ( createClient ( ) . request ( protocol , host , port , path ) ) ; } | Specifies the resource to be requested . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.