idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
19,200 | public void putString ( String key , String value ) { sharedPreferences . edit ( ) . putString ( key , value ) . commit ( ) ; } | put the string value to shared preference |
19,201 | public void putFloat ( String key , float value ) { sharedPreferences . edit ( ) . putFloat ( key , value ) . commit ( ) ; } | put the float value to shared preference |
19,202 | public final EventData convert ( final CommonEvent commonEvent ) { final String dataType = commonEvent . getDataType ( ) . asBaseType ( ) ; final SerializedDataType serUserDataType = new SerializedDataType ( dataType ) ; final Serializer userDataSerializer = serRegistry . getSerializer ( serUserDataType ) ; final byte [ ] serUserData = userDataSerializer . marshal ( commonEvent . getData ( ) , serUserDataType ) ; final byte [ ] serData ; if ( userDataSerializer . getMimeType ( ) . matchEncoding ( targetContentType ) ) { serData = serUserData ; } else { final Base64Data base64data = new Base64Data ( serUserData ) ; final Serializer base64Serializer = serRegistry . getSerializer ( Base64Data . SER_TYPE ) ; serData = base64Serializer . marshal ( base64data , Base64Data . SER_TYPE ) ; } final EscMeta escMeta = EscSpiUtils . createEscMeta ( serRegistry , targetContentType , commonEvent ) ; final SerializedDataType escMetaType = new SerializedDataType ( EscMeta . TYPE . asBaseType ( ) ) ; final Serializer escMetaSerializer = getSerializer ( escMetaType ) ; final byte [ ] escSerMeta = escMetaSerializer . marshal ( escMeta , escMetaType ) ; final EventData . Builder builder = EventData . newBuilder ( ) . eventId ( commonEvent . getId ( ) . asBaseType ( ) ) . type ( dataType ) ; if ( targetContentType . isJson ( ) ) { builder . jsonData ( serData ) ; builder . jsonMetadata ( escSerMeta ) ; } else { builder . data ( serData ) ; builder . metadata ( escSerMeta ) ; } return builder . build ( ) ; } | Converts a common event into event data . |
19,203 | public FunctionCall bindParameter ( Number number ) { int pos = bindings . size ( ) ; String parameterName = function . getNthParameter ( pos ) ; bindings . put ( parameterName , number ) ; return this ; } | Bind a parameter number to a function . |
19,204 | public Number getParameter ( String name ) { Number number = bindings . get ( name ) ; if ( number == null ) { throw new FuzzerException ( function . getName ( ) + ": undefined parameter '" + name + "'" ) ; } return number ; } | Get a parameter assignment . |
19,205 | @ Initialize ( distributed = false ) public void truncateIfNecesary ( ) { if ( truncateTable ) { final UpdateableDatastoreConnection con = datastore . openConnection ( ) ; try { final SchemaNavigator schemaNavigator = con . getSchemaNavigator ( ) ; final Table table = schemaNavigator . convertToTable ( schemaName , tableName ) ; final UpdateableDataContext dc = con . getUpdateableDataContext ( ) ; dc . executeUpdate ( new UpdateScript ( ) { public void run ( UpdateCallback callback ) { final RowDeletionBuilder delete = callback . deleteFrom ( table ) ; if ( logger . isInfoEnabled ( ) ) { logger . info ( "Executing truncating DELETE operation: {}" , delete . toSql ( ) ) ; } delete . execute ( ) ; } } ) ; } finally { con . close ( ) ; } } } | Truncates the database table if necesary . This is NOT a distributable initializer since it can only happen once . |
19,206 | public RestClientResponse execute ( AsyncHttpClient . BoundRequestBuilder requestBuilder ) throws RestClientException { Response response ; try { ListenableFuture < Response > futureResponse = requestBuilder . execute ( ) ; response = futureResponse . get ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Got response body: {}" , response . getResponseBody ( ) ) ; } } catch ( InterruptedException e ) { throw new RestClientException ( "Interrupted while waiting for server response" , e ) ; } catch ( ExecutionException e ) { throw new RestClientException ( "Tried to retrieve result from aborted action." , e ) ; } catch ( IOException e ) { throw new RestClientException ( "Encountered IOException while executing REST request." , e ) ; } return new NingRestClientResponse ( response ) ; } | Execute and throw RestClientException exceptions if the request could not be executed . |
19,207 | public void addParameter ( String ... paras ) { for ( String parameter : paras ) { for ( String knownDef : parameters ) { if ( parameter . equals ( knownDef ) ) { throw new FuzzerException ( name + ": parameter '" + parameter + "' already defined" ) ; } } parameters . add ( parameter ) ; } } | Add a function configuration parameter . |
19,208 | protected void appendToString ( StringBuilder sb , ValueCountingAnalyzerResult groupResult , int maxEntries ) { if ( maxEntries != 0 ) { Collection < ValueFrequency > valueCounts = groupResult . getValueCounts ( ) ; for ( ValueFrequency valueCount : valueCounts ) { sb . append ( "\n - " ) ; sb . append ( valueCount . getName ( ) ) ; sb . append ( ": " ) ; sb . append ( valueCount . getCount ( ) ) ; maxEntries -- ; if ( maxEntries == 0 ) { sb . append ( "\n ..." ) ; break ; } } } } | Appends a string representation with a maximum amount of entries |
19,209 | public static CliArguments parse ( String [ ] args ) { CliArguments arguments = new CliArguments ( ) ; if ( args != null ) { CmdLineParser parser = new CmdLineParser ( arguments ) ; try { parser . parseArgument ( args ) ; } catch ( CmdLineException e ) { } arguments . usageMode = false ; for ( String arg : args ) { for ( int i = 0 ; i < USAGE_TOKENS . length ; i ++ ) { String usageToken = USAGE_TOKENS [ i ] ; if ( usageToken . equalsIgnoreCase ( arg ) ) { arguments . usageMode = true ; break ; } } } } return arguments ; } | Parses the CLI arguments and creates a CliArguments instance |
19,210 | public static void printUsage ( PrintWriter out ) { CliArguments arguments = new CliArguments ( ) ; CmdLineParser parser = new CmdLineParser ( arguments ) ; parser . setUsageWidth ( 120 ) ; parser . printUsage ( out , null ) ; } | Prints the usage information for the CLI |
19,211 | public boolean isSet ( ) { if ( isUsageMode ( ) ) { return true ; } if ( getJobFile ( ) != null ) { return true ; } if ( getListType ( ) != null ) { return true ; } return false ; } | Gets whether the arguments have been sufficiently set to execute a CLI task . |
19,212 | private void writeObject ( ObjectOutputStream out ) throws IOException { logger . info ( "Serialization requested, awaiting reference to load." ) ; get ( ) ; out . defaultWriteObject ( ) ; logger . info ( "Serialization finished!" ) ; } | Method invoked when serialization takes place . Makes sure that we await the loading of the result reference before writing any data . |
19,213 | public static EscEvents create ( final JsonArray jsonArray ) { final List < EscEvent > events = new ArrayList < > ( ) ; for ( final JsonValue jsonValue : jsonArray ) { if ( jsonValue . getValueType ( ) != JsonValue . ValueType . OBJECT ) { throw new IllegalArgumentException ( "All elements in the JSON array must be an JsonObject, but was: " + jsonValue . getValueType ( ) ) ; } events . add ( EscEvent . create ( ( JsonObject ) jsonValue ) ) ; } return new EscEvents ( events ) ; } | Creates in instance from the given JSON array . |
19,214 | static KAFDocument load ( File file ) throws IOException , JDOMException , KAFNotValidException { SAXBuilder builder = new SAXBuilder ( ) ; Document document = ( Document ) builder . build ( file ) ; Element rootElem = document . getRootElement ( ) ; return DOMToKAF ( document ) ; } | Loads the content of a KAF file into the given KAFDocument object |
19,215 | static KAFDocument load ( Reader stream ) throws IOException , JDOMException , KAFNotValidException { SAXBuilder builder = new SAXBuilder ( ) ; Document document = ( Document ) builder . build ( stream ) ; Element rootElem = document . getRootElement ( ) ; return DOMToKAF ( document ) ; } | Loads the content of a String in KAF format into the given KAFDocument object |
19,216 | static void save ( KAFDocument kaf , String filename ) { try { File file = new File ( filename ) ; Writer out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( file ) , "UTF8" ) ) ; out . write ( kafToStr ( kaf ) ) ; out . flush ( ) ; } catch ( Exception e ) { System . out . println ( "Error writing to file" ) ; } } | Writes the content of a given KAFDocument to a file . |
19,217 | static void print ( KAFDocument kaf ) { try { Writer out = new BufferedWriter ( new OutputStreamWriter ( System . out , "UTF8" ) ) ; out . write ( kafToStr ( kaf ) ) ; out . flush ( ) ; } catch ( Exception e ) { System . out . println ( e ) ; } } | Writes the content of a KAFDocument object to standard output . |
19,218 | static String kafToStr ( KAFDocument kaf ) { XMLOutputter out = new XMLOutputter ( Format . getPrettyFormat ( ) . setLineSeparator ( LineSeparator . UNIX ) . setTextMode ( Format . TextMode . TRIM_FULL_WHITE ) ) ; Document jdom = KAFToDOM ( kaf ) ; return out . outputString ( jdom ) ; } | Returns a string containing the XML content of a KAFDocument object . |
19,219 | public Query getOptimizedQuery ( ) { Query q = _baseQuery . clone ( ) ; Set < Entry < FilterConsumer , FilterOutcome > > entries = _optimizedFilters . entrySet ( ) ; for ( Entry < FilterConsumer , FilterOutcome > entry : entries ) { FilterConsumer consumer = entry . getKey ( ) ; FilterOutcome outcome = entry . getValue ( ) ; Filter < ? > filter = consumer . getComponent ( ) ; @ SuppressWarnings ( "rawtypes" ) QueryOptimizedFilter queryOptimizedFilter = ( QueryOptimizedFilter ) filter ; @ SuppressWarnings ( "unchecked" ) Query newQuery = queryOptimizedFilter . optimizeQuery ( q , outcome . getCategory ( ) ) ; q = newQuery ; } return q ; } | Gets the optimized query . |
19,220 | public List < Token > tokenize ( String s ) { List < Token > result = new ArrayList < Token > ( ) ; result . add ( new UndefinedToken ( s ) ) ; for ( PredefinedTokenDefinition predefinedTokenDefinition : _predefinedTokenDefitions ) { Set < Pattern > patterns = predefinedTokenDefinition . getTokenRegexPatterns ( ) ; for ( Pattern pattern : patterns ) { for ( ListIterator < Token > it = result . listIterator ( ) ; it . hasNext ( ) ; ) { Token token = it . next ( ) ; if ( token instanceof UndefinedToken ) { List < Token > replacementTokens = tokenizeInternal ( token . getString ( ) , predefinedTokenDefinition , pattern ) ; if ( replacementTokens . size ( ) > 1 ) { it . remove ( ) ; for ( Token newToken : replacementTokens ) { it . add ( newToken ) ; } } } } } } return result ; } | Will only return either tokens with type PREDEFINED or UNDEFINED |
19,221 | public void doLog ( String clientID , String name , long time , Level level , Object message , Throwable t ) { if ( logOpen && formatter != null ) { sendMessage ( syslogMessage . createMessageData ( formatter . format ( clientID , name , time , level , message , t ) ) ) ; } } | Do the logging . |
19,222 | public String format ( String clientID , String name , long time , Level level , Object message , Throwable t ) { if ( ! patternParsed && pattern != null ) { parsePattern ( pattern ) ; } StringBuffer formattedStringBuffer = new StringBuffer ( 64 ) ; if ( commandArray != null ) { int length = commandArray . length ; for ( int index = 0 ; index < length ; index ++ ) { FormatCommandInterface currentConverter = commandArray [ index ] ; if ( currentConverter != null ) { formattedStringBuffer . append ( currentConverter . execute ( clientID , name , time , level , message , t ) ) ; } } } return formattedStringBuffer . toString ( ) ; } | Format the input parameters . |
19,223 | public void setPattern ( String pattern ) throws IllegalArgumentException { if ( pattern == null ) { throw new IllegalArgumentException ( "The pattern must not be null." ) ; } this . pattern = pattern ; parsePattern ( this . pattern ) ; } | Set the pattern that is when formatting . |
19,224 | private void parsePattern ( String pattern ) { int currentIndex = 0 ; int patternLength = pattern . length ( ) ; Vector < FormatCommandInterface > converterVector = new Vector < FormatCommandInterface > ( 20 ) ; while ( currentIndex < patternLength ) { char currentChar = pattern . charAt ( currentIndex ) ; if ( currentChar == '%' ) { currentIndex ++ ; currentChar = pattern . charAt ( currentIndex ) ; switch ( currentChar ) { case CLIENT_ID_CONVERSION_CHAR : converterVector . addElement ( new ClientIdFormatCommand ( ) ) ; break ; case CATEGORY_CONVERSION_CHAR : CategoryFormatCommand categoryFormatCommand = new CategoryFormatCommand ( ) ; String specifier = extraxtSpecifier ( pattern , currentIndex ) ; int specifierLength = specifier . length ( ) ; if ( specifierLength > 0 ) { categoryFormatCommand . init ( specifier ) ; currentIndex = currentIndex + specifierLength + 2 ; } converterVector . addElement ( categoryFormatCommand ) ; break ; case DATE_CONVERSION_CHAR : DateFormatCommand formatCommand = new DateFormatCommand ( ) ; specifier = extraxtSpecifier ( pattern , currentIndex ) ; specifierLength = specifier . length ( ) ; if ( specifierLength > 0 ) { formatCommand . init ( specifier ) ; currentIndex = currentIndex + specifierLength + 2 ; } converterVector . addElement ( formatCommand ) ; break ; case MESSAGE_CONVERSION_CHAR : converterVector . addElement ( new MessageFormatCommand ( ) ) ; break ; case PRIORITY_CONVERSION_CHAR : converterVector . addElement ( new PriorityFormatCommand ( ) ) ; break ; case RELATIVE_TIME_CONVERSION_CHAR : converterVector . addElement ( new TimeFormatCommand ( ) ) ; break ; case THREAD_CONVERSION_CHAR : converterVector . addElement ( new ThreadFormatCommand ( ) ) ; break ; case THROWABLE_CONVERSION_CHAR : converterVector . addElement ( new ThrowableFormatCommand ( ) ) ; break ; case PERCENT_CONVERSION_CHAR : NoFormatCommand noFormatCommand = new NoFormatCommand ( ) ; noFormatCommand . init ( "%" ) ; converterVector . addElement ( noFormatCommand ) ; break ; default : Log . e ( TAG , "Unrecognized conversion character " + currentChar ) ; break ; } currentIndex ++ ; } else { int percentIndex = pattern . indexOf ( "%" , currentIndex ) ; String noFormatString = "" ; if ( percentIndex != - 1 ) { noFormatString = pattern . substring ( currentIndex , percentIndex ) ; } else { noFormatString = pattern . substring ( currentIndex , patternLength ) ; } NoFormatCommand noFormatCommand = new NoFormatCommand ( ) ; noFormatCommand . init ( noFormatString ) ; converterVector . addElement ( noFormatCommand ) ; currentIndex = currentIndex + noFormatString . length ( ) ; } } commandArray = new FormatCommandInterface [ converterVector . size ( ) ] ; converterVector . copyInto ( commandArray ) ; patternParsed = true ; } | Parse the pattern . |
19,225 | public static < K , V > Map < K , V > zip ( List < K > keys , List < V > values ) { checkArgument ( keys != null , "Expected non-null keys" ) ; checkArgument ( values != null , "Expected non-null values" ) ; checkArgument ( keys . size ( ) == values . size ( ) , "Expected equal size of lists, got %s and %s" , keys . size ( ) , values . size ( ) ) ; ImmutableMap . Builder < K , V > builder = ImmutableMap . builder ( ) ; for ( int i = 0 ; i < keys . size ( ) ; i ++ ) { builder . put ( keys . get ( i ) , values . get ( i ) ) ; } return builder . build ( ) ; } | Combine two lists into a map . Lists must have the same size . |
19,226 | public static < K , V > Map . Entry < K , V > getOnlyEntry ( Map < K , V > map ) { checkArgument ( map != null , "Expected non-null map" ) ; return getOnlyElement ( map . entrySet ( ) ) ; } | Gets the only element from a given map or throws an exception |
19,227 | public static < K , V > Map < K , V > mergeMaps ( Map < K , V > first , Map < K , V > second , V defaultValue ) { checkArgument ( first != null , "Expected non-null first map" ) ; checkArgument ( second != null , "Expected non-null second map" ) ; checkArgument ( defaultValue != null , "Expected non-null default value" ) ; Map < K , V > map = new HashMap < K , V > ( ) ; for ( Map . Entry < K , V > entry : first . entrySet ( ) ) { if ( entry . getKey ( ) == null ) { continue ; } map . put ( entry . getKey ( ) , entry . getValue ( ) == null ? defaultValue : entry . getValue ( ) ) ; } for ( Map . Entry < K , V > entry : second . entrySet ( ) ) { if ( entry . getKey ( ) == null ) { continue ; } map . put ( entry . getKey ( ) , entry . getValue ( ) == null ? defaultValue : entry . getValue ( ) ) ; } return map ; } | Mergers two maps handling null keys null values and duplicates |
19,228 | public static < M extends PMessage < M , F > , F extends PField , B extends PMessageBuilder < M , F > > List < M > buildAll ( Collection < B > builders ) { if ( builders == null ) { return null ; } return builders . stream ( ) . map ( PMessageBuilder :: build ) . collect ( Collectors . toList ( ) ) ; } | Build all items of the collection containing builders . The list must not contain any null items . |
19,229 | @ SuppressWarnings ( "unchecked" ) public static < M extends PMessage < M , F > , F extends PField , B extends PMessageBuilder < M , F > > List < B > mutateAll ( Collection < M > messages ) { if ( messages == null ) { return null ; } return ( List < B > ) messages . stream ( ) . map ( PMessage :: mutate ) . collect ( Collectors . toList ( ) ) ; } | Mutate all items of the collection containing messages . The list must not contain any null items . |
19,230 | public static < M extends PMessage < M , F > , F extends PField , B extends PMessageBuilder < M , F > > M buildIfNotNull ( B builder ) { if ( builder == null ) { return null ; } return builder . build ( ) ; } | Build the message from builder if it is not null . |
19,231 | @ SuppressWarnings ( "unchecked" ) public static < M extends PMessage < M , F > , F extends PField , B extends PMessageBuilder < M , F > > B mutateIfNotNull ( M message ) { if ( message == null ) { return null ; } return ( B ) message . mutate ( ) ; } | Mutate the message if it is not null . |
19,232 | static boolean isSupported ( int index ) { if ( ( index <= 0 ) || ( index >= NAMED_CURVE_OID_TABLE . length ) ) { return false ; } if ( fips == false ) { return true ; } return DEFAULT . contains ( index ) ; } | Test whether we support the curve with the given index . |
19,233 | public static < M extends PMessage < M , F > , F extends PField > MessageFieldArgument < M , F > toField ( M message , F field ) { return new MessageFieldArgument < > ( message , field ) ; } | Bind to the given field for the message . |
19,234 | public static < F extends PField > MappedField < F > withColumn ( F field ) { return new MappedField < > ( field . getName ( ) , field ) ; } | With column mapped to field using the field name . |
19,235 | public static < F extends PField > MappedField < F > withColumn ( String name , F field ) { return new MappedField < > ( name , field ) ; } | With column mapped to field . |
19,236 | public AuthenticationInfo beforeAllAttempts ( Collection < ? extends Realm > realms , AuthenticationToken token ) throws AuthenticationException { final SimpleAuthenticationInfo authenticationInfo = ( SimpleAuthenticationInfo ) super . beforeAllAttempts ( realms , token ) ; authenticationInfo . setPrincipals ( new PrincipalCollectionWithSinglePrincipalForApplicationUserInAnyRealm ( ) ) ; return authenticationInfo ; } | Reconfigures the SimpleAuthenticationInfo to use a implementation for storing its PrincipalCollections . |
19,237 | protected final void set ( M config ) { ArrayList < WeakReference < ConfigListener < M , F > > > iterateOver ; synchronized ( this ) { M old = instance . get ( ) ; if ( old == config || ( old != null && old . equals ( config ) ) ) { return ; } instance . set ( config ) ; lastUpdateTimestamp . set ( clock . millis ( ) ) ; listeners . removeIf ( ref -> ref . get ( ) == null ) ; iterateOver = new ArrayList < > ( listeners ) ; } iterateOver . forEach ( ref -> { ConfigListener < M , F > listener = ref . get ( ) ; if ( listener != null ) { try { listener . onConfigChange ( config ) ; } catch ( Exception ignore ) { } } } ) ; } | Set a new config value to the supplier . This is protected as it is usually up to the supplier implementation to enable updating the config at later stages . |
19,238 | private List < AgigaTypedDependency > parseDependencies ( VTDNav vn , DependencyForm form ) throws NavException , PilotException { require ( vn . matchElement ( AgigaConstants . SENTENCE ) ) ; require ( vn . toElement ( VTDNav . FC , form . getXmlTag ( ) ) ) ; List < AgigaTypedDependency > agigaDeps = new ArrayList < AgigaTypedDependency > ( ) ; AutoPilot basicDepRelAp = new AutoPilot ( vn ) ; basicDepRelAp . selectElement ( AgigaConstants . DEP ) ; while ( basicDepRelAp . iterate ( ) ) { String type = vn . toString ( vn . getAttrVal ( AgigaConstants . DEP_TYPE ) ) ; require ( vn . toElement ( VTDNav . FC , AgigaConstants . GOVERNOR ) ) ; int governorId = vn . parseInt ( vn . getText ( ) ) ; require ( vn . toElement ( VTDNav . NS , AgigaConstants . DEPENDENT ) ) ; int dependentId = vn . parseInt ( vn . getText ( ) ) ; log . finer ( String . format ( "\tdep type=%s\t%d , type , governorId , dependentId ) ) ; AgigaTypedDependency agigaDep = new AgigaTypedDependency ( type , governorId - 1 , dependentId - 1 ) ; agigaDeps . add ( agigaDep ) ; } return agigaDeps ; } | Assumes the position of vn is at a sent tag |
19,239 | public void configure ( String filename , boolean isExternalFile ) { try { Properties properties ; InputStream inputStream ; if ( ! isExternalFile ) { Resources resources = context . getResources ( ) ; AssetManager assetManager = resources . getAssets ( ) ; inputStream = assetManager . open ( filename ) ; } else { inputStream = new FileInputStream ( filename ) ; } properties = loadProperties ( inputStream ) ; inputStream . close ( ) ; startConfiguration ( properties ) ; } catch ( IOException e ) { Log . e ( TAG , "Failed to open file. " + filename + " " + e ) ; } } | Configure using the specified filename . |
19,240 | public void configure ( int resId ) { Resources resources = context . getResources ( ) ; try { InputStream rawResource = resources . openRawResource ( resId ) ; Properties properties = loadProperties ( rawResource ) ; startConfiguration ( properties ) ; } catch ( NotFoundException e ) { Log . e ( TAG , "Did not find resource." + e ) ; } catch ( IOException e ) { Log . e ( TAG , "Failed to read the resource." + e ) ; } } | Configure using the specified resource Id . |
19,241 | private void startConfiguration ( Properties properties ) { if ( properties . containsKey ( Configurator . ROOT_LOGGER_KEY ) ) { Log . i ( TAG , "Modern configuration not yet supported" ) ; } else { Log . i ( TAG , "Configure using the simple style (aka classic style)" ) ; configureSimpleStyle ( properties ) ; } } | Start the configuration |
19,242 | void setVersion ( ProtocolVersion protocolVersion ) { this . protocolVersion = protocolVersion ; setVersionSE ( protocolVersion ) ; output . r . setVersion ( protocolVersion ) ; } | Set the active protocol version and propagate it to the SSLSocket and our handshake streams . Called from ClientHandshaker and ServerHandshaker with the negotiated protocol version . |
19,243 | void activate ( ProtocolVersion helloVersion ) throws IOException { if ( activeProtocols == null ) { activeProtocols = getActiveProtocols ( ) ; } if ( activeProtocols . collection ( ) . isEmpty ( ) || activeProtocols . max . v == ProtocolVersion . NONE . v ) { throw new SSLHandshakeException ( "No appropriate protocol (protocol is disabled or " + "cipher suites are inappropriate)" ) ; } if ( activeCipherSuites == null ) { activeCipherSuites = getActiveCipherSuites ( ) ; } if ( activeCipherSuites . collection ( ) . isEmpty ( ) ) { throw new SSLHandshakeException ( "No appropriate cipher suite" ) ; } if ( ! isInitialHandshake ) { protocolVersion = activeProtocolVersion ; } else { protocolVersion = activeProtocols . max ; } if ( helloVersion == null || helloVersion . v == ProtocolVersion . NONE . v ) { helloVersion = activeProtocols . helloVersion ; } Set < String > localSupportedHashAlgorithms = SignatureAndHashAlgorithm . getHashAlgorithmNames ( getLocalSupportedSignAlgs ( ) ) ; handshakeHash = new HandshakeHash ( ! isClient , needCertVerify , localSupportedHashAlgorithms ) ; input = new HandshakeInStream ( handshakeHash ) ; if ( conn != null ) { output = new HandshakeOutStream ( protocolVersion , helloVersion , handshakeHash , conn ) ; conn . getAppInputStream ( ) . r . setHandshakeHash ( handshakeHash ) ; conn . getAppInputStream ( ) . r . setHelloVersion ( helloVersion ) ; conn . getAppOutputStream ( ) . r . setHelloVersion ( helloVersion ) ; } else { output = new HandshakeOutStream ( protocolVersion , helloVersion , handshakeHash , engine ) ; engine . inputRecord . setHandshakeHash ( handshakeHash ) ; engine . inputRecord . setHelloVersion ( helloVersion ) ; engine . outputRecord . setHelloVersion ( helloVersion ) ; } state = - 1 ; } | Prior to handshaking activate the handshake and initialize the version input stream and output stream . |
19,244 | boolean isNegotiable ( CipherSuite s ) { if ( activeCipherSuites == null ) { activeCipherSuites = getActiveCipherSuites ( ) ; } return activeCipherSuites . contains ( s ) && s . isNegotiable ( ) ; } | Check if the given ciphersuite is enabled and available . Does not check if the required server certificates are available . |
19,245 | boolean isNegotiable ( ProtocolVersion protocolVersion ) { if ( activeProtocols == null ) { activeProtocols = getActiveProtocols ( ) ; } return activeProtocols . contains ( protocolVersion ) ; } | Check if the given protocol version is enabled and available . |
19,246 | ProtocolVersion selectProtocolVersion ( ProtocolVersion protocolVersion ) { if ( activeProtocols == null ) { activeProtocols = getActiveProtocols ( ) ; } return activeProtocols . selectProtocolVersion ( protocolVersion ) ; } | Select a protocol version from the list . Called from ServerHandshaker to negotiate protocol version . |
19,247 | CipherSuiteList getActiveCipherSuites ( ) { if ( activeCipherSuites == null ) { if ( activeProtocols == null ) { activeProtocols = getActiveProtocols ( ) ; } ArrayList < CipherSuite > suites = new ArrayList < > ( ) ; if ( ! ( activeProtocols . collection ( ) . isEmpty ( ) ) && activeProtocols . min . v != ProtocolVersion . NONE . v ) { for ( CipherSuite suite : enabledCipherSuites . collection ( ) ) { if ( suite . obsoleted > activeProtocols . min . v && suite . supported <= activeProtocols . max . v ) { if ( algorithmConstraints . permits ( EnumSet . of ( CryptoPrimitive . KEY_AGREEMENT ) , suite . name , null ) ) { suites . add ( suite ) ; } } else if ( debug != null && Debug . isOn ( "verbose" ) ) { if ( suite . obsoleted <= activeProtocols . min . v ) { System . out . println ( "Ignoring obsoleted cipher suite: " + suite ) ; } else { System . out . println ( "Ignoring unsupported cipher suite: " + suite ) ; } } } } activeCipherSuites = new CipherSuiteList ( suites ) ; } return activeCipherSuites ; } | Get the active cipher suites . |
19,248 | CipherBox newReadCipher ( ) throws NoSuchAlgorithmException { BulkCipher cipher = cipherSuite . cipher ; CipherBox box ; if ( isClient ) { box = cipher . newCipher ( protocolVersion , svrWriteKey , svrWriteIV , sslContext . getSecureRandom ( ) , false ) ; svrWriteKey = null ; svrWriteIV = null ; } else { box = cipher . newCipher ( protocolVersion , clntWriteKey , clntWriteIV , sslContext . getSecureRandom ( ) , false ) ; clntWriteKey = null ; clntWriteIV = null ; } return box ; } | Create a new read cipher and return it to caller . |
19,249 | MAC newReadMAC ( ) throws NoSuchAlgorithmException , InvalidKeyException { MacAlg macAlg = cipherSuite . macAlg ; MAC mac ; if ( isClient ) { mac = macAlg . newMac ( protocolVersion , svrMacSecret ) ; svrMacSecret = null ; } else { mac = macAlg . newMac ( protocolVersion , clntMacSecret ) ; clntMacSecret = null ; } return mac ; } | Create a new read MAC and return it to caller . |
19,250 | static void throwSSLException ( String msg , Throwable cause ) throws SSLException { SSLException e = new SSLException ( msg ) ; e . initCause ( cause ) ; throw e ; } | Throw an SSLException with the specified message and cause . Shorthand until a new SSLException constructor is added . This method never returns . |
19,251 | static Object getInMessage ( PMessage message , String key ) throws ProvidenceConfigException { return getInMessage ( message , key , null ) ; } | Look up a key in the message structure . If the key is not found return null . |
19,252 | static Object getInMessage ( PMessage message , final String key , Object defValue ) throws ProvidenceConfigException { String sub = key ; String name ; PMessageDescriptor descriptor = message . descriptor ( ) ; while ( sub . contains ( "." ) ) { int idx = sub . indexOf ( "." ) ; name = sub . substring ( 0 , idx ) ; sub = sub . substring ( idx + 1 ) ; PField field = descriptor . findFieldByName ( name ) ; if ( field == null ) { throw new ProvidenceConfigException ( "Message " + descriptor . getQualifiedName ( ) + " has no field named " + name ) ; } PDescriptor fieldDesc = field . getDescriptor ( ) ; if ( fieldDesc . getType ( ) != PType . MESSAGE ) { throw new ProvidenceConfigException ( "Field '" + name + "' is not of message type in " + descriptor . getQualifiedName ( ) ) ; } descriptor = ( PMessageDescriptor ) fieldDesc ; if ( message != null ) { message = ( PMessage ) message . get ( field . getId ( ) ) ; } } PField field = descriptor . findFieldByName ( sub ) ; if ( field == null ) { throw new ProvidenceConfigException ( "Message " + descriptor . getQualifiedName ( ) + " has no field named " + sub ) ; } if ( message == null || ! message . has ( field . getId ( ) ) ) { return asType ( field . getDescriptor ( ) , defValue ) ; } return message . get ( field . getId ( ) ) ; } | Look up a key in the message structure . If the key is not found return the default value . Note that the default value will be converted to the type of the declared field not returned verbatim . |
19,253 | static double asDouble ( Object value ) throws ProvidenceConfigException { if ( value instanceof Number ) { return ( ( Number ) value ) . doubleValue ( ) ; } else if ( value instanceof Numeric ) { return ( ( Numeric ) value ) . asInteger ( ) ; } throw new ProvidenceConfigException ( "Unable to convert " + value . getClass ( ) . getSimpleName ( ) + " to a double" ) ; } | Convert the value to a double . |
19,254 | static String asString ( Object value ) throws ProvidenceConfigException { if ( value instanceof Collection || value instanceof Map ) { throw new ProvidenceConfigException ( "Unable to convert " + value . getClass ( ) . getSimpleName ( ) + " to a string" ) ; } else if ( value instanceof Stringable ) { return ( ( Stringable ) value ) . asString ( ) ; } else if ( value instanceof Date ) { Instant instant = ( ( Date ) value ) . toInstant ( ) ; return DateTimeFormatter . ISO_INSTANT . format ( instant ) ; } return Objects . toString ( value ) ; } | Convert the value to a string . |
19,255 | static Path resolveFile ( Path reference , String path ) throws IOException { if ( reference == null ) { Path file = canonicalFileLocation ( Paths . get ( path ) ) ; if ( Files . exists ( file ) ) { if ( Files . isRegularFile ( file ) ) { return file ; } throw new FileNotFoundException ( path + " is a directory, expected file" ) ; } throw new FileNotFoundException ( "File " + path + " not found" ) ; } else if ( path . startsWith ( "/" ) ) { throw new FileNotFoundException ( "Absolute path includes not allowed: " + path ) ; } else { reference = readCanonicalPath ( reference ) ; if ( ! Files . isDirectory ( reference ) ) { reference = reference . getParent ( ) ; } Path file = canonicalFileLocation ( reference . resolve ( path ) ) ; if ( Files . exists ( file ) ) { if ( Files . isRegularFile ( file ) ) { return file ; } throw new FileNotFoundException ( path + " is a directory, expected file" ) ; } throw new FileNotFoundException ( "Included file " + path + " not found" ) ; } } | Resolve a file path within the source roots . |
19,256 | public static int getNextAvailablePort ( int fromPort , int toPort ) { if ( fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER || fromPort > toPort ) { throw new IllegalArgumentException ( format ( "Invalid port range: %d ~ %d" , fromPort , toPort ) ) ; } int nextPort = fromPort ; while ( ! isPortAvailable ( nextPort ++ ) ) { } return nextPort ; } | Returns a currently available port number in the specified range . |
19,257 | public static boolean isPortAvailable ( int port ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "Testing port " ) . append ( port ) . append ( "\n" ) ; try ( Socket s = new Socket ( "localhost" , port ) ) { builder . append ( "Port " ) . append ( port ) . append ( " is not available" ) . append ( "\n" ) ; return false ; } catch ( IOException e ) { builder . append ( "Port " ) . append ( port ) . append ( " is available" ) . append ( "\n" ) ; return true ; } finally { log . fine ( builder . toString ( ) ) ; } } | Checks if a port is available by opening a socket on it |
19,258 | public Collection < F > presentFields ( ) { return Arrays . stream ( descriptor ( ) . getFields ( ) ) . filter ( this :: isSet ) . collect ( Collectors . toList ( ) ) ; } | Get a Collection of F with fields set on the builder . A . k . a is present . |
19,259 | public Collection < F > modifiedFields ( ) { return Arrays . stream ( descriptor ( ) . getFields ( ) ) . filter ( this :: isModified ) . collect ( Collectors . toList ( ) ) ; } | Get a Collection of F with fields Modified since creation of the builder . |
19,260 | public static < T extends Enum < T > & RichEnum < T > > RichEnumConstants < T > richConstants ( Class < T > theClass ) { return new RichEnumConstants < > ( theClass ) ; } | The factory method |
19,261 | public void putConfigurationValue ( String key , Object value ) { this . configuration . put ( key , value ) ; } | Put a value in the module configuration map . |
19,262 | public java . util . Optional < String > optionalFilePath ( ) { return java . util . Optional . ofNullable ( mFilePath ) ; } | Full absolute path to the file . |
19,263 | public java . util . Optional < java . util . List < String > > optionalFileLines ( ) { return java . util . Optional . ofNullable ( mFileLines ) ; } | The lines of the program file |
19,264 | public java . util . Optional < net . morimekta . providence . model . ProgramType > optionalProgram ( ) { return java . util . Optional . ofNullable ( mProgram ) ; } | The program type definition |
19,265 | public ProgramTypeRegistry registryForPath ( String path ) { return registryMap . computeIfAbsent ( path , p -> new ProgramTypeRegistry ( programNameFromPath ( path ) ) ) ; } | Get a program type registry for the file at given path . If the registry is not created yet it will be created . |
19,266 | public boolean containsProgramPath ( String path ) { return registryMap . containsKey ( path ) && registryMap . get ( path ) . getProgram ( ) != null ; } | Gets the document for a given file path . |
19,267 | public void completeFrame ( ) throws IOException { int frameSize = buffer . position ( ) ; if ( frameSize > 0 ) { frameSizeBuffer . rewind ( ) ; try ( ByteBufferOutputStream bos = new ByteBufferOutputStream ( frameSizeBuffer ) ; BinaryWriter writer = new BigEndianBinaryWriter ( bos ) ) { writer . writeInt ( frameSize ) ; bos . flush ( ) ; } frameSizeBuffer . flip ( ) ; buffer . flip ( ) ; synchronized ( out ) { out . write ( frameSizeBuffer ) ; while ( buffer . hasRemaining ( ) ) { out . write ( buffer ) ; } } buffer . rewind ( ) ; buffer . limit ( buffer . capacity ( ) ) ; } } | Write the frame at the current state and reset the buffer to be able to generate a new frame . |
19,268 | public synchronized void put ( ApnsConnection connection ) { if ( connection == null ) { throw new IllegalArgumentException ( "connection must not be null" ) ; } if ( mPool . size ( ) < mCapacity ) { mPool . add ( connection ) ; } } | If and only if size of the pool is less than its capacity then connection is put into the pool and size of the pool incremented by one ; otherwise method argument is ignored and pool is not changed . |
19,269 | public static HashCode newHash ( String input , HashFunction function ) { return function . hashString ( input , Charsets . UTF_8 ) ; } | Creates a UTF - 8 encoded hash using the hash function |
19,270 | private static boolean equalsQualifiedName ( PDescriptor a , PDescriptor b ) { return ( a != null ) && ( b != null ) && ( a . getQualifiedName ( ) . equals ( b . getQualifiedName ( ) ) ) ; } | Check if the two descriptors has the same qualified name i .. e symbolically represent the same type . |
19,271 | private boolean setupPrivateKeyAndChain ( String algorithm ) { X509ExtendedKeyManager km = sslContext . getX509KeyManager ( ) ; String alias ; if ( conn != null ) { alias = km . chooseServerAlias ( algorithm , null , conn ) ; } else { alias = km . chooseEngineServerAlias ( algorithm , null , engine ) ; } if ( alias == null ) { return false ; } PrivateKey tempPrivateKey = km . getPrivateKey ( alias ) ; if ( tempPrivateKey == null ) { return false ; } X509Certificate [ ] tempCerts = km . getCertificateChain ( alias ) ; if ( ( tempCerts == null ) || ( tempCerts . length == 0 ) ) { return false ; } String keyAlgorithm = algorithm . split ( "_" ) [ 0 ] ; PublicKey publicKey = tempCerts [ 0 ] . getPublicKey ( ) ; if ( ( tempPrivateKey . getAlgorithm ( ) . equals ( keyAlgorithm ) == false ) || ( publicKey . getAlgorithm ( ) . equals ( keyAlgorithm ) == false ) ) { return false ; } if ( keyAlgorithm . equals ( "EC" ) ) { if ( publicKey instanceof ECPublicKey == false ) { return false ; } ECParameterSpec params = ( ( ECPublicKey ) publicKey ) . getParams ( ) ; int index = SupportedEllipticCurvesExtension . getCurveIndex ( params ) ; if ( SupportedEllipticCurvesExtension . isSupported ( index ) == false ) { return false ; } if ( ( supportedCurves != null ) && ! supportedCurves . contains ( index ) ) { return false ; } } this . privateKey = tempPrivateKey ; this . certs = tempCerts ; return true ; } | Retrieve the server key and certificate for the specified algorithm from the KeyManager and set the instance variables . |
19,272 | private boolean setupKerberosKeys ( ) { if ( kerberosKeys != null ) { return true ; } try { final AccessControlContext acc = getAccSE ( ) ; kerberosKeys = AccessController . doPrivileged ( new PrivilegedExceptionAction < SecretKey [ ] > ( ) { public SecretKey [ ] run ( ) throws Exception { return Krb5Helper . getServerKeys ( acc ) ; } } ) ; if ( kerberosKeys != null && kerberosKeys . length > 0 ) { if ( debug != null && Debug . isOn ( "handshake" ) ) { for ( SecretKey k : kerberosKeys ) { System . out . println ( "Using Kerberos key: " + k ) ; } } String serverPrincipal = Krb5Helper . getServerPrincipalName ( kerberosKeys [ 0 ] ) ; SecurityManager sm = System . getSecurityManager ( ) ; try { if ( sm != null ) { sm . checkPermission ( Krb5Helper . getServicePermission ( serverPrincipal , "accept" ) , acc ) ; } } catch ( SecurityException se ) { kerberosKeys = null ; if ( debug != null && Debug . isOn ( "handshake" ) ) System . out . println ( "Permission to access Kerberos" + " secret key denied" ) ; return false ; } } return ( kerberosKeys != null && kerberosKeys . length > 0 ) ; } catch ( PrivilegedActionException e ) { if ( debug != null && Debug . isOn ( "handshake" ) ) { System . out . println ( "Attempt to obtain Kerberos key failed: " + e . toString ( ) ) ; } return false ; } } | Retrieve the Kerberos key for the specified server principal from the JAAS configuration file . |
19,273 | public boolean implies ( final ApplicationFeatureId featureId , final ApplicationPermissionMode mode ) { if ( getRule ( ) != ApplicationPermissionRule . ALLOW ) { return false ; } if ( getMode ( ) == ApplicationPermissionMode . VIEWING && mode == ApplicationPermissionMode . CHANGING ) { return false ; } return onPathOf ( featureId ) ; } | region > implies refutes |
19,274 | public static PPrimitive findByName ( String name ) { switch ( name ) { case "void" : return VOID ; case "bool" : return BOOL ; case "byte" : case "i8" : return BYTE ; case "i16" : return I16 ; case "i32" : return I32 ; case "i64" : return I64 ; case "double" : return DOUBLE ; case "string" : return STRING ; case "binary" : return BINARY ; } return null ; } | Find primitive by name . |
19,275 | public String execute ( String clientID , String name , long time , Level level , Object message , Throwable throwable ) { StringBuilder sb = new StringBuilder ( ) ; if ( throwable != null ) { sb . append ( throwable . toString ( ) ) ; String newline = System . getProperty ( "line.separator" ) ; StackTraceElement [ ] stackTrace = throwable . getStackTrace ( ) ; for ( int i = 0 ; i < stackTrace . length ; i ++ ) { StackTraceElement element = stackTrace [ i ] ; sb . append ( newline ) ; sb . append ( "\tat " ) ; sb . append ( element . toString ( ) ) ; } } return sb . toString ( ) ; } | Set the log data . |
19,276 | public String createMessageData ( String message ) { messageStringBuffer . delete ( 0 , messageStringBuffer . length ( ) ) ; messageStringBuffer . append ( '<' ) ; int priority = facility * 8 + severity ; messageStringBuffer . append ( priority ) ; messageStringBuffer . append ( '>' ) ; if ( header ) { long currentTime = System . currentTimeMillis ( ) ; calendar . setTime ( new Date ( currentTime ) ) ; messageStringBuffer . append ( SyslogMessage . MONTHS [ calendar . get ( Calendar . MONTH ) ] ) ; messageStringBuffer . append ( ' ' ) ; int dayOfMonth = calendar . get ( Calendar . DAY_OF_MONTH ) ; if ( dayOfMonth < SyslogMessage . TEN ) { messageStringBuffer . append ( '0' ) ; } messageStringBuffer . append ( dayOfMonth ) ; messageStringBuffer . append ( ' ' ) ; int hour = calendar . get ( Calendar . HOUR_OF_DAY ) ; if ( hour < SyslogMessage . TEN ) { messageStringBuffer . append ( '0' ) ; } messageStringBuffer . append ( hour ) ; messageStringBuffer . append ( ':' ) ; int minute = calendar . get ( Calendar . MINUTE ) ; if ( minute < SyslogMessage . TEN ) { messageStringBuffer . append ( '0' ) ; } messageStringBuffer . append ( minute ) ; messageStringBuffer . append ( ':' ) ; int second = calendar . get ( Calendar . SECOND ) ; if ( second < SyslogMessage . TEN ) { messageStringBuffer . append ( '0' ) ; } messageStringBuffer . append ( second ) ; messageStringBuffer . append ( ' ' ) ; messageStringBuffer . append ( hostname ) ; } messageStringBuffer . append ( ' ' ) ; messageStringBuffer . append ( tag ) ; messageStringBuffer . append ( ": " ) ; messageStringBuffer . append ( message ) ; return messageStringBuffer . toString ( ) ; } | Create the syslog message data that is consequently wrapped in a datagram . |
19,277 | public void setFacility ( byte facility ) { if ( facility < SyslogMessage . FACILITY_KERNAL_MESSAGE || facility > SyslogMessage . FACILITY_LOCAL_USE_7 ) { throw new IllegalArgumentException ( "Not a valid facility." ) ; } this . facility = facility ; } | Set the facility that is used when sending message . |
19,278 | public void setSeverity ( byte severity ) throws IllegalArgumentException { if ( severity < SyslogMessage . SEVERITY_EMERGENCY || severity > SyslogMessage . SEVERITY_DEBUG ) { throw new IllegalArgumentException ( "Not a valid severity." ) ; } this . severity = severity ; } | Get the severity at which the message shall be sent . |
19,279 | public void setTag ( String tag ) throws IllegalArgumentException { if ( tag == null || ( tag != null && ( tag . length ( ) < 1 || tag . length ( ) > 32 ) ) ) { throw new IllegalArgumentException ( "The tag must not be null, the length between 1..32" ) ; } this . tag = tag ; } | Set the tag that is used for the TAG field in the MSG part of the message . The TAG length must not exceed 32 chars . |
19,280 | public static Properties getFileAsProperties ( String path ) { File file = new File ( nullToEmpty ( path ) ) ; return getFileAsProperties ( file ) ; } | Loads properties from file path |
19,281 | public java . util . Optional < net . morimekta . util . Binary > optionalData ( ) { return java . util . Optional . ofNullable ( mData ) ; } | The actual content binary data . |
19,282 | private void reload ( ) { try { if ( ! configFile . exists ( ) ) { LOGGER . warn ( "Config file deleted " + configFile + ", keeping old config." ) ; return ; } LOGGER . trace ( "Config reload triggered for " + configFile ) ; if ( parentSupplier != null ) { set ( loadConfig ( parentSupplier . get ( ) ) ) ; } else { set ( loadConfig ( null ) ) ; } } catch ( ProvidenceConfigException e ) { LOGGER . error ( "Exception when reloading " + configFile , e ) ; } } | Trigger reloading of the config file . |
19,283 | public static < Message extends PMessage < Message , Field > , Field extends PField > Message readMessage ( BigEndianBinaryReader input , PMessageDescriptor < Message , Field > descriptor , boolean strict ) throws IOException { PMessageBuilder < Message , Field > builder = descriptor . builder ( ) ; if ( builder instanceof BinaryReader ) { ( ( BinaryReader ) builder ) . readBinary ( input , strict ) ; } else { FieldInfo fieldInfo = readFieldInfo ( input ) ; while ( fieldInfo != null ) { PField field = descriptor . findFieldById ( fieldInfo . getId ( ) ) ; if ( field != null ) { Object value = readFieldValue ( input , fieldInfo , field . getDescriptor ( ) , strict ) ; builder . set ( field . getId ( ) , value ) ; } else { readFieldValue ( input , fieldInfo , null , false ) ; } fieldInfo = readFieldInfo ( input ) ; } if ( strict ) { try { builder . validate ( ) ; } catch ( IllegalStateException e ) { throw new SerializerException ( e , e . getMessage ( ) ) ; } } } return builder . build ( ) ; } | Read message from reader . |
19,284 | public static void consumeMessage ( BigEndianBinaryReader in ) throws IOException { FieldInfo fieldInfo ; while ( ( fieldInfo = readFieldInfo ( in ) ) != null ) { readFieldValue ( in , fieldInfo , null , false ) ; } } | Consume a message from the stream without parsing the content into a message . |
19,285 | public static < Message extends PMessage < Message , Field > , Field extends PField > int writeMessage ( BigEndianBinaryWriter writer , Message message ) throws IOException { if ( message instanceof BinaryWriter ) { return ( ( BinaryWriter ) message ) . writeBinary ( writer ) ; } int len = 0 ; if ( message instanceof PUnion ) { if ( ( ( PUnion ) message ) . unionFieldIsSet ( ) ) { PField field = ( ( PUnion ) message ) . unionField ( ) ; len += writeFieldSpec ( writer , forType ( field . getDescriptor ( ) . getType ( ) ) , field . getId ( ) ) ; len += writeFieldValue ( writer , message . get ( field . getId ( ) ) , field . getDescriptor ( ) ) ; } } else { for ( PField field : message . descriptor ( ) . getFields ( ) ) { if ( message . has ( field . getId ( ) ) ) { len += writeFieldSpec ( writer , forType ( field . getDescriptor ( ) . getType ( ) ) , field . getId ( ) ) ; len += writeFieldValue ( writer , message . get ( field . getId ( ) ) , field . getDescriptor ( ) ) ; } } } len += writer . writeUInt8 ( BinaryType . STOP ) ; return len ; } | Write message to writer . |
19,286 | protected void register ( Serializer serializer , String ... mediaTypes ) { for ( String mediaType : mediaTypes ) { this . serializerMap . put ( mediaType , serializer ) ; } } | Register the serializer with a given set of media types . |
19,287 | public String getContentLocation ( ) { String [ ] values = getMimeHeader ( "Content-Location" ) ; if ( values != null && values . length > 0 ) return values [ 0 ] ; return null ; } | Retrieves the value of the MIME header whose name is Content - Location . |
19,288 | public String readBinary ( char end ) throws IOException { int startOffset = bufferOffset ; int startLinePos = linePos ; CharArrayWriter baos = new CharArrayWriter ( ) ; while ( readNextChar ( ) ) { if ( lastChar == end ) { lastChar = 0 ; return baos . toString ( ) ; } else if ( lastChar == ' ' || lastChar == '\t' || lastChar == '\r' || lastChar == '\n' ) { throw failure ( getLineNo ( ) , startLinePos , startOffset , "Illegal char '%s' in binary" , Strings . escape ( ( char ) lastChar ) ) ; } baos . write ( lastChar ) ; } throw eof ( "Unexpected end of file in binary" ) ; } | Read the content of encoded binary . This does not parse the binary just read out from the buffer the string representing the binary data as delimited by the requested end char . |
19,289 | public static ApplicationFeatureViewModel newViewModel ( final ApplicationFeatureId featureId , final ApplicationFeatureRepositoryDefault applicationFeatureRepository , final DomainObjectContainer container ) { final Class < ? extends ApplicationFeatureViewModel > cls = viewModelClassFor ( featureId , applicationFeatureRepository ) ; if ( cls == null ) { return null ; } return container . newViewModelInstance ( cls , featureId . asEncodedString ( ) ) ; } | region > constructors |
19,290 | @ Property ( domainEvent = MemberNameDomainEvent . class ) @ PropertyLayout ( typicalLength = ApplicationFeature . TYPICAL_LENGTH_MEMBER_NAME ) @ MemberOrder ( name = "Id" , sequence = "2.4" ) public String getMemberName ( ) { return getFeatureId ( ) . getMemberName ( ) ; } | For packages and class names will be null . |
19,291 | public ApplicationFeatureViewModel getParentPackage ( ) { return Functions . asViewModelForId ( applicationFeatureRepository , container ) . apply ( getFeatureId ( ) . getParentPackageId ( ) ) ; } | The parent package feature of this class or package . |
19,292 | public ApplicationUser findByUsernameCached ( final String username ) { return queryResultsCache . execute ( new Callable < ApplicationUser > ( ) { public ApplicationUser call ( ) throws Exception { return findByUsername ( username ) ; } } , ApplicationUserRepository . class , "findByUsernameCached" , username ) ; } | region > findByUsername |
19,293 | public List < ApplicationUser > findByAtPath ( final String atPath ) { return container . allMatches ( new QueryDefault < > ( ApplicationUser . class , "findByAtPath" , "atPath" , atPath ) ) ; } | region > allUsers |
19,294 | @ SuppressWarnings ( "unchecked" ) private static < V > V resolve ( ProvidenceConfigContext context , Token token , Tokenizer tokenizer , PDescriptor descriptor ) throws TokenizerException { Object value = resolveAny ( context , token , tokenizer ) ; if ( value == null ) { return null ; } return ( V ) asType ( descriptor , value ) ; } | Resolve a value reference . |
19,295 | public static ClassLoader getContextClassLoader ( Class < ? > contextClass ) { return Objects . firstNonNull ( Thread . currentThread ( ) . getContextClassLoader ( ) , contextClass . getClassLoader ( ) ) ; } | Returns current thread context class loader or context class s class loader |
19,296 | public static String buildPath ( String first , String ... parts ) { StringBuilder result = new StringBuilder ( first ) ; for ( String part : parts ) { if ( result . length ( ) == 0 ) { if ( part . startsWith ( "/" ) ) { result . append ( part . substring ( 1 ) ) ; } else { result . append ( part ) ; } } else { if ( result . toString ( ) . endsWith ( "/" ) && part . startsWith ( "/" ) ) { result . append ( part . substring ( 1 ) ) ; } else if ( ! result . toString ( ) . endsWith ( "/" ) && ! part . startsWith ( "/" ) && ! part . isEmpty ( ) ) { result . append ( "/" ) . append ( part ) ; } else { result . append ( part ) ; } } } return result . toString ( ) ; } | Concatenate path parts into a full path taking care of extra or missing slashes . |
19,297 | private TokenType lexUtf8Char ( Bytes jsonText , int curChar ) { if ( curChar <= 0x7f ) { return STRING ; } else if ( ( curChar >> 5 ) == 0x6 ) { if ( jsonText . readRemaining ( ) == 0 ) return EOF ; curChar = readChar ( jsonText ) ; if ( ( curChar >> 6 ) == 0x2 ) return STRING ; } else if ( ( curChar >> 4 ) == 0x0e ) { if ( jsonText . readRemaining ( ) == 0 ) return EOF ; curChar = readChar ( jsonText ) ; if ( ( curChar >> 6 ) == 0x2 ) { if ( jsonText . readRemaining ( ) == 0 ) return EOF ; curChar = readChar ( jsonText ) ; if ( ( curChar >> 6 ) == 0x2 ) return STRING ; } } else if ( ( curChar >> 3 ) == 0x1e ) { if ( jsonText . readRemaining ( ) == 0 ) return EOF ; curChar = readChar ( jsonText ) ; if ( ( curChar >> 6 ) == 0x2 ) { if ( jsonText . readRemaining ( ) == 0 ) return EOF ; curChar = readChar ( jsonText ) ; if ( ( curChar >> 6 ) == 0x2 ) { if ( jsonText . readRemaining ( ) == 0 ) return EOF ; curChar = readChar ( jsonText ) ; if ( ( curChar >> 6 ) == 0x2 ) return STRING ; } } } return ERROR ; } | process a variable length utf8 encoded codepoint . |
19,298 | private TokenType lexString ( Bytes jsonText ) { TokenType tok = ERROR ; boolean hasEscapes = false ; finish_string_lex : for ( ; ; ) { int curChar ; { if ( bufInUse && buf . readRemaining ( ) > 0 ) { stringScan ( buf ) ; } else if ( jsonText . readRemaining ( ) > 0 ) { stringScan ( jsonText ) ; } } if ( jsonText . readRemaining ( ) == 0 ) { tok = EOF ; break ; } curChar = readChar ( jsonText ) ; if ( curChar == '"' ) { tok = STRING ; break ; } else if ( curChar == '\\' ) { hasEscapes = true ; if ( jsonText . readRemaining ( ) == 0 ) { tok = EOF ; break ; } curChar = readChar ( jsonText ) ; if ( curChar == 'u' ) { for ( int i = 0 ; i < 4 ; i ++ ) { if ( jsonText . readRemaining ( ) == 0 ) { tok = EOF ; break finish_string_lex ; } curChar = readChar ( jsonText ) ; if ( ( CHAR_LOOKUP_TABLE [ curChar ] & VHC ) == 0 ) { unreadChar ( jsonText ) ; error = STRING_INVALID_HEX_CHAR ; break finish_string_lex ; } } } else if ( ( CHAR_LOOKUP_TABLE [ curChar ] & VEC ) == 0 ) { unreadChar ( jsonText ) ; error = STRING_INVALID_ESCAPED_CHAR ; break ; } } else if ( ( CHAR_LOOKUP_TABLE [ curChar ] & IJC ) != 0 ) { unreadChar ( jsonText ) ; error = STRING_INVALID_JSON_CHAR ; break ; } else if ( validateUTF8 ) { TokenType t = lexUtf8Char ( jsonText , curChar ) ; if ( t == EOF ) { tok = EOF ; break ; } else if ( t == ERROR ) { error = STRING_INVALID_UTF8 ; break ; } } } if ( hasEscapes && tok == STRING ) { tok = STRING_WITH_ESCAPES ; } return tok ; } | Lex a string . |
19,299 | public static < T > Predicate < T > nor ( Predicate < ? super T > first , Predicate < ? super T > second ) { return com . google . common . base . Predicates . not ( com . google . common . base . Predicates . or ( first , second ) ) ; } | NOT OR Predicate |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.