idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
22,800 | 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 | 240 | 8 |
22,801 | 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 | 93 | 47 |
22,802 | 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 | 53 | 12 |
22,803 | 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 | 211 | 8 |
22,804 | 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 == ' ' ) { // skip binary values 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 == ' ' ) { // segment-ende gefunden 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 | 319 | 17 |
22,805 | private static Gson createGson ( String className ) { GsonBuilder builder = new GsonBuilder ( ) ; // ISO8601 date format support 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 | 202 | 7 |
22,806 | 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 | 150 | 10 |
22,807 | 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 | 76 | 13 |
22,808 | private void suppressSeleniumJavaUtilLogging ( ) { if ( ! seleniumLoggingSuppressed . getAndSet ( true ) ) { try { // Log4j logging is annoyingly difficult to turn off, it usually requires a config file but we can also do it with an InputStream 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 | 240 | 13 |
22,809 | 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 | 114 | 12 |
22,810 | 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 ; } // Wenn sich die Versionsnummer nicht geaendert hat, muessen wir die // Huehner ja nicht verrueckt machen ;) if ( version == this . segVersion ) return ; log . info ( "changing segment version for task " + this . jobName + " explicit from " + this . segVersion + " to " + version ) ; // Der alte Name String oldName = this . name ; // Neuer Name und neue Versionsnummer this . segVersion = version ; this . name = this . jobName + version ; // Bereits gesetzte llParams fixen String [ ] names = this . llParams . keySet ( ) . toArray ( new String [ 0 ] ) ; for ( String s : names ) { if ( ! s . startsWith ( oldName ) ) continue ; // nicht betroffen // Alten Schluessel entfernen und neuen einfuegen String value = this . llParams . get ( s ) ; String newName = s . replaceFirst ( oldName , this . name ) ; this . llParams . remove ( s ) ; this . llParams . put ( newName , value ) ; } // Destination-Namen in den LowLevel-Parameter auf den neuen Namen umbiegen constraints . forEach ( ( frontendName , values ) -> { for ( String [ ] value : values ) { // value[0] ist das Target if ( ! value [ 0 ] . startsWith ( oldName ) ) continue ; // Hier ersetzen wir z.Bsp. "TAN2Step5.process" gegen "TAN2Step3.process" 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 . | 450 | 201 |
22,811 | public Konto getOrderAccount ( ) { // Checken, ob wir das Konto unter "My.[number/iban]" haben 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 ) ) { // OK, vielleicht unter "KTV.[number/iban]"? 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 ; // definitiv kein Konto vorhanden } 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 . | 338 | 28 |
22,812 | void put ( HashMap < String , String > props , Names name , String value ) { // BUGZILLA 1610 - "java.util.Properties" ist von Hashtable abgeleitet und unterstuetzt keine NULL-Werte if ( value == null ) return ; props . put ( name . getValue ( ) , value ) ; } | Speichert den Wert in den Properties . | 83 | 11 |
22,813 | public DocumentTranslationRequestDataChangeSet setTargetLanguagesMap ( Map < String , Map < String , Set < String > > > targetLanguagesMap ) { // TODO - check empty map? 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 . | 84 | 26 |
22,814 | 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 | 116 | 12 |
22,815 | @ Override public boolean propagateValue ( String destPath , String valueString , boolean tryToCreate , boolean allowOverwrite ) { boolean ret = false ; // wenn dieses de gemeint ist if ( destPath . equals ( getPath ( ) ) ) { if ( this . value != null ) { // es gibt schon einen Wert if ( ! allowOverwrite ) { // überschreiben ist nicht erlaubt throw new OverwriteException ( getPath ( ) , value . toString ( ) , valueString ) ; } } setValue ( valueString ) ; ret = true ; } return ret ; } | setzen des wertes des de | 140 | 8 |
22,816 | 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 ( ) ) ) ; } // log.("error string: "+res.toString(),log._ERR); // log.("current: "+getPath()+":"+type+"("+minsize+","+maxsize+")="+value,log._ERR); // log.("predelimiter mismatch (required:"+getPreDelim()+" found:"+temp.charAt(0)+")",log._ERR); 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 | 521 | 31 |
22,817 | static ObjectMapper getMapper ( ) { ObjectMapper mapper = new ObjectMapper ( ) ; // do not write null values mapper . setSerializationInclusion ( Include . NON_NULL ) ; mapper . setVisibility ( PropertyAccessor . ALL , JsonAutoDetect . Visibility . NONE ) ; mapper . setVisibility ( PropertyAccessor . FIELD , JsonAutoDetect . Visibility . ANY ) ; // set Date objects to output in readable customized format 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 | 179 | 6 |
22,818 | 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 . | 61 | 20 |
22,819 | 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 , ' ' ) ; 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 | 174 | 26 |
22,820 | static String [ ] getClasspathFileNames ( ) throws IOException { //for performance we most likely only want to do this once for each interpreter session, //classpath should not change dynamically 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 . | 151 | 54 |
22,821 | 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 . | 119 | 34 |
22,822 | 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 . | 284 | 38 |
22,823 | 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 | 150 | 15 |
22,824 | 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 | 87 | 11 |
22,825 | public void applyParams ( AbstractHBCIJob task , AbstractHBCIJob hktan , HBCITwoStepMechanism hbciTwoStepMechanism ) { String code = task . getHBCICode ( ) ; // Code des Geschaeftsvorfalls // Job-Parameter holen Job job = this . getData ( code ) ; // Den Geschaeftsvorfall kennen wir nicht. Dann brauchen wir // auch keine Challenge-Parameter setzen 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 ) ; // Parameter fuer die passende HHD-Version holen HhdVersion hhd = job . getVersion ( version . getChallengeVersion ( ) ) ; // Wir haben keine Parameter fuer diese HHD-Version if ( hhd == null ) { log . info ( "have no challenge data for " + code + " in " + version + ", will not apply challenge params" ) ; return ; } // Schritt 1: Challenge-Klasse uebernehmen String klass = hhd . getKlass ( ) ; log . debug ( "using challenge klass " + klass ) ; hktan . setParam ( "challengeklass" , klass ) ; // Schritt 2: Challenge-Parameter uebernehmen List < Param > params = hhd . getParams ( ) ; for ( int i = 0 ; i < params . size ( ) ; ++ i ) { int num = i + 1 ; // Die Job-Parameter beginnen bei 1 Param param = params . get ( i ) ; // Checken, ob der Parameter angewendet werden soll. if ( ! param . isComplied ( hbciTwoStepMechanism ) ) { log . debug ( "skipping challenge parameter " + num + " (" + param . path + "), condition " + param . conditionName + "=" + param . conditionValue + " not complied" ) ; continue ; } // Parameter uebernehmen. Aber nur wenn er auch einen Wert hat. // Seit HHD 1.4 duerfen Parameter mittendrin optional sein, sie // werden dann freigelassen 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 . | 649 | 23 |
22,826 | 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 | 62 | 20 |
22,827 | 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 | 145 | 16 |
22,828 | 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 | 55 | 8 |
22,829 | @ 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 | 97 | 9 |
22,830 | 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 | 256 | 15 |
22,831 | 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 | 583 | 14 |
22,832 | 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 . | 323 | 24 |
22,833 | 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 | 88 | 36 |
22,834 | 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 . | 47 | 17 |
22,835 | public TranslationRequestDataChangeSet setTargetLanguagesByBundle ( Map < String , Set < String > > targetLanguagesByBundle ) { // TODO - check empty map? 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 . | 88 | 25 |
22,836 | private void addFeaturesRecursively ( File directory , List < File > targetList , FileFilter fileFilter ) { File [ ] files = directory . listFiles ( ) ; //sort the files here, since otherwise we get differences in execution order between 'nix, case sensitive //and win, case insensitive, toys 'r us 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 . | 179 | 16 |
22,837 | 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 ( ) ; //no assertion errors? condition passes, we can continue success = true ; break ; } catch ( Throwable r ) { if ( r instanceof FailImmediatelyException ) { throw ( FailImmediatelyException ) r ; } else if ( r . getCause ( ) instanceof FailImmediatelyException ) { throw ( FailImmediatelyException ) r . getCause ( ) ; } //ignore failures up until the last check } sleepUntil ( startTime + ( pollPeriodMillis * iteration ) ) ; if ( System . currentTimeMillis ( ) >= expireTime ) { break ; } } if ( ! success ) { try { validate ( ) ; //this time allow any assertion errors to propagate } catch ( Throwable e ) { propagateAsError ( e ) ; } } return iteration ; } | Wait for the assertions to pass for the specified time limit | 246 | 11 |
22,838 | 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 | 134 | 13 |
22,839 | 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 | 73 | 12 |
22,840 | 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 . | 42 | 10 |
22,841 | 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 . | 331 | 8 |
22,842 | 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 . | 49 | 7 |
22,843 | public static String generateRegId ( final String domainCreationDate , final String reverseDomainName ) { return generateRegId ( domainCreationDate , reverseDomainName , null ) ; } | Generate RegId . | 39 | 5 |
22,844 | 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 . | 180 | 8 |
22,845 | public void setGenerator ( final IdGenerator generator ) { if ( generator != null ) { this . idGenerator = generator ; swidTag . setId ( idGenerator . nextId ( ) ) ; } } | Set element identifier generator . | 47 | 5 |
22,846 | 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 . | 251 | 8 |
22,847 | 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 . | 58 | 8 |
22,848 | public void write ( final SoftwareIdentificationTagComplexType swidTag , final File file ) { JAXBUtils . writeObject ( objectFactory . createSoftwareIdentificationTag ( swidTag ) , file , getComment ( ) ) ; } | Write the object into a file . | 53 | 7 |
22,849 | public void write ( final SoftwareIdentificationTagComplexType swidTag , final java . io . Writer writer ) { JAXBUtils . writeObject ( objectFactory . createSoftwareIdentificationTag ( swidTag ) , writer , getComment ( ) ) ; } | Write the object into a Writer . | 57 | 7 |
22,850 | 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 ( ) ) ; } // custom header, for UPS conn . setRequestProperty ( "aerogear-sender" , "AeroGear Java Sender" ) ; ( ( HttpURLConnection ) conn ) . setRequestMethod ( "POST" ) ; OutputStream out = null ; try { out = conn . getOutputStream ( ) ; out . write ( bytes ) ; } finally { // in case something blows up, while writing // the payload, we wanna close the stream: if ( out != null ) { out . close ( ) ; } } return conn ; } | Returns URLConnection that posts the given JSON to the given UnifiedPush Server URL . | 600 | 16 |
22,851 | 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 ) ) ; // POST the payload to the UnifiedPush Server 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 we got a redirect, let's extract the 'Location' header from the response // and submit the payload again if ( isRedirect ( statusCode ) ) { String redirectURL = httpURLConnection . getHeaderField ( "Location" ) ; logger . log ( Level . INFO , String . format ( "Performing redirect to '%s'" , redirectURL ) ) ; // execute the 'redirect' submitPayload ( redirectURL , pushConfiguration . getConnectionSettings ( ) , jsonPayloadObject , pushApplicationId , masterSecret , callback , redirectUrls ) ; } else if ( statusCode >= 400 ) { // treating any 400/500 error codes an an exception to a sending attempt: 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 { // tear down if ( httpURLConnection != null ) { httpURLConnection . disconnect ( ) ; } } } | The actual method that does the real send and connection handling | 534 | 11 |
22,852 | 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 . | 57 | 10 |
22,853 | 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 . | 398 | 47 |
22,854 | 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 | 427 | 9 |
22,855 | @ Override public void run ( ) { stopped = false ; try { try { serverSocket = new ServerSocket ( port ) ; serverSocket . setSoTimeout ( TIMEOUT ) ; // Block for maximum of 1.5 seconds } finally { // Notify when server socket has been created startupBarrier . countDown ( ) ; } // Server: loop until stopped while ( ! isStopped ( ) ) { // get a semaphore so we can ensure below that no thread is still doing stuff when we want to close the server if ( ! semaphore . tryAcquire ( ) ) { throw new IllegalStateException ( "Could not get semaphore, number of possible threads is too low." ) ; } try { // Start server socket and listen for client connections final Socket socket ; try { socket = serverSocket . accept ( ) ; } catch ( @ SuppressWarnings ( "unused" ) Exception e ) { continue ; // Non-blocking socket timeout occurred: try accept() again } // Get the input and output streams BufferedReader input = new BufferedReader ( new InputStreamReader ( socket . getInputStream ( ) , "UTF-8" ) ) ; // NOSONAR - test class works only locally anyway PrintWriter out = new PrintWriter ( socket . getOutputStream ( ) ) ; // NOSONAR - test class works only locally anyway synchronized ( this ) { /* * We synchronize over the handle method and the list update because the client call completes inside * the handle method and we have to prevent the client from reading the list until we've updated it. * For higher concurrency, we could just change handle to return void and update the list inside the * method * to limit the duration that we hold the lock. */ List < SmtpMessage > messages = handleTransaction ( out , input ) ; receivedMail . addAll ( messages ) ; } socket . close ( ) ; } finally { semaphore . release ( ) ; } } } catch ( Exception e ) { // TODO: Should throw an appropriate exception here 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 . | 501 | 8 |
22,856 | public synchronized void stop ( ) { // Mark us closed stopped = true ; try { // Kick the server accept loop serverSocket . close ( ) ; // acquire all semaphores so that we wait for all connections to finish before we report back as closed 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 . | 103 | 17 |
22,857 | private List < SmtpMessage > handleTransaction ( PrintWriter out , BufferedReader input ) throws IOException { // Initialize the state machine SmtpState smtpState = SmtpState . CONNECT ; SmtpRequest smtpRequest = new SmtpRequest ( SmtpActionType . CONNECT , "" , smtpState ) ; // Execute the connection request SmtpResponse smtpResponse = smtpRequest . execute ( ) ; // Send initial response 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 ; } // Create request from client input and current state SmtpRequest request = SmtpRequest . createRequest ( line , smtpState ) ; // Execute request and create response object SmtpResponse response = request . execute ( ) ; // Move to next internal state smtpState = response . getNextState ( ) ; // Send response to client sendResponse ( out , response ) ; // Store input in message String params = request . getParams ( ) ; msg . store ( response , params ) ; // If message reception is complete save it 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 . | 331 | 19 |
22,858 | 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 . | 82 | 5 |
22,859 | public static SafeCloseSmtpServer start ( int port ) { SafeCloseSmtpServer server = new SafeCloseSmtpServer ( port ) ; Thread t = new Thread ( server , "Mock SMTP Server Thread" ) ; t . start ( ) ; // Block until the server socket is created try { server . startupBarrier . await ( ) ; } catch ( InterruptedException e ) { log . log ( Level . WARNING , "Interrupted" , e ) ; } return server ; } | Creates an instance of SimpleSmtpServer and starts it . | 104 | 13 |
22,860 | 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 . | 165 | 15 |
22,861 | 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 . | 68 | 17 |
22,862 | 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 . | 41 | 8 |
22,863 | private static HttpBuilder defaults ( HttpBuilder builder ) { if ( defaultTimeout != null ) { builder . timeout ( defaultTimeout ) ; } if ( defaultTimeoutConnection != null ) { builder . timeoutConnection ( defaultTimeoutConnection ) ; } if ( defaultTimeoutRead != null ) { builder . timeoutRead ( defaultTimeoutRead ) ; } if ( defaultHeader != null ) { builder . headers ( defaultHeader ) ; } return builder ; } | Setting the static defaults before returning the builder | 91 | 8 |
22,864 | public static void printBox ( String title , String message ) { printBox ( title , Splitter . on ( LINEBREAK ) . splitToList ( message ) ) ; } | Prints a box with the given title and message to the logger the title can be omitted . | 37 | 19 |
22,865 | public static void printBox ( String title , List < String > messageLines ) { Say . info ( "{message}" , generateBox ( title , messageLines ) ) ; } | Prints a box with the given title and message lines to the logger the title can be omitted . | 38 | 20 |
22,866 | public static void setUtc ( Date time ) { setClock ( Clock . fixed ( time . toInstant ( ) , ZoneId . of ( "UTC" ) ) ) ; } | Creates a fixed Clock . | 38 | 6 |
22,867 | public synchronized static void addShutdownHook ( Runnable task ) { if ( task != null ) { Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ( ) -> { try { task . run ( ) ; } catch ( RuntimeException rex ) { Say . warn ( "Exception while processing shutdown-hook" , rex ) ; } } ) ) ; } } | Null - safe shortcut to Runtime method catching RuntimeExceptions . | 84 | 12 |
22,868 | public void finish ( ) { if ( startMeasure == null ) { Say . info ( "No invokations are measured" ) ; } else { long total = System . currentTimeMillis ( ) - startMeasure ; double average = 1d * total / counter ; logFinished ( total , average ) ; } } | This method can be called to print the total amount of time taken until that point in time . | 67 | 19 |
22,869 | public void run ( ExceptionalRunnable runnable ) throws Exception { initStartTotal ( ) ; long startInvokation = System . currentTimeMillis ( ) ; runnable . run ( ) ; invoked ( System . currentTimeMillis ( ) - startInvokation ) ; } | Measure the invokation time of the given ExceptionalRunnable . | 63 | 15 |
22,870 | public < V > V call ( Callable < V > callable ) throws Exception { initStartTotal ( ) ; long startInvokation = System . currentTimeMillis ( ) ; V result = callable . call ( ) ; invoked ( System . currentTimeMillis ( ) - startInvokation ) ; return result ; } | Measure the invokation time of the given Callable . | 70 | 12 |
22,871 | public static void sleep ( long millis ) { try { Thread . sleep ( millis ) ; } catch ( InterruptedException ex ) { Thread . currentThread ( ) . interrupt ( ) ; } } | Sleep the given milliseconds swallowing the exception | 42 | 7 |
22,872 | public < T > T fallback ( T val , T fallback ) { return val != null ? val : fallback ; } | Returns the given value or the fallback if the value is null . | 27 | 14 |
22,873 | public Iterator < String > getMessages ( ) { Iterator < SmtpMessage > it = server . getReceivedEmail ( ) ; List < String > msgs = new ArrayList <> ( ) ; while ( it . hasNext ( ) ) { SmtpMessage msg = it . next ( ) ; msgs . add ( msg . toString ( ) ) ; } return msgs . iterator ( ) ; } | Returns an iterator of messages that were received by this server . | 89 | 12 |
22,874 | public static void registerMBean ( String packageName , String type , String name , Object mbean ) { try { String pkg = defaultString ( packageName , mbean . getClass ( ) . getPackage ( ) . getName ( ) ) ; MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; ObjectName on = new ObjectName ( pkg + ":type=" + type + ",name=" + name ) ; if ( server . isRegistered ( on ) ) { Say . debug ( "MBean with type {type} and name {name} for {package} has already been defined, ignoring" , type , name , pkg ) ; } else { server . registerMBean ( mbean , on ) ; } } catch ( Exception ex ) { Say . warn ( "MBean could not be registered" , ex ) ; } } | Will register the given mbean using the given packageName type and name . If no packageName has been given the package of the mbean will be used . | 189 | 32 |
22,875 | public static Long dehumanize ( String time ) { Long result = getHumantimeCache ( ) . get ( time ) ; if ( result == null ) { if ( isNotBlank ( time ) ) { String input = time . trim ( ) ; if ( NumberUtils . isDigits ( input ) ) { result = NumberUtils . toLong ( input ) ; } else { Matcher matcher = PATTERN_HUMAN_TIME . matcher ( input ) ; if ( matcher . matches ( ) ) { long sum = 0L ; sum += dehumanizeUnit ( matcher . group ( 1 ) , MS_WEEK ) ; sum += dehumanizeUnit ( matcher . group ( 2 ) , MS_DAY ) ; sum += dehumanizeUnit ( matcher . group ( 3 ) , MS_HOUR ) ; sum += dehumanizeUnit ( matcher . group ( 4 ) , MS_MINUTE ) ; sum += dehumanizeUnit ( matcher . group ( 5 ) , MS_SECOND ) ; sum += dehumanizeUnit ( matcher . group ( 6 ) , MS_MILLISECOND ) ; result = sum ; } } getHumantimeCache ( ) . put ( time , result ) ; } } return result ; } | Converts a human readable duration in the format Xd Xh Xm Xs Xms to miliseconds . | 267 | 24 |
22,876 | @ Override public final V computeIfPresent ( K key , BiFunction < ? super K , ? super V , ? extends V > remappingFunction ) { if ( remappingFunction == null ) throw new NullPointerException ( ) ; long hash ; return segment ( segmentIndex ( hash = keyHashCode ( key ) ) ) . computeIfPresent ( this , hash , key , remappingFunction ) ; } | If the value for the specified key is present and non - null attempts to compute a new mapping given the key and its current mapped value . | 86 | 28 |
22,877 | private long nextSegmentIndex ( long segmentIndex , Segment segment ) { long segmentsTier = this . segmentsTier ; segmentIndex <<= - segmentsTier ; segmentIndex = Long . reverse ( segmentIndex ) ; int numberOfArrayIndexesWithThisSegment = 1 << ( segmentsTier - segment . tier ) ; segmentIndex += numberOfArrayIndexesWithThisSegment ; if ( segmentIndex > segmentsMask ) return - 1 ; segmentIndex = Long . reverse ( segmentIndex ) ; segmentIndex >>>= - segmentsTier ; return segmentIndex ; } | Extension rules make order of iteration of segments a little weird avoiding visiting the same segment twice | 115 | 18 |
22,878 | @ Override public final void replaceAll ( BiFunction < ? super K , ? super V , ? extends V > function ) { Objects . requireNonNull ( function ) ; int mc = this . modCount ; Segment < K , V > segment ; for ( long segmentIndex = 0 ; segmentIndex >= 0 ; segmentIndex = nextSegmentIndex ( segmentIndex , segment ) ) { ( segment = segment ( segmentIndex ) ) . replaceAll ( function ) ; } if ( mc != modCount ) throw new ConcurrentModificationException ( ) ; } | Replaces each entry s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception . Exceptions thrown by the function are relayed to the caller . | 116 | 42 |
22,879 | public final boolean removeIf ( BiPredicate < ? super K , ? super V > filter ) { Objects . requireNonNull ( filter ) ; if ( isEmpty ( ) ) return false ; Segment < K , V > segment ; int mc = this . modCount ; int initialModCount = mc ; for ( long segmentIndex = 0 ; segmentIndex >= 0 ; segmentIndex = nextSegmentIndex ( segmentIndex , segment ) ) { mc = ( segment = segment ( segmentIndex ) ) . removeIf ( this , filter , mc ) ; } if ( mc != modCount ) throw new ConcurrentModificationException ( ) ; return mc != initialModCount ; } | Removes all of the entries of this map that satisfy the given predicate . Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller . | 140 | 32 |
22,880 | private String getJustifiedText ( String text ) { String [ ] words = text . split ( NORMAL_SPACE ) ; for ( String word : words ) { boolean containsNewLine = ( word . contains ( "\n" ) || word . contains ( "\r" ) ) ; if ( fitsInSentence ( word , currentSentence , true ) ) { addWord ( word , containsNewLine ) ; } else { sentences . add ( fillSentenceWithSpaces ( currentSentence ) ) ; currentSentence . clear ( ) ; addWord ( word , containsNewLine ) ; } } //Making sure we add the last sentence if needed. if ( currentSentence . size ( ) > 0 ) { sentences . add ( getSentenceFromList ( currentSentence , true ) ) ; } //Returns the justified text. return getSentenceFromList ( sentences , false ) ; } | Retrieves a String with appropriate spaces to justify the text in the TextView . | 189 | 17 |
22,881 | private void addWord ( String word , boolean containsNewLine ) { currentSentence . add ( word ) ; if ( containsNewLine ) { sentences . add ( getSentenceFromListCheckingNewLines ( currentSentence ) ) ; currentSentence . clear ( ) ; } } | Adds a word into sentence and starts a new one if new line is part of the string . | 61 | 19 |
22,882 | private String getSentenceFromList ( List < String > strings , boolean addSpaces ) { StringBuilder stringBuilder = new StringBuilder ( ) ; for ( String string : strings ) { stringBuilder . append ( string ) ; if ( addSpaces ) { stringBuilder . append ( NORMAL_SPACE ) ; } } return stringBuilder . toString ( ) ; } | Creates a string using the words in the list and adds spaces between words if required . | 78 | 18 |
22,883 | private String getSentenceFromListCheckingNewLines ( List < String > strings ) { StringBuilder stringBuilder = new StringBuilder ( ) ; for ( String string : strings ) { stringBuilder . append ( string ) ; //We don't want to add a space next to the word if this one contains a new line character if ( ! string . contains ( "\n" ) && ! string . contains ( "\r" ) ) { stringBuilder . append ( NORMAL_SPACE ) ; } } return stringBuilder . toString ( ) ; } | Creates a string using the words in the list and adds spaces between words taking new lines in consideration . | 115 | 21 |
22,884 | private String fillSentenceWithSpaces ( List < String > sentence ) { sentenceWithSpaces . clear ( ) ; //We don't need to do this process if the sentence received is a single word. if ( sentence . size ( ) > 1 ) { //We fill with normal spaces first, we can do this with confidence because "fitsInSentence" //already takes these spaces into account. for ( String word : sentence ) { sentenceWithSpaces . add ( word ) ; sentenceWithSpaces . add ( NORMAL_SPACE ) ; } //Filling sentence with thin spaces. while ( fitsInSentence ( HAIR_SPACE , sentenceWithSpaces , false ) ) { //We remove 2 from the sentence size because we need to make sure we are not adding //spaces to the end of the line. sentenceWithSpaces . add ( getRandomNumber ( sentenceWithSpaces . size ( ) - 2 ) , HAIR_SPACE ) ; } } return getSentenceFromList ( sentenceWithSpaces , false ) ; } | Fills sentence with appropriate amount of spaces . | 223 | 9 |
22,885 | private boolean fitsInSentence ( String word , List < String > sentence , boolean addSpaces ) { String stringSentence = getSentenceFromList ( sentence , addSpaces ) ; stringSentence += word ; float sentenceWidth = getPaint ( ) . measureText ( stringSentence ) ; return sentenceWidth < viewWidth ; } | Verifies if word to be added will fit into the sentence | 72 | 12 |
22,886 | @ Nonnull final String writeManifest ( @ Nonnull final TreeLogger logger , @ Nonnull final Set < String > staticResources , @ Nonnull final Map < String , String > fallbackResources , @ Nonnull final Set < String > cacheResources ) throws UnableToCompleteException { final ManifestDescriptor descriptor = new ManifestDescriptor ( ) ; final List < String > cachedResources = Stream . concat ( staticResources . stream ( ) , cacheResources . stream ( ) ) . sorted ( ) . distinct ( ) . collect ( Collectors . toList ( ) ) ; descriptor . getCachedResources ( ) . addAll ( cachedResources ) ; descriptor . getFallbackResources ( ) . putAll ( fallbackResources ) ; descriptor . getNetworkResources ( ) . add ( "*" ) ; try { return descriptor . toString ( ) ; } catch ( final Exception e ) { logger . log ( Type . ERROR , "Error generating manifest: " + e , e ) ; throw new UnableToCompleteException ( ) ; } } | Write a manifest file for the given set of artifacts and return it as a string | 219 | 16 |
22,887 | @ Nullable final Permutation calculatePermutation ( @ Nonnull final TreeLogger logger , @ Nonnull final LinkerContext context , @ Nonnull final ArtifactSet artifacts ) throws UnableToCompleteException { Permutation permutation = null ; for ( final SelectionInformation result : artifacts . find ( SelectionInformation . class ) ) { final String strongName = result . getStrongName ( ) ; if ( null != permutation && ! permutation . getPermutationName ( ) . equals ( strongName ) ) { throw new UnableToCompleteException ( ) ; } if ( null == permutation ) { permutation = new Permutation ( strongName ) ; final Set < String > artifactsForCompilation = getArtifactsForCompilation ( context , artifacts ) ; permutation . getPermutationFiles ( ) . addAll ( artifactsForCompilation ) ; } final List < BindingProperty > list = new ArrayList <> ( ) ; for ( final SelectionProperty property : context . getProperties ( ) ) { if ( ! property . isDerived ( ) ) { final String name = property . getName ( ) ; final String value = result . getPropMap ( ) . get ( name ) ; if ( null != value ) { list . add ( new BindingProperty ( name , value ) ) ; } } } final SelectionDescriptor selection = new SelectionDescriptor ( strongName , list ) ; final List < SelectionDescriptor > selectors = permutation . getSelectors ( ) ; if ( ! selectors . contains ( selection ) ) { selectors . add ( selection ) ; } } if ( null != permutation ) { logger . log ( Type . DEBUG , "Calculated Permutation: " + permutation . getPermutationName ( ) + " Selectors: " + permutation . getSelectors ( ) ) ; } return permutation ; } | Return the permutation for a single link step . | 397 | 10 |
22,888 | protected boolean handleUnmatchedRequest ( final HttpServletRequest request , final HttpServletResponse response , final String moduleName , final String baseUrl , final List < BindingProperty > computedBindings ) throws ServletException , IOException { return false ; } | Sub - classes can override this method to perform handle the inability to find a matching permutation . In which case the method should return true if the response has been handled . | 55 | 34 |
22,889 | protected final String loadAndMergeManifests ( final String baseUrl , final String moduleName , final String ... permutationNames ) throws ServletException { final String cacheKey = toCacheKey ( baseUrl , moduleName , permutationNames ) ; if ( isCacheEnabled ( ) ) { final String manifest = _cache . get ( cacheKey ) ; if ( null != manifest ) { return manifest ; } } final ManifestDescriptor descriptor = new ManifestDescriptor ( ) ; for ( final String permutationName : permutationNames ) { final String manifest = loadManifest ( baseUrl , moduleName , permutationName ) ; final ManifestDescriptor other = ManifestDescriptor . parse ( manifest ) ; descriptor . merge ( other ) ; } Collections . sort ( descriptor . getCachedResources ( ) ) ; Collections . sort ( descriptor . getNetworkResources ( ) ) ; final String manifest = descriptor . toString ( ) ; if ( isCacheEnabled ( ) ) { _cache . put ( cacheKey , manifest ) ; } return manifest ; } | Utility method that loads and merges the cache files for multiple permutations . This is useful when it is not possible to determine the exact permutation required for a client on the server . This defers the decision to the client but may result in extra files being downloaded . | 222 | 55 |
22,890 | protected final void reduceToMatchingDescriptors ( @ Nonnull final List < BindingProperty > bindings , @ Nonnull final List < SelectionDescriptor > descriptors ) { final Iterator < BindingProperty > iterator = bindings . iterator ( ) ; while ( iterator . hasNext ( ) ) { final BindingProperty property = iterator . next ( ) ; // Do any selectors match? boolean matched = false ; for ( final SelectionDescriptor selection : descriptors ) { final BindingProperty candidate = findMatchingBindingProperty ( selection . getBindingProperties ( ) , property ) ; if ( null != candidate ) { matched = true ; break ; } } if ( matched ) { // if so we can remove binding property from candidates list iterator . remove ( ) ; // and now remove any selections that don't match final Iterator < SelectionDescriptor > selections = descriptors . iterator ( ) ; while ( selections . hasNext ( ) ) { final SelectionDescriptor selection = selections . next ( ) ; if ( null == findSatisfiesBindingProperty ( selection . getBindingProperties ( ) , property ) ) { selections . remove ( ) ; } } } } } | This method will restrict the list of descriptors so that it only contains selections valid for specified bindings . Bindings will be removed from the list as they are matched . Unmatched bindings will remain in the bindings list after the method completes . | 248 | 47 |
22,891 | private BindingProperty findMatchingBindingProperty ( final List < BindingProperty > bindings , final BindingProperty requirement ) { for ( final BindingProperty candidate : bindings ) { if ( requirement . getName ( ) . equals ( candidate . getName ( ) ) ) { return candidate ; } } return null ; } | Return the binding property in the bindings list that matches specified requirement . | 63 | 13 |
22,892 | private BindingProperty findSatisfiesBindingProperty ( final List < BindingProperty > bindings , final BindingProperty requirement ) { final BindingProperty property = findMatchingBindingProperty ( bindings , requirement ) ; if ( null != property && property . matches ( requirement . getValue ( ) ) ) { return property ; } return null ; } | Return the binding property in the bindings list that satisfies specified requirement . Satisfies means that the property name matches and the value matches . | 69 | 26 |
22,893 | protected final String [ ] selectPermutations ( @ Nonnull final String baseUrl , @ Nonnull final String moduleName , @ Nonnull final List < BindingProperty > computedBindings ) throws ServletException { try { final List < SelectionDescriptor > descriptors = new ArrayList <> ( ) ; descriptors . addAll ( getPermutationDescriptors ( baseUrl , moduleName ) ) ; final List < BindingProperty > bindings = new ArrayList <> ( ) ; bindings . addAll ( computedBindings ) ; reduceToMatchingDescriptors ( bindings , descriptors ) ; if ( 0 == bindings . size ( ) ) { if ( 1 == descriptors . size ( ) ) { return new String [ ] { descriptors . get ( 0 ) . getPermutationName ( ) } ; } else { final ArrayList < String > permutations = new ArrayList <> ( ) ; for ( final SelectionDescriptor descriptor : descriptors ) { if ( descriptor . getBindingProperties ( ) . size ( ) == computedBindings . size ( ) ) { permutations . add ( descriptor . getPermutationName ( ) ) ; } else { for ( final BindingProperty property : descriptor . getBindingProperties ( ) ) { // This is one of the bindings that we could not reduce on if ( null == findMatchingBindingProperty ( computedBindings , property ) ) { if ( canMergeManifestForSelectionProperty ( property . getName ( ) ) ) { permutations . add ( descriptor . getPermutationName ( ) ) ; } } } } } if ( 0 == permutations . size ( ) ) { return null ; } else { return permutations . toArray ( new String [ permutations . size ( ) ] ) ; } } } return null ; } catch ( final Exception e ) { throw new ServletException ( "can not read permutation information" , e ) ; } } | Return an array of permutation names that are selected based on supplied properties . | 413 | 15 |
22,894 | public static < E > Collector < E , ? , Optional < E > > getOnly ( ) { return Collector . of ( AtomicReference < E > :: new , ( ref , e ) -> { if ( ! ref . compareAndSet ( null , e ) ) { throw new IllegalArgumentException ( "Multiple values" ) ; } } , ( ref1 , ref2 ) -> { if ( ref1 . get ( ) == null ) { return ref2 ; } else if ( ref2 . get ( ) != null ) { throw new IllegalArgumentException ( "Multiple values" ) ; } else { return ref1 ; } } , ref -> Optional . ofNullable ( ref . get ( ) ) , Collector . Characteristics . UNORDERED ) ; } | Can be replaced with MoreCollectors . onlyElement as soon as we can upgrade to the newest Guava version . | 161 | 23 |
22,895 | public static Object getSingleResultOrNull ( Query query ) { List results = query . getResultList ( ) ; if ( results . isEmpty ( ) ) { return null ; } else if ( results . size ( ) == 1 ) { return results . get ( 0 ) ; } throw new NonUniqueResultException ( ) ; } | Executes the query and ensures that either a single result is returned or null . | 69 | 16 |
22,896 | public char [ ] hash ( char [ ] password , byte [ ] salt ) { checkNotNull ( password ) ; checkArgument ( password . length != 0 ) ; checkNotNull ( salt ) ; checkArgument ( salt . length != 0 ) ; try { SecretKeyFactory f = SecretKeyFactory . getInstance ( "PBKDF2WithHmacSHA1" ) ; SecretKey key = f . generateSecret ( new PBEKeySpec ( password , salt , ITERATIONS , DESIRED_KEY_LENGTH ) ) ; return Base64 . encodeBase64String ( key . getEncoded ( ) ) . toCharArray ( ) ; } catch ( NoSuchAlgorithmException | InvalidKeySpecException e ) { throw new IllegalStateException ( "Could not hash the password of the user." , e ) ; } } | Hashes the password using pbkdf2 and the given salt . | 175 | 15 |
22,897 | public boolean check ( char [ ] plain , char [ ] database , byte [ ] salt ) { checkNotNull ( plain ) ; checkArgument ( plain . length != 0 , "Plain must not be empty." ) ; checkNotNull ( database ) ; checkArgument ( database . length != 0 , "Database must not be empty." ) ; checkNotNull ( salt ) ; checkArgument ( salt . length != 0 , "Salt must not be empty." ) ; char [ ] hashedPlain = this . hash ( plain , salt ) ; return Arrays . equals ( hashedPlain , database ) ; } | Checks if the given plain password matches the given password hash | 131 | 12 |
22,898 | public static double mean ( double [ ] a ) { if ( a . length == 0 ) return Double . NaN ; double sum = sum ( a ) ; return sum / a . length ; } | Returns the average value in the specified array . | 41 | 9 |
22,899 | public static double stdDev ( double [ ] a ) { if ( a == null || a . length == 0 ) return - 1 ; return Math . sqrt ( varp ( a ) ) ; } | Returns the population standard deviation in the specified array . | 42 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.