idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
142,600
public Stream < LsSurvey > getSurveys ( ) throws LimesurveyRCException { JsonElement result = callRC ( new LsApiBody ( "list_surveys" , getParamsWithKey ( ) ) ) ; List < LsSurvey > surveys = gson . fromJson ( result , new TypeToken < List < LsSurvey > > ( ) { } . getType ( ) ) ; return surveys . stream ( ) ; }
Gets all surveys .
104
5
142,601
public LsSurveyLanguage getSurveyLanguageProperties ( int surveyId ) throws LimesurveyRCException { LsApiBody . LsApiParams params = getParamsWithKey ( surveyId ) ; List < String > localeSettings = new ArrayList <> ( ) ; localeSettings . add ( "surveyls_welcometext" ) ; localeSettings . add ( "surveyls_endtext" ) ; params . setSurveyLocaleSettings ( localeSettings ) ; LsSurveyLanguage surveyLanguage = gson . fromJson ( callRC ( new LsApiBody ( "get_language_properties" , params ) ) , LsSurveyLanguage . class ) ; surveyLanguage . setId ( surveyId ) ; return surveyLanguage ; }
Gets language properties from a survey .
173
8
142,602
public String getSessionKey ( ) throws LimesurveyRCException { // Use the saved key if isn't expired if ( ! key . isEmpty ( ) && ZonedDateTime . now ( ) . isBefore ( keyExpiration ) ) { return key ; } // Get session key and save it with an expiration set to 1 minute before the expiration date LsApiBody . LsApiParams params = new LsApiBody . LsApiParams ( ) ; params . setUsername ( user ) ; params . setPassword ( password ) ; JsonElement result = callRC ( new LsApiBody ( "get_session_key" , params ) ) ; key = result . getAsString ( ) ; keyExpiration = ZonedDateTime . now ( ) . plusSeconds ( keyTimeout - 60 ) ; return key ; }
Gets the current session key .
185
7
142,603
public Map < String , String > getParticipantProperties ( int surveyId , String token , List < String > tokenProperties ) throws LimesurveyRCException { LsApiBody . LsApiParams params = getParamsWithKey ( surveyId ) ; Map < String , String > queryProperties = new HashMap <> ( ) ; queryProperties . put ( "token" , token ) ; params . setTokenQueryProperties ( queryProperties ) ; params . setTokenProperties ( tokenProperties ) ; return gson . fromJson ( callRC ( new LsApiBody ( "get_participant_properties" , params ) ) , new TypeToken < Map < String , String > > ( ) { } . getType ( ) ) ; }
Gets participant properties .
170
5
142,604
public Stream < LsParticipant > getAllParticipants ( int surveyId ) throws LimesurveyRCException { LsApiBody . LsApiParams params = getParamsWithKey ( surveyId ) ; params . setStart ( 0 ) ; params . setLimit ( - 1 ) ; List < LsParticipant > participants = gson . fromJson ( callRC ( new LsApiBody ( "list_participants" , params ) ) , new TypeToken < List < LsParticipant > > ( ) { } . getType ( ) ) ; return participants . stream ( ) ; }
Gets all participants from a survey .
134
8
142,605
public static SharedPreferenceUtils initWith ( SharedPreferences sharedPreferences ) { if ( sharedPreferenceUtils == null ) { sharedPreferenceUtils = new SharedPreferenceUtils ( ) ; } sharedPreferenceUtils . sharedPreferences = sharedPreferences ; return sharedPreferenceUtils ; }
Init SharedPreferenceUtils with SharedPreferences file
67
11
142,606
public static SharedPreferenceUtils initWith ( Context context , String name ) { if ( sharedPreferenceUtils == null ) { sharedPreferenceUtils = new SharedPreferenceUtils ( ) ; } if ( isEmptyString ( name ) ) { sharedPreferenceUtils . sharedPreferences = PreferenceManager . getDefaultSharedPreferences ( context ) ; } else { sharedPreferenceUtils . sharedPreferences = context . getSharedPreferences ( name , Context . MODE_PRIVATE ) ; } return sharedPreferenceUtils ; }
Init SharedPreferences with context and a SharedPreferences name
120
12
142,607
public static int getNumber ( CharSequence string ) { int number = 0 ; if ( ! isEmptyString ( string ) ) { if ( TextUtils . isDigitsOnly ( string ) ) { number = Integer . parseInt ( string . toString ( ) ) ; } } return number ; }
Extract number from string failsafe . If the string is not a proper number it will always return 0 ;
64
22
142,608
public static float getNumberFloat ( CharSequence string ) { float number = 0.0f ; try { if ( ! isEmptyString ( string ) ) { number = Float . parseFloat ( string . toString ( ) ) ; } } catch ( NumberFormatException e ) { e . printStackTrace ( ) ; } return number ; }
Extract number from string failsafe . If the string is not a proper number it will always return 0 . 0f ;
73
25
142,609
public static long getNumberLong ( CharSequence string ) { long number = 0l ; try { if ( ! isEmptyString ( string ) ) { if ( TextUtils . isDigitsOnly ( string ) ) { number = Long . parseLong ( string . toString ( ) ) ; } } } catch ( NumberFormatException e ) { e . printStackTrace ( ) ; } return number ; }
Extract number from string failsafe . If the string is not a proper number it will always return 0l ;
87
23
142,610
public void inflateDebugMenu ( MenuInflater inflater , Menu menu ) { inflater . inflate ( R . menu . debug , menu ) ; }
Inflate menu item for debug .
34
8
142,611
public boolean isDebugHandled ( Context context , MenuItem item ) { int id = item . getItemId ( ) ; if ( id == R . id . action_debug ) { startActivity ( context ) ; return true ; } return false ; }
Checks if debug menu item clicked or not .
53
10
142,612
public boolean isValueExistForKey ( String key ) { boolean isValueExists ; try { String string = getString ( key , "" ) ; isValueExists = ! string . equalsIgnoreCase ( "" ) ; } catch ( ClassCastException e ) { try { int anInt = getInt ( key , 0 ) ; isValueExists = anInt != 0 ; } catch ( ClassCastException e1 ) { try { long aLong = getLong ( key , 0 ) ; isValueExists = aLong != 0 ; } catch ( ClassCastException e2 ) { try { float aFloat = getFloat ( key , 0f ) ; isValueExists = aFloat != 0 ; } catch ( ClassCastException e3 ) { try { boolean aBoolean = getBoolean ( key , false ) ; isValueExists = ! aBoolean ; } catch ( Exception e4 ) { isValueExists = false ; e . printStackTrace ( ) ; } } } } } catch ( Exception e ) { isValueExists = false ; } return isValueExists ; }
Check if value exists for key .
236
7
142,613
public String getString ( String key , String defaultValue ) throws ClassCastException { return sharedPreferences . getString ( key , ( defaultValue == null ) ? "" : defaultValue ) ; }
Retrieve a String value from the preferences .
41
9
142,614
public void restoreKey ( String key ) { if ( ! key . equalsIgnoreCase ( "test_mode_opened" ) ) { String originalKey = key . substring ( keyTestMode . length ( ) ) ; Object value = get ( key ) ; put ( originalKey , value ) ; clear ( key ) ; } }
Restore the original value for the key after it has been changed in test mode .
70
17
142,615
public Object get ( String key ) { try { return getString ( key , null ) ; } catch ( ClassCastException e ) { try { return getInt ( key , 0 ) ; } catch ( ClassCastException e1 ) { try { return getLong ( key , 0 ) ; } catch ( ClassCastException e2 ) { try { return getFloat ( key , 0f ) ; } catch ( ClassCastException e3 ) { try { return getBoolean ( key , false ) ; } catch ( Exception e4 ) { e . printStackTrace ( ) ; } } } } } return null ; }
Get the value of the key .
130
7
142,616
public void put ( String key , Object value ) { if ( value . getClass ( ) . equals ( String . class ) ) { putString ( key , value . toString ( ) ) ; } else if ( value . getClass ( ) . equals ( Integer . class ) ) { putInt ( key , ( Integer ) value ) ; } else if ( value . getClass ( ) . equals ( Float . class ) ) { putFloat ( key , ( Float ) value ) ; } else if ( value . getClass ( ) . equals ( Long . class ) ) { putLong ( key , ( Long ) value ) ; } else if ( value . getClass ( ) . equals ( Boolean . class ) ) { putBoolean ( key , ( Boolean ) value ) ; } else { putString ( key , value . toString ( ) ) ; } }
Put the value in given shared preference
180
7
142,617
public void putString ( String key , String value ) { sharedPreferences . edit ( ) . putString ( key , value ) . commit ( ) ; }
put the string value to shared preference
33
7
142,618
public void putFloat ( String key , float value ) { sharedPreferences . edit ( ) . putFloat ( key , value ) . commit ( ) ; }
put the float value to shared preference
33
7
142,619
@ Override public final EventData convert ( final CommonEvent commonEvent ) { // User's data 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 ) ; } // EscMeta 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 ) ; // Create event data 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 .
425
9
142,620
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 .
47
8
142,621
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 .
58
5
142,622
@ 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 ( ) { @ Override 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 .
201
26
142,623
public RestClientResponse execute ( AsyncHttpClient . BoundRequestBuilder requestBuilder ) throws RestClientException { Response response ; try { ListenableFuture < Response > futureResponse = requestBuilder . execute ( ) ; response = futureResponse . get ( ) ; if ( log . isDebugEnabled ( ) ) { // the if is here so that we don't call the getResponseBody() when we're not going to print it 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 .
206
16
142,624
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 .
72
6
142,625
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
147
11
142,626
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 ) { // ignore } 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
156
14
142,627
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
60
8
142,628
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 .
54
15
142,629
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 .
54
24
142,630
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 .
131
10
142,631
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
71
16
142,632
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
71
18
142,633
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 .
96
14
142,634
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 .
75
14
142,635
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 .
91
14
142,636
public Query getOptimizedQuery ( ) { // if (isOptimizable()) { // return _baseQuery; // } // create a copy/clone of the original query 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 .
202
6
142,637
@ Override 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
206
17
142,638
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 .
71
4
142,639
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 .
155
5
142,640
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 .
54
8
142,641
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 .
675
5
142,642
@ Beta 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 .
178
15
142,643
@ Beta 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
62
13
142,644
@ Beta 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 > ( ) ; //noinspection ConstantConditions for ( Map . Entry < K , V > entry : first . entrySet ( ) ) { if ( entry . getKey ( ) == null ) { continue ; } map . put ( entry . getKey ( ) , entry . getValue ( ) == null ? defaultValue : entry . getValue ( ) ) ; } //noinspection ConstantConditions 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
268
12
142,645
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 .
82
18
142,646
@ 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 .
101
19
142,647
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 .
58
11
142,648
@ 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 .
75
10
142,649
static boolean isSupported ( int index ) { if ( ( index <= 0 ) || ( index >= NAMED_CURVE_OID_TABLE . length ) ) { return false ; } if ( fips == false ) { // in non-FIPS mode, we support all valid indices return true ; } return DEFAULT . contains ( index ) ; }
Test whether we support the curve with the given index .
76
11
142,650
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 .
52
9
142,651
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 .
40
10
142,652
public static < F extends PField > MappedField < F > withColumn ( String name , F field ) { return new MappedField <> ( name , field ) ; }
With column mapped to field .
38
6
142,653
@ Override 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 .
82
20
142,654
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 ) { // Ignored... TODO: At least log? } } } ) ; }
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 .
184
30
142,655
private List < AgigaTypedDependency > parseDependencies ( VTDNav vn , DependencyForm form ) throws NavException , PilotException { require ( vn . matchElement ( AgigaConstants . SENTENCE ) ) ; // Move to the <basic-deps> tag require ( vn . toElement ( VTDNav . FC , form . getXmlTag ( ) ) ) ; List < AgigaTypedDependency > agigaDeps = new ArrayList < AgigaTypedDependency > ( ) ; // Loop through the dep tags AutoPilot basicDepRelAp = new AutoPilot ( vn ) ; basicDepRelAp . selectElement ( AgigaConstants . DEP ) ; while ( basicDepRelAp . iterate ( ) ) { // Read the type, governor, and dependent 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-->%d" , type , governorId , dependentId ) ) ; // Subtract one, since the tokens are one-indexed in the XML but // zero-indexed in this API AgigaTypedDependency agigaDep = new AgigaTypedDependency ( type , governorId - 1 , dependentId - 1 ) ; agigaDeps . add ( agigaDep ) ; } return agigaDeps ; }
Assumes the position of vn is at a sent tag
412
12
142,656
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 .
136
7
142,657
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 .
106
8
142,658
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
77
3
142,659
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 .
38
35
142,660
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" ) ; } // temporary protocol version until the actual protocol version // is negotiated in the Hello exchange. This affects the record // version we sent with the ClientHello. if ( ! isInitialHandshake ) { protocolVersion = activeProtocolVersion ; } else { protocolVersion = activeProtocols . max ; } if ( helloVersion == null || helloVersion . v == ProtocolVersion . NONE . v ) { helloVersion = activeProtocols . helloVersion ; } // We accumulate digests of the handshake messages so that // we can read/write CertificateVerify and Finished messages, // getting assurance against some particular active attacks. Set < String > localSupportedHashAlgorithms = SignatureAndHashAlgorithm . getHashAlgorithmNames ( getLocalSupportedSignAlgs ( ) ) ; handshakeHash = new HandshakeHash ( ! isClient , needCertVerify , localSupportedHashAlgorithms ) ; // Generate handshake input/output stream. 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 ) ; } // move state to activated state = - 1 ; }
Prior to handshaking activate the handshake and initialize the version input stream and output stream .
526
18
142,661
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 .
62
23
142,662
boolean isNegotiable ( ProtocolVersion protocolVersion ) { if ( activeProtocols == null ) { activeProtocols = getActiveProtocols ( ) ; } return activeProtocols . contains ( protocolVersion ) ; }
Check if the given protocol version is enabled and available .
50
11
142,663
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 .
54
19
142,664
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 .
301
6
142,665
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 .
141
11
142,666
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 .
99
11
142,667
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 .
48
32
142,668
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 .
31
18
142,669
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 .
355
41
142,670
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 .
94
8
142,671
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 .
136
8
142,672
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 { // Referenced files are referenced from the real file, // not from symlink location, in case of sym-linked files. // this way include references are always consistent, but // files can be referenced via symlinks if needed. 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 .
306
10
142,673
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 ; //noinspection StatementWithEmptyBody while ( ! isPortAvailable ( nextPort ++ ) ) { /* Empty */ } return nextPort ; }
Returns a currently available port number in the specified range .
113
11
142,674
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 ) ) { // If the code makes it this far without an exception it means // something is using the port and has responded. 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
172
13
142,675
@ Nonnull 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 .
51
20
142,676
@ Nonnull 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 .
52
14
142,677
public static < T extends Enum < T > & RichEnum < T > > RichEnumConstants < T > richConstants ( Class < T > theClass ) { return new RichEnumConstants <> ( theClass ) ; }
The factory method
53
3
142,678
@ JsonAnySetter public void putConfigurationValue ( String key , Object value ) { this . configuration . put ( key , value ) ; }
Put a value in the module configuration map .
31
9
142,679
@ javax . annotation . Nonnull public java . util . Optional < String > optionalFilePath ( ) { return java . util . Optional . ofNullable ( mFilePath ) ; }
Full absolute path to the file .
41
7
142,680
@ javax . annotation . Nonnull public java . util . Optional < java . util . List < String > > optionalFileLines ( ) { return java . util . Optional . ofNullable ( mFileLines ) ; }
The lines of the program file
50
6
142,681
@ javax . annotation . Nonnull public java . util . Optional < net . morimekta . providence . model . ProgramType > optionalProgram ( ) { return java . util . Optional . ofNullable ( mProgram ) ; }
The program type definition
52
4
142,682
@ Nonnull 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 .
46
24
142,683
public boolean containsProgramPath ( String path ) { return registryMap . containsKey ( path ) && registryMap . get ( path ) . getProgram ( ) != null ; }
Gets the document for a given file path .
36
10
142,684
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 .
156
20
142,685
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 .
59
41
142,686
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
33
12
142,687
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 .
58
21
142,688
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 ; } // For ECC certs, check whether we support the EC domain parameters. // If the client sent a SupportedEllipticCurves ClientHello extension, // check against that too. 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 .
427
21
142,689
private boolean setupKerberosKeys ( ) { if ( kerberosKeys != null ) { return true ; } try { final AccessControlContext acc = getAccSE ( ) ; kerberosKeys = AccessController . doPrivileged ( // Eliminate dependency on KerberosKey new PrivilegedExceptionAction < SecretKey [ ] > ( ) { public SecretKey [ ] run ( ) throws Exception { // get kerberos key for the default principal return Krb5Helper . getServerKeys ( acc ) ; } } ) ; // check permission to access and use the secret key of the // Kerberized "host" service 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 ) { // Eliminate dependency on ServicePermission sm . checkPermission ( Krb5Helper . getServicePermission ( serverPrincipal , "accept" ) , acc ) ; } } catch ( SecurityException se ) { kerberosKeys = null ; // %%% destroy keys? or will that affect Subject? 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 ) { // Likely exception here is LoginExceptin 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 .
443
19
142,690
@ Programmatic public boolean implies ( final ApplicationFeatureId featureId , final ApplicationPermissionMode mode ) { if ( getRule ( ) != ApplicationPermissionRule . ALLOW ) { // only allow rules can imply return false ; } if ( getMode ( ) == ApplicationPermissionMode . VIEWING && mode == ApplicationPermissionMode . CHANGING ) { // an "allow viewing" permission does not imply ability to change return false ; } // determine if this permission is on the path (ie the feature or one of its parents) return onPathOf ( featureId ) ; }
region > implies refutes
121
5
142,691
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 .
115
5
142,692
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 .
173
5
142,693
public String createMessageData ( String message ) { messageStringBuffer . delete ( 0 , messageStringBuffer . length ( ) ) ; // Create the PRI part messageStringBuffer . append ( ' ' ) ; int priority = facility * 8 + severity ; messageStringBuffer . append ( priority ) ; messageStringBuffer . append ( ' ' ) ; // Create the HEADER part. if ( header ) { // Add the TIMESTAMP field of the HEADER // Time format is "Mmm dd hh:mm:ss". For more info see rfc3164. 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 ( ' ' ) ; } messageStringBuffer . append ( dayOfMonth ) ; messageStringBuffer . append ( ' ' ) ; int hour = calendar . get ( Calendar . HOUR_OF_DAY ) ; if ( hour < SyslogMessage . TEN ) { messageStringBuffer . append ( ' ' ) ; } messageStringBuffer . append ( hour ) ; messageStringBuffer . append ( ' ' ) ; int minute = calendar . get ( Calendar . MINUTE ) ; if ( minute < SyslogMessage . TEN ) { messageStringBuffer . append ( ' ' ) ; } messageStringBuffer . append ( minute ) ; messageStringBuffer . append ( ' ' ) ; int second = calendar . get ( Calendar . SECOND ) ; if ( second < SyslogMessage . TEN ) { messageStringBuffer . append ( ' ' ) ; } messageStringBuffer . append ( second ) ; messageStringBuffer . append ( ' ' ) ; // Add the HOSTNAME part of the message messageStringBuffer . append ( hostname ) ; } // Create the MSG part. 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 .
496
15
142,694
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 .
74
10
142,695
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 .
70
11
142,696
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 .
77
27
142,697
public static Properties getFileAsProperties ( String path ) { File file = new File ( nullToEmpty ( path ) ) ; return getFileAsProperties ( file ) ; }
Loads properties from file path
38
6
142,698
@ javax . annotation . Nonnull public java . util . Optional < net . morimekta . util . Binary > optionalData ( ) { return java . util . Optional . ofNullable ( mData ) ; }
The actual content binary data .
48
6
142,699
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 .
125
8