idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
6,600
public RequestBuilder < T , ID > setParameter ( String name , String value ) { parameters . set ( name , value ) ; return this ; }
Set a parameter on the request . Replaces any existing values for the name .
6,601
public RequestBuilder < T , ID > addHeader ( String name , String value ) { headers . add ( name , value ) ; return this ; }
Add a header to the request . Adds this value to any existing values for this name .
6,602
public Request < T > build ( ) { MultiMap headers = resolveHeaders ( ) ; MultiMap parameters = resolveParameters ( ) ; parameters . add ( "version" , Integer . toString ( version ) ) ; Request < T > request = new Request < T > ( ) ; request . setEntityName ( entityName ) ; request . setEntityType ( objectType ) ; request . setHeaders ( headers ) ; request . setParameters ( parameters ) ; return request ; }
Build the request
6,603
protected MultiMap resolveHeaders ( ) { MultiMap resolved = null ; if ( headerFactory != null ) resolved = headerFactory . getHeaders ( ) ; if ( resolved != null ) resolved = resolved . merge ( headers ) ; else resolved = headers ; return resolved ; }
Combine any locally defined headers with any headers from the header factory
6,604
protected MultiMap resolveParameters ( ) { MultiMap resolved = null ; if ( parameterFactory != null ) resolved = parameterFactory . getParameters ( ) ; if ( resolved != null ) resolved = resolved . merge ( parameters ) ; else resolved = parameters ; return resolved ; }
Combine any locally defined parameters with any parameters from the parameter factory
6,605
private void classify ( ) { monitor . taskStarted ( "Classifying" ) ; monitor . taskBusy ( ) ; reasoner = reasoner . classify ( ) ; monitor . taskEnded ( ) ; monitor . taskStarted ( "Building taxonomy" ) ; monitor . taskBusy ( ) ; taxonomy = reasoner . getClassifiedOntology ( ) ; monitor . taskEnded ( ) ; }
Performs a full classification on the current ontology .
6,606
public void flush ( ) { if ( rawChanges . isEmpty ( ) || ! buffering ) { return ; } boolean hasRemoveAxiom = false ; List < OWLAxiom > newAxioms = new ArrayList < OWLAxiom > ( ) ; for ( OWLOntologyChange change : rawChanges ) { OWLAxiom axiom = change . getAxiom ( ) ; if ( axiom instanceof RemoveAxiom ) { hasRemoveAxiom = true ; break ; } newAxioms . add ( axiom ) ; } if ( hasRemoveAxiom ) { rawChanges . clear ( ) ; classify ( ) ; return ; } Set < Axiom > canAxioms = getAxioms ( newAxioms ) ; monitor . taskStarted ( "Classifying incrementally" ) ; monitor . taskBusy ( ) ; reasoner . loadAxioms ( canAxioms ) ; reasoner = reasoner . classify ( ) ; monitor . taskEnded ( ) ; monitor . taskStarted ( "Calculating taxonomy incrementally" ) ; monitor . taskBusy ( ) ; taxonomy = reasoner . getClassifiedOntology ( ) ; monitor . taskEnded ( ) ; rawChanges . clear ( ) ; }
Classifies the ontology incrementally if no import changes have occurred .
6,607
public boolean isPrecomputed ( InferenceType inferenceType ) { if ( inferenceType . equals ( InferenceType . CLASS_HIERARCHY ) ) { return reasoner . isClassified ( ) ; } else { return false ; } }
Determines if a specific set of inferences have been precomputed .
6,608
public boolean isSatisfiable ( OWLClassExpression classExpression ) throws ReasonerInterruptedException , TimeOutException , ClassExpressionNotInProfileException , FreshEntitiesException , InconsistentOntologyException { if ( classExpression . isAnonymous ( ) ) { return false ; } else { Object id = getId ( classExpression . asOWLClass ( ) ) ; au . csiro . ontology . Node bottom = getTaxonomy ( ) . getBottomNode ( ) ; return ! bottom . getEquivalentConcepts ( ) . contains ( id ) ; } }
A convenience method that determines if the specified class expression is satisfiable with respect to the reasoner axioms .
6,609
public Node < OWLClass > getUnsatisfiableClasses ( ) throws ReasonerInterruptedException , TimeOutException , InconsistentOntologyException { return nodeToOwlClassNode ( getTaxonomy ( ) . getBottomNode ( ) ) ; }
A convenience method that obtains the classes in the signature of the root ontology that are unsatisfiable .
6,610
public boolean isEntailed ( Set < ? extends OWLAxiom > axioms ) throws ReasonerInterruptedException , UnsupportedEntailmentTypeException , TimeOutException , AxiomNotInProfileException , FreshEntitiesException , InconsistentOntologyException { throw new UnsupportedEntailmentTypeException ( axioms . iterator ( ) . next ( ) ) ; }
Determines if the specified set of axioms is entailed by the reasoner axioms .
6,611
public Set < OWLLiteral > getDataPropertyValues ( OWLNamedIndividual ind , OWLDataProperty pe ) throws InconsistentOntologyException , FreshEntitiesException , ReasonerInterruptedException , TimeOutException { return Collections . emptySet ( ) ; }
Gets the data property values for the specified individual and data property expression . The values are a set of literals . Note that the results are not guaranteed to be complete for this method . The reasoner may also return canonical literals or they may be in a form that bears a resemblance to the syntax of the literals in the root ontology imports closure .
6,612
public Node < OWLNamedIndividual > getSameIndividuals ( OWLNamedIndividual ind ) throws InconsistentOntologyException , FreshEntitiesException , ReasonerInterruptedException , TimeOutException { throw new ReasonerInternalException ( "getSameIndividuals not implemented" ) ; }
Gets the individuals that are the same as the specified individual .
6,613
public static boolean methodBelongsTo ( Method m , Method [ ] methods ) { boolean result = false ; for ( int i = 0 ; i < methods . length && ! result ; i ++ ) { if ( methodEquals ( methods [ i ] , m ) ) { result = true ; } } return result ; }
Returns true if the method is in the method array .
6,614
public static boolean methodEquals ( Method method , Method other ) { if ( ( method . getDeclaringClass ( ) . equals ( other . getDeclaringClass ( ) ) ) && ( method . getName ( ) . equals ( other . getName ( ) ) ) ) { if ( ! method . getReturnType ( ) . equals ( other . getReturnType ( ) ) ) return false ; Class < ? > [ ] params1 = method . getParameterTypes ( ) ; Class < ? > [ ] params2 = other . getParameterTypes ( ) ; if ( params1 . length == params2 . length ) { for ( int i = 0 ; i < params1 . length ; i ++ ) { if ( params1 [ i ] != params2 [ i ] ) return false ; } return true ; } } return false ; }
Checks if the 2 methods are equals .
6,615
@ SuppressWarnings ( "unchecked" ) private void fixupMin ( int k ) { K key = array [ k ] ; int gp = k / 4 ; while ( gp > 0 && ( ( Comparable < ? super K > ) array [ gp ] ) . compareTo ( key ) > 0 ) { array [ k ] = array [ gp ] ; k = gp ; gp = k / 4 ; } array [ k ] = key ; }
Upwards fix starting from a particular element at a minimum level
6,616
private void fixupMinWithComparator ( int k ) { K key = array [ k ] ; int gp = k / 4 ; while ( gp > 0 && comparator . compare ( array [ gp ] , key ) > 0 ) { array [ k ] = array [ gp ] ; k = gp ; gp = k / 4 ; } array [ k ] = key ; }
Upwards fix starting from a particular element at a minimum level . Performs comparisons using the comparator .
6,617
private void fixupMaxWithComparator ( int k ) { K key = array [ k ] ; int gp = k / 4 ; while ( gp > 0 && comparator . compare ( array [ gp ] , key ) < 0 ) { array [ k ] = array [ gp ] ; k = gp ; gp = k / 4 ; } array [ k ] = key ; }
Upwards fix starting from a particular element at a maximum level . Performs comparisons using the comparator .
6,618
@ SuppressWarnings ( "unchecked" ) private void fixdownMin ( int k ) { int c = 2 * k ; while ( c <= size ) { int m = minChildOrGrandchild ( k ) ; if ( m > c + 1 ) { if ( ( ( Comparable < ? super K > ) array [ m ] ) . compareTo ( array [ k ] ) >= 0 ) { break ; } K tmp = array [ k ] ; array [ k ] = array [ m ] ; array [ m ] = tmp ; if ( ( ( Comparable < ? super K > ) array [ m ] ) . compareTo ( array [ m / 2 ] ) > 0 ) { tmp = array [ m ] ; array [ m ] = array [ m / 2 ] ; array [ m / 2 ] = tmp ; } k = m ; c = 2 * k ; } else { if ( ( ( Comparable < ? super K > ) array [ m ] ) . compareTo ( array [ k ] ) < 0 ) { K tmp = array [ k ] ; array [ k ] = array [ m ] ; array [ m ] = tmp ; } break ; } } }
Downwards fix starting from a particular element at a minimum level .
6,619
private void fixdownMinWithComparator ( int k ) { int c = 2 * k ; while ( c <= size ) { int m = minChildOrGrandchildWithComparator ( k ) ; if ( m > c + 1 ) { if ( comparator . compare ( array [ m ] , array [ k ] ) >= 0 ) { break ; } K tmp = array [ k ] ; array [ k ] = array [ m ] ; array [ m ] = tmp ; if ( comparator . compare ( array [ m ] , array [ m / 2 ] ) > 0 ) { tmp = array [ m ] ; array [ m ] = array [ m / 2 ] ; array [ m / 2 ] = tmp ; } k = m ; c = 2 * k ; } else { if ( comparator . compare ( array [ m ] , array [ k ] ) < 0 ) { K tmp = array [ k ] ; array [ k ] = array [ m ] ; array [ m ] = tmp ; } break ; } } }
Downwards fix starting from a particular element at a minimum level . Performs comparisons using the comparator .
6,620
@ SuppressWarnings ( "unchecked" ) private void fixdownMax ( int k ) { int c = 2 * k ; while ( c <= size ) { int m = maxChildOrGrandchild ( k ) ; if ( m > c + 1 ) { if ( ( ( Comparable < ? super K > ) array [ m ] ) . compareTo ( array [ k ] ) <= 0 ) { break ; } K tmp = array [ k ] ; array [ k ] = array [ m ] ; array [ m ] = tmp ; if ( ( ( Comparable < ? super K > ) array [ m ] ) . compareTo ( array [ m / 2 ] ) < 0 ) { tmp = array [ m ] ; array [ m ] = array [ m / 2 ] ; array [ m / 2 ] = tmp ; } k = m ; c = 2 * k ; } else { if ( ( ( Comparable < ? super K > ) array [ m ] ) . compareTo ( array [ k ] ) > 0 ) { K tmp = array [ k ] ; array [ k ] = array [ m ] ; array [ m ] = tmp ; } break ; } } }
Downwards fix starting from a particular element at a maximum level .
6,621
private void fixdownMaxWithComparator ( int k ) { int c = 2 * k ; while ( c <= size ) { int m = maxChildOrGrandchildWithComparator ( k ) ; if ( m > c + 1 ) { if ( comparator . compare ( array [ m ] , array [ k ] ) <= 0 ) { break ; } K tmp = array [ k ] ; array [ k ] = array [ m ] ; array [ m ] = tmp ; if ( comparator . compare ( array [ m ] , array [ m / 2 ] ) < 0 ) { tmp = array [ m ] ; array [ m ] = array [ m / 2 ] ; array [ m / 2 ] = tmp ; } k = m ; c = 2 * k ; } else { if ( comparator . compare ( array [ m ] , array [ k ] ) > 0 ) { K tmp = array [ k ] ; array [ k ] = array [ m ] ; array [ m ] = tmp ; } break ; } } }
Downwards fix starting from a particular element at a maximum level . Performs comparisons using the comparator .
6,622
public NetworkConnectionType getCurrentConnectionType ( ) { NetworkInfo activeNetworkInfo = getActiveNetworkInfo ( ) ; if ( activeNetworkInfo == null || ! isInternetAccessAvailable ( ) ) { return NetworkConnectionType . NO_CONNECTION ; } switch ( activeNetworkInfo . getType ( ) ) { case ConnectivityManager . TYPE_WIFI : return NetworkConnectionType . WIFI ; case ConnectivityManager . TYPE_MOBILE : return NetworkConnectionType . MOBILE ; case ConnectivityManager . TYPE_WIMAX : return NetworkConnectionType . WIMAX ; case ConnectivityManager . TYPE_ETHERNET : return NetworkConnectionType . ETHERNET ; default : return NetworkConnectionType . NO_CONNECTION ; } }
Get the type of network connection that the device is currently using to connect to the internet .
6,623
protected NetworkInfo getActiveNetworkInfo ( ) { ConnectivityManager connectivityManager = ( ConnectivityManager ) context . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; return connectivityManager . getActiveNetworkInfo ( ) ; }
Retrieves information on the current type of network connection that the device is using
6,624
public Stats runBechmarkRF1 ( ) { Stats res = new Stats ( ) ; String version = "20110731" ; System . out . println ( "Classifying ontology" ) ; long start = System . currentTimeMillis ( ) ; IFactory factory = new CoreFactory ( ) ; NormalisedOntology no = new NormalisedOntology ( factory ) ; System . out . println ( "Importing axioms" ) ; RF1Importer imp = new RF1Importer ( this . getClass ( ) . getResourceAsStream ( "/sct1_Concepts_Core_INT_20110731.txt" ) , this . getClass ( ) . getResourceAsStream ( "/res1_StatedRelationships_Core_INT_20110731.txt" ) , version ) ; Iterator < Ontology > it = imp . getOntologyVersions ( new NullProgressMonitor ( ) ) ; Ontology ont = null ; while ( it . hasNext ( ) ) { Ontology o = it . next ( ) ; if ( o . getVersion ( ) . equals ( "snomed" ) ) { ont = o ; break ; } } if ( ont == null ) { throw new RuntimeException ( "Could not find version " + version + " in input files" ) ; } res . setAxiomTransformationTimeMs ( System . currentTimeMillis ( ) - start ) ; start = System . currentTimeMillis ( ) ; System . out . println ( "Loading axioms" ) ; no . loadAxioms ( new HashSet < Axiom > ( ( Collection < ? extends Axiom > ) ont . getStatedAxioms ( ) ) ) ; res . setAxiomLoadingTimeMs ( System . currentTimeMillis ( ) - start ) ; start = System . currentTimeMillis ( ) ; System . out . println ( "Running classification" ) ; no . classify ( ) ; res . setClassificationTimeMs ( System . currentTimeMillis ( ) - start ) ; start = System . currentTimeMillis ( ) ; System . out . println ( "Computing taxonomy" ) ; no . buildTaxonomy ( ) ; res . setTaxonomyBuildingTimeMs ( System . currentTimeMillis ( ) - start ) ; System . out . println ( "Done" ) ; return res ; }
Runs the benchmark using an RF1 file as input .
6,625
private void delete ( Node < K , V > n ) { if ( n != root && n . o_s == null && n . poolIndex == Node . NO_INDEX ) { throw new IllegalArgumentException ( "Invalid handle!" ) ; } if ( n . o_s != null ) { Node < K , V > oldestChild = cutOldestChild ( n ) ; if ( oldestChild != null ) { linkInPlace ( oldestChild , n ) ; } else { cutFromParent ( n ) ; } } Node < K , V > childrenTree = combine ( cutChildren ( n ) ) ; boolean checkConsolidate = false ; if ( childrenTree != null ) { checkConsolidate = true ; addPool ( childrenTree , true ) ; } size -- ; if ( n == root ) { root = null ; consolidate ( ) ; checkConsolidate = false ; } else if ( n . poolIndex != Node . NO_INDEX ) { byte curIndex = n . poolIndex ; decreasePool [ curIndex ] = decreasePool [ decreasePoolSize - 1 ] ; decreasePool [ curIndex ] . poolIndex = curIndex ; decreasePool [ decreasePoolSize - 1 ] = null ; decreasePoolSize -- ; n . poolIndex = Node . NO_INDEX ; if ( curIndex == decreasePoolMinPos ) { consolidate ( ) ; checkConsolidate = false ; } else { if ( decreasePoolMinPos == decreasePoolSize ) { decreasePoolMinPos = curIndex ; } checkConsolidate = true ; } } if ( checkConsolidate ) { double sizeAsDouble = size ; if ( decreasePoolSize >= Math . getExponent ( sizeAsDouble ) + 1 ) { consolidate ( ) ; } } }
Delete a node .
6,626
@ SuppressWarnings ( "unchecked" ) private void addPool ( Node < K , V > n , boolean updateMinimum ) { decreasePool [ decreasePoolSize ] = n ; n . poolIndex = decreasePoolSize ; decreasePoolSize ++ ; if ( updateMinimum && decreasePoolSize > 1 ) { Node < K , V > poolMin = decreasePool [ decreasePoolMinPos ] ; int c ; if ( comparator == null ) { c = ( ( Comparable < ? super K > ) n . key ) . compareTo ( poolMin . key ) ; } else { c = comparator . compare ( n . key , poolMin . key ) ; } if ( c < 0 ) { decreasePoolMinPos = n . poolIndex ; } } }
Append to decrease pool .
6,627
private Node < K , V > cutOldestChild ( Node < K , V > n ) { Node < K , V > oldestChild = n . o_c ; if ( oldestChild != null ) { if ( oldestChild . y_s != null ) { oldestChild . y_s . o_s = n ; } n . o_c = oldestChild . y_s ; oldestChild . y_s = null ; oldestChild . o_s = null ; } return oldestChild ; }
Cut the oldest child of a node .
6,628
private void cutFromParent ( Node < K , V > n ) { if ( n . o_s != null ) { if ( n . y_s != null ) { n . y_s . o_s = n . o_s ; } if ( n . o_s . o_c == n ) { n . o_s . o_c = n . y_s ; } else { n . o_s . y_s = n . y_s ; } n . y_s = null ; n . o_s = null ; } }
Cut a node from its parent .
6,629
private void linkInPlace ( Node < K , V > orphan , Node < K , V > n ) { orphan . y_s = n . y_s ; if ( n . y_s != null ) { n . y_s . o_s = orphan ; } orphan . o_s = n . o_s ; if ( n . o_s != null ) { if ( n . o_s . o_c == n ) { n . o_s . o_c = orphan ; } else { n . o_s . y_s = orphan ; } } n . o_s = null ; n . y_s = null ; }
Put an orphan node into the position of another node . The other node becomes an orphan .
6,630
public static synchronized MCAAuthorizationManager createInstance ( Context context ) { if ( instance == null ) { instance = new MCAAuthorizationManager ( context . getApplicationContext ( ) ) ; instance . bluemixRegionSuffix = BMSClient . getInstance ( ) . getBluemixRegionSuffix ( ) ; instance . tenantId = BMSClient . getInstance ( ) . getBluemixAppGUID ( ) ; AuthorizationRequest . setup ( ) ; } return instance ; }
Init singleton instance with context
6,631
public static synchronized MCAAuthorizationManager createInstance ( Context context , String tenantId ) { instance = createInstance ( context ) ; if ( null != tenantId ) { instance . tenantId = tenantId ; } return instance ; }
Init singleton instance with context and tenantId
6,632
public static synchronized MCAAuthorizationManager createInstance ( Context context , String tenantId , String bluemixRegion ) { instance = createInstance ( context , tenantId ) ; if ( null != bluemixRegion ) { instance . bluemixRegionSuffix = bluemixRegion ; } return instance ; }
Init singleton instance with context tenantId and Bluemix region .
6,633
public synchronized void obtainAuthorization ( Context context , ResponseListener listener , Object ... params ) { authorizationProcessManager . startAuthorizationProcess ( context , listener ) ; }
Invoke process for obtaining authorization header . during this process
6,634
public void clearAuthorizationData ( ) { preferences . accessToken . clear ( ) ; preferences . idToken . clear ( ) ; preferences . userIdentity . clear ( ) ; if ( BMSClient . getInstance ( ) != null && BMSClient . getInstance ( ) . getCookieManager ( ) != null ) { CookieStore cookieStore = BMSClient . getInstance ( ) . getCookieManager ( ) . getCookieStore ( ) ; if ( cookieStore != null ) { for ( URI uri : cookieStore . getURIs ( ) ) { for ( HttpCookie cookie : cookieStore . get ( uri ) ) { if ( cookie . getName ( ) . equals ( TAI_COOKIE_NAME ) ) { cookieStore . remove ( uri , cookie ) ; } } } } } }
Clear the local stored authorization data
6,635
public void setAuthorizationPersistencePolicy ( PersistencePolicy policy ) { if ( policy == null ) { throw new IllegalArgumentException ( "The policy argument cannot be null" ) ; } if ( preferences . persistencePolicy . get ( ) != policy ) { preferences . persistencePolicy . set ( policy ) ; preferences . accessToken . updateStateByPolicy ( ) ; preferences . idToken . updateStateByPolicy ( ) ; } }
Change the sate of the current authorization persistence policy
6,636
public void registerAuthenticationListener ( String realm , AuthenticationListener listener ) { if ( realm == null || realm . isEmpty ( ) ) { throw new InvalidParameterException ( "The realm name can't be null or empty." ) ; } if ( listener == null ) { throw new InvalidParameterException ( "The authentication listener object can't be null." ) ; } ChallengeHandler handler = new ChallengeHandler ( ) ; handler . initialize ( realm , listener ) ; challengeHandlers . put ( realm , handler ) ; }
Registers authentication listener for specified realm .
6,637
public void unregisterAuthenticationListener ( String realm ) { if ( realm != null && ! realm . isEmpty ( ) ) { challengeHandlers . remove ( realm ) ; } }
Unregisters authentication listener
6,638
public static void addAuthorizationHeader ( URLConnection urlConnection , String header ) { if ( header != null ) { urlConnection . setRequestProperty ( AUTHORIZATION_HEADER , header ) ; } }
Adds the authorization header to the given URL connection object .
6,639
protected BinaryResourcesHandler getBinaryResourcesHandler ( FacesContext context ) { BinaryResourcesHandler binaryRsHandler = ( BinaryResourcesHandler ) context . getExternalContext ( ) . getApplicationMap ( ) . get ( JawrConstant . BINARY_CONTEXT_ATTRIBUTE ) ; if ( binaryRsHandler == null ) { throw new IllegalStateException ( "You are using a Jawr image tag while the Jawr Binary servlet has not been initialized. Initialization of Jawr Binary servlet either failed or never occurred." ) ; } return binaryRsHandler ; }
Returns the image resource handler
6,640
protected Predicate createPredicate ( Path root , CriteriaQuery < ? > query , CriteriaBuilder cb , String propertyName , ComparisonOperator operator , Object argument , PersistenceContext context ) { logger . debug ( "Creating criterion: {} {} {}" , propertyName , operator , argument ) ; switch ( operator ) { case EQUAL : { if ( containWildcard ( argument ) ) { return createLike ( root , query , cb , propertyName , argument , context ) ; } else { return createEqual ( root , query , cb , propertyName , argument , context ) ; } } case NOT_EQUAL : { if ( containWildcard ( argument ) ) { return createNotLike ( root , query , cb , propertyName , argument , context ) ; } else { return createNotEqual ( root , query , cb , propertyName , argument , context ) ; } } case GREATER_THAN : return createGreaterThan ( root , query , cb , propertyName , argument , context ) ; case GREATER_EQUAL : return createGreaterEqual ( root , query , cb , propertyName , argument , context ) ; case LESS_THAN : return createLessThan ( root , query , cb , propertyName , argument , context ) ; case LESS_EQUAL : return createLessEqual ( root , query , cb , propertyName , argument , context ) ; case IN : return createIn ( root , query , cb , propertyName , argument , context ) ; case NOT_IN : return createNotIn ( root , query , cb , propertyName , argument , context ) ; } throw new IllegalArgumentException ( "Unknown operator: " + operator ) ; }
Delegate creating of a Predicate to an appropriate method according to operator .
6,641
protected Predicate createEqual ( Path root , CriteriaQuery < ? > query , CriteriaBuilder cb , String propertyPath , Object argument , PersistenceContext context ) { return cb . equal ( root . get ( propertyPath ) , argument ) ; }
Apply an equal constraint to the named property .
6,642
protected Predicate createNotEqual ( Path root , CriteriaQuery < ? > query , CriteriaBuilder cb , String propertyPath , Object argument , PersistenceContext context ) { return cb . notEqual ( root . get ( propertyPath ) , argument ) ; }
Apply a not equal constraint to the named property .
6,643
protected Predicate createLessThan ( Path root , CriteriaQuery < ? > query , CriteriaBuilder cb , String propertyPath , Object argument , PersistenceContext context ) { if ( ! ( argument instanceof Comparable ) ) throw new BadRequestException ( context . getMessageSource ( ) . getErrorMessage ( INCOMPATIBLE_QUERY_OPERATION , context . getLocale ( ) , "lt" ) ) ; return cb . lessThan ( root . get ( propertyPath ) , ( Comparable ) argument ) ; }
Apply a less than constraint to the named property .
6,644
protected boolean containWildcard ( Object value ) { if ( ! ( value instanceof String ) ) { return false ; } String casted = ( String ) value ; return casted . contains ( LIKE_WILDCARD . toString ( ) ) ; }
Check if given value contains wildcard .
6,645
public String getDetailMessage ( ) { if ( errorDetails == null || errorDetails . isEmpty ( ) ) return getMessage ( ) ; StringBuilder sb = new StringBuilder ( 512 ) ; sb . append ( getMessage ( ) ) ; sb . append ( " [" ) ; for ( int i = 0 ; i < errorDetails . size ( ) ; i ++ ) { ErrorDetail errorDetail = errorDetails . get ( i ) ; if ( i > 0 ) sb . append ( ", " ) ; sb . append ( errorDetail . getMessage ( ) ) ; } sb . append ( "]" ) ; return sb . toString ( ) ; }
Return a detail message . If errorDetails is not empty then the returned message will combine these together otherwise the standard exception message is returned .
6,646
public static JawrCacheManager getCacheManager ( JawrConfig config , String resourceType ) { String cacheMgrAttributeName = CACHE_ATTR_PREFIX + resourceType . toUpperCase ( ) + CACHE_ATTR_SUFFIX ; JawrCacheManager cacheManager = ( JawrCacheManager ) config . getContext ( ) . getAttribute ( cacheMgrAttributeName ) ; if ( cacheManager == null ) { String cacheManagerClass = config . getProperty ( CACHE_PROPERTY_NAME , BasicCacheManager . class . getName ( ) ) ; cacheManager = ( JawrCacheManager ) ClassLoaderResourceUtils . buildObjectInstance ( cacheManagerClass , new Object [ ] { config } ) ; config . getContext ( ) . setAttribute ( cacheMgrAttributeName , cacheManager ) ; } return cacheManager ; }
Retrieves the cache manager for a resource type
6,647
public static synchronized JawrCacheManager resetCacheManager ( JawrConfig config , String resourceType ) { String cacheMgrAttributeName = CACHE_ATTR_PREFIX + resourceType . toUpperCase ( ) + CACHE_ATTR_SUFFIX ; JawrCacheManager cacheManager = ( JawrCacheManager ) config . getContext ( ) . getAttribute ( cacheMgrAttributeName ) ; if ( cacheManager != null ) { cacheManager . clear ( ) ; config . getContext ( ) . removeAttribute ( cacheMgrAttributeName ) ; } return getCacheManager ( config , resourceType ) ; }
Resets the cache manager for a resource type
6,648
protected final void addBundleToMap ( String bundleId , String mapping ) throws DuplicateBundlePathException { for ( JoinableResourceBundle bundle : currentBundles ) { if ( bundleId . equals ( bundle . getId ( ) ) || this . bundleMapping . containsKey ( bundleId ) ) { Marker fatal = MarkerFactory . getMarker ( "FATAL" ) ; LOGGER . error ( fatal , "Duplicate bundle id resulted from mapping:" + bundleId ) ; throw new DuplicateBundlePathException ( bundleId ) ; } } bundleMapping . put ( bundleId , mapping ) ; }
Add a bundle and its mapping to the resulting Map .
6,649
public void loadAxioms ( final Set < ? extends Axiom > inclusions ) { long start = System . currentTimeMillis ( ) ; if ( log . isInfoEnabled ( ) ) log . info ( "Loading " + inclusions . size ( ) + " axioms" ) ; Set < Inclusion > normInclusions = normalise ( inclusions ) ; if ( log . isInfoEnabled ( ) ) log . info ( "Processing " + normInclusions . size ( ) + " normalised axioms" ) ; Statistics . INSTANCE . setTime ( "normalisation" , System . currentTimeMillis ( ) - start ) ; start = System . currentTimeMillis ( ) ; for ( Inclusion i : normInclusions ) { addTerm ( i . getNormalForm ( ) ) ; } Statistics . INSTANCE . setTime ( "indexing" , System . currentTimeMillis ( ) - start ) ; }
Normalises and loads a set of axioms .
6,650
private String printInternalObject ( Object o ) { if ( o instanceof Conjunction ) { Conjunction con = ( Conjunction ) o ; StringBuilder sb = new StringBuilder ( ) ; AbstractConcept [ ] cons = con . getConcepts ( ) ; if ( cons != null && cons . length > 0 ) { sb . append ( printInternalObject ( cons [ 0 ] ) ) ; for ( int i = 1 ; i < cons . length ; i ++ ) { sb . append ( " + " ) ; sb . append ( printInternalObject ( cons [ i ] ) ) ; } } return sb . toString ( ) ; } else if ( o instanceof Existential ) { Existential e = ( Existential ) o ; AbstractConcept c = e . getConcept ( ) ; int role = e . getRole ( ) ; return factory . lookupRoleId ( role ) + "." + printInternalObject ( c ) ; } else if ( o instanceof Datatype ) { StringBuilder sb = new StringBuilder ( ) ; Datatype d = ( Datatype ) o ; String feature = factory . lookupFeatureId ( d . getFeature ( ) ) ; sb . append ( feature . toString ( ) ) ; sb . append ( ".(" ) ; AbstractLiteral literal = d . getLiteral ( ) ; sb . append ( literal ) ; sb . append ( ")" ) ; return sb . toString ( ) ; } else if ( o instanceof Concept ) { Object obj = factory . lookupConceptId ( ( ( Concept ) o ) . hashCode ( ) ) ; if ( au . csiro . ontology . model . NamedConcept . TOP . equals ( obj ) ) { return "TOP" ; } else if ( au . csiro . ontology . model . NamedConcept . BOTTOM . equals ( obj ) ) { return "BOTTOM" ; } else if ( obj instanceof AbstractConcept ) { return "<" + printInternalObject ( obj ) + ">" ; } else { return obj . toString ( ) ; } } else if ( o instanceof Comparable < ? > ) { return o . toString ( ) ; } else { throw new RuntimeException ( "Unexpected object with class " + o . getClass ( ) . getName ( ) ) ; } }
Prints an object of the internal model using the string representation of the corresponding object in the external model .
6,651
protected void addTerm ( NormalFormGCI term ) { if ( term instanceof NF1a ) { final NF1a nf1 = ( NF1a ) term ; final int a = nf1 . lhsA ( ) ; addTerms ( ontologyNF1 , a , nf1 . getQueueEntry ( ) ) ; } else if ( term instanceof NF1b ) { final NF1b nf1 = ( NF1b ) term ; final int a1 = nf1 . lhsA1 ( ) ; final int a2 = nf1 . lhsA2 ( ) ; addTerms ( ontologyNF1 , a1 , nf1 . getQueueEntry1 ( ) ) ; addTerms ( ontologyNF1 , a2 , nf1 . getQueueEntry2 ( ) ) ; } else if ( term instanceof NF2 ) { final NF2 nf2 = ( NF2 ) term ; addTerms ( ontologyNF2 , nf2 ) ; } else if ( term instanceof NF3 ) { final NF3 nf3 = ( NF3 ) term ; addTerms ( ontologyNF3 , nf3 ) ; } else if ( term instanceof NF4 ) { ontologyNF4 . add ( ( NF4 ) term ) ; } else if ( term instanceof NF5 ) { ontologyNF5 . add ( ( NF5 ) term ) ; } else if ( term instanceof NF6 ) { reflexiveRoles . add ( ( ( NF6 ) term ) . getR ( ) ) ; } else if ( term instanceof NF7 ) { final NF7 nf7 = ( NF7 ) term ; addTerms ( ontologyNF7 , nf7 ) ; } else if ( term instanceof NF8 ) { final NF8 nf8 = ( NF8 ) term ; addTerms ( ontologyNF8 , nf8 ) ; } else { throw new IllegalArgumentException ( "Type of " + term + " must be one of NF1 through NF8" ) ; } }
Adds a normalised term to the ontology .
6,652
private void rePrimeNF6 ( AxiomSet as , IConceptMap < IConceptSet > subsumptions ) { int size = as . getNf6Axioms ( ) . size ( ) ; if ( size == 0 ) return ; IConceptSet deltaNF6 = new SparseConceptSet ( size ) ; for ( NF6 nf6 : as . getNf6Axioms ( ) ) { deltaNF6 . add ( nf6 . getR ( ) ) ; } for ( IntIterator it = deltaNF6 . iterator ( ) ; it . hasNext ( ) ; ) { int role = it . next ( ) ; for ( IntIterator it2 = contextIndex . keyIterator ( ) ; it2 . hasNext ( ) ; ) { int concept = it2 . next ( ) ; Context ctx = contextIndex . get ( concept ) ; if ( ctx . getSucc ( ) . containsRole ( role ) && ! ctx . getSucc ( ) . lookupConcept ( role ) . contains ( concept ) ) { ctx . processExternalEdge ( role , concept ) ; affectedContexts . add ( ctx ) ; ctx . startTracking ( ) ; if ( ctx . activate ( ) ) { todo . add ( ctx ) ; } } } } }
These are reflexive role axioms . If an axiom of this kind is added then an external edge must be added to all the contexts that contain that role and don t contain a successor to themselves .
6,653
public void classify ( ) { long start = System . currentTimeMillis ( ) ; if ( log . isInfoEnabled ( ) ) log . info ( "Classifying with " + numThreads + " threads" ) ; int numConcepts = factory . getTotalConcepts ( ) ; for ( int i = 0 ; i < numConcepts ; i ++ ) { Context c = new Context ( i , this ) ; contextIndex . put ( i , c ) ; if ( c . activate ( ) ) { todo . add ( c ) ; } if ( log . isTraceEnabled ( ) ) { log . trace ( "Added context " + i ) ; } } if ( log . isInfoEnabled ( ) ) log . info ( "Running saturation" ) ; ExecutorService executor = Executors . newFixedThreadPool ( numThreads , THREAD_FACTORY ) ; for ( int j = 0 ; j < numThreads ; j ++ ) { Runnable worker = new Worker ( todo ) ; executor . execute ( worker ) ; } executor . shutdown ( ) ; while ( ! executor . isTerminated ( ) ) { try { executor . awaitTermination ( 100 , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } assert ( todo . isEmpty ( ) ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Processed " + contextIndex . size ( ) + " contexts" ) ; } hasBeenIncrementallyClassified = false ; Statistics . INSTANCE . setTime ( "classification" , System . currentTimeMillis ( ) - start ) ; }
Starts the concurrent classification process .
6,654
public IConceptMap < IConceptSet > getNewSubsumptions ( ) { IConceptMap < IConceptSet > res = new DenseConceptMap < IConceptSet > ( newContexts . size ( ) ) ; for ( Context ctx : newContexts ) { res . put ( ctx . getConcept ( ) , ctx . getS ( ) ) ; } return res ; }
Returns the subsumptions for the new concepts added in an incremental classification .
6,655
public IConceptMap < IConceptSet > getAffectedSubsumptions ( ) { int size = 0 ; for ( Context ctx : affectedContexts ) { if ( ctx . hasNewSubsumptions ( ) ) { size ++ ; } } IConceptMap < IConceptSet > res = new DenseConceptMap < IConceptSet > ( size ) ; for ( IntIterator it = contextIndex . keyIterator ( ) ; it . hasNext ( ) ; ) { int key = it . next ( ) ; Context ctx = contextIndex . get ( key ) ; if ( ctx . hasNewSubsumptions ( ) ) { res . put ( key , ctx . getS ( ) ) ; } } return res ; }
Returns the subsumptions for the existing concepts that have additional subsumptions due to the axioms added in an incremental classification .
6,656
public R getRelationships ( ) { R r = new R ( factory . getTotalConcepts ( ) , factory . getTotalRoles ( ) ) ; for ( IntIterator it = contextIndex . keyIterator ( ) ; it . hasNext ( ) ; ) { int key = it . next ( ) ; Context ctx = contextIndex . get ( key ) ; int concept = ctx . getConcept ( ) ; CR pred = ctx . getPred ( ) ; CR succ = ctx . getSucc ( ) ; int [ ] predRoles = pred . getRoles ( ) ; for ( int i = 0 ; i < predRoles . length ; i ++ ) { IConceptSet cs = pred . lookupConcept ( predRoles [ i ] ) ; for ( IntIterator it2 = cs . iterator ( ) ; it2 . hasNext ( ) ; ) { int predC = it2 . next ( ) ; r . store ( predC , predRoles [ i ] , concept ) ; } } int [ ] succRoles = succ . getRoles ( ) ; for ( int i = 0 ; i < succRoles . length ; i ++ ) { IConceptSet cs = succ . lookupConcept ( succRoles [ i ] ) ; for ( IntIterator it2 = cs . iterator ( ) ; it2 . hasNext ( ) ; ) { int succC = it2 . next ( ) ; r . store ( concept , succRoles [ i ] , succC ) ; } } } return r ; }
Collects all the information contained in the concurrent R structures in every context and returns a single R structure with all their content .
6,657
private boolean isChild ( Node cn , Node cn2 ) { if ( cn == cn2 ) return false ; Queue < Node > toProcess = new LinkedList < Node > ( ) ; toProcess . addAll ( cn . getParents ( ) ) ; while ( ! toProcess . isEmpty ( ) ) { Node tcn = toProcess . poll ( ) ; if ( tcn . equals ( cn2 ) ) return true ; Set < Node > parents = tcn . getParents ( ) ; if ( parents != null && ! parents . isEmpty ( ) ) toProcess . addAll ( parents ) ; } return false ; }
Indicates if cn is a child of cn2 .
6,658
public void setHeaders ( Map < String , List < String > > headerMap ) { headers = new Headers . Builder ( ) ; for ( Map . Entry < String , List < String > > e : headerMap . entrySet ( ) ) { for ( String headerValue : e . getValue ( ) ) { addHeader ( e . getKey ( ) , headerValue ) ; } } }
Sets headers for this resource request . Overrides all headers previously added .
6,659
public void addAppIDHeader ( Context contextValue ) { BaseAppIdentity appIdDetails = new BaseAppIdentity ( contextValue ) ; headers . add ( APPLICATION_BUNDLE_ID , appIdDetails . getId ( ) ) ; }
Adds the App budle ID to this resource request .
6,660
public void setTimeout ( int timeout ) { this . timeout = timeout ; httpClient . connectTimeout ( timeout , TimeUnit . MILLISECONDS ) ; httpClient . readTimeout ( timeout , TimeUnit . MILLISECONDS ) ; httpClient . writeTimeout ( timeout , TimeUnit . MILLISECONDS ) ; }
Sets the timeout for this resource request .
6,661
protected void sendOKHttpRequest ( Request request , final Callback callback ) { OkHttpClient client = httpClient . build ( ) ; client . newCall ( request ) . enqueue ( callback ) ; }
Hands off the request to OkHttp
6,662
protected void updateProgressListener ( ProgressListener progressListener , Response response ) { InputStream responseStream = response . getResponseByteStream ( ) ; int bytesDownloaded = 0 ; long totalBytesExpected = response . getContentLength ( ) ; final int segmentSize = 2048 ; byte [ ] responseBytes ; if ( totalBytesExpected > Integer . MAX_VALUE ) { logger . warn ( "The response body for " + getUrl ( ) + " is too large to hold in a byte array. Only the first 2 GiB will be available." ) ; responseBytes = new byte [ Integer . MAX_VALUE ] ; } else { responseBytes = new byte [ ( int ) totalBytesExpected ] ; } int nextByte ; try { while ( ( nextByte = responseStream . read ( ) ) != - 1 ) { if ( bytesDownloaded % segmentSize == 0 ) { progressListener . onProgress ( bytesDownloaded , totalBytesExpected ) ; } responseBytes [ bytesDownloaded ] = ( byte ) nextByte ; bytesDownloaded += 1 ; } } catch ( IOException e ) { logger . error ( "IO Exception: " + e . getMessage ( ) ) ; } if ( response instanceof ResponseImpl ) { ( ( ResponseImpl ) response ) . setResponseBytes ( responseBytes ) ; } }
As a download request progresses periodically call the user s ProgressListener
6,663
public void initialize ( Context context , ResponseListener listener ) { this . context = context ; this . listener = ( listener != null ) ? listener : new ResponseListener ( ) { final String message = "ResponseListener is not specified. Defaulting to empty listener." ; public void onSuccess ( Response response ) { logger . debug ( message ) ; } public void onFailure ( Response response , Throwable t , JSONObject extendedInfo ) { logger . debug ( message ) ; } } ; logger . debug ( "AuthorizationRequestAgent is initialized." ) ; }
Initializes the request manager .
6,664
public void sendRequest ( String path , RequestOptions options ) throws IOException , JSONException { String rootUrl ; if ( path == null ) { throw new IllegalArgumentException ( "'path' parameter can't be null." ) ; } if ( path . indexOf ( BMSClient . HTTP_SCHEME ) == 0 && path . contains ( ":" ) ) { URL url = new URL ( path ) ; path = url . getPath ( ) ; rootUrl = url . toString ( ) . replace ( path , "" ) ; } else { String MCATenantId = MCAAuthorizationManager . getInstance ( ) . getTenantId ( ) ; if ( MCATenantId == null ) { MCATenantId = BMSClient . getInstance ( ) . getBluemixAppGUID ( ) ; } String bluemixRegionSuffix = MCAAuthorizationManager . getInstance ( ) . getBluemixRegionSuffix ( ) ; if ( bluemixRegionSuffix == null ) { bluemixRegionSuffix = BMSClient . getInstance ( ) . getBluemixRegionSuffix ( ) ; } String serverHost = BMSClient . getInstance ( ) . getDefaultProtocol ( ) + "://" + AUTH_SERVER_NAME + bluemixRegionSuffix ; if ( overrideServerHost != null ) serverHost = overrideServerHost ; rootUrl = serverHost + "/" + AUTH_SERVER_NAME + "/" + AUTH_PATH + MCATenantId ; } sendRequestInternal ( rootUrl , path , options ) ; }
Assembles the request path from root and path to authorization endpoint and sends the request .
6,665
private void sendRequestInternal ( String rootUrl , String path , RequestOptions options ) throws IOException , JSONException { logger . debug ( "Sending request to root: " + rootUrl + " with path: " + path ) ; if ( options == null ) { options = new RequestOptions ( ) ; } this . requestPath = Utils . concatenateUrls ( rootUrl , path ) ; this . requestOptions = options ; AuthorizationRequest request = new AuthorizationRequest ( this . requestPath , options . requestMethod ) ; if ( options . timeout != 0 ) { request . setTimeout ( options . timeout ) ; } else { request . setTimeout ( BMSClient . getInstance ( ) . getDefaultTimeout ( ) ) ; } if ( options . headers != null ) { for ( Map . Entry < String , String > entry : options . headers . entrySet ( ) ) { request . addHeader ( entry . getKey ( ) , entry . getValue ( ) ) ; } } if ( answers != null ) { String answer = answers . toString ( 0 ) ; String authorizationHeaderValue = String . format ( "Bearer %s" , answer . replace ( "\n" , "" ) ) ; request . addHeader ( "Authorization" , authorizationHeaderValue ) ; logger . debug ( "Added authorization header to request: " + authorizationHeaderValue ) ; } if ( Request . GET . equalsIgnoreCase ( options . requestMethod ) ) { request . setQueryParameters ( options . parameters ) ; request . send ( this ) ; } else { request . send ( options . parameters , this ) ; } }
Builds an authorization request and sends it . It also caches the request url and request options in order to be able to re - send the request when authorization challenges have been handled .
6,666
private void setExpectedAnswers ( ArrayList < String > realms ) { if ( answers == null ) { return ; } for ( String realm : realms ) { try { answers . put ( realm , "" ) ; } catch ( JSONException t ) { logger . error ( "setExpectedAnswers failed with exception: " + t . getLocalizedMessage ( ) , t ) ; } } }
Initializes the collection of expected challenge answers .
6,667
public void removeExpectedAnswer ( String realm ) { if ( answers != null ) { answers . remove ( realm ) ; } try { if ( isAnswersFilled ( ) ) { resendRequest ( ) ; } } catch ( Throwable t ) { logger . error ( "removeExpectedAnswer failed with exception: " + t . getLocalizedMessage ( ) , t ) ; } }
Removes an expected challenge answer from collection .
6,668
public void submitAnswer ( JSONObject answer , String realm ) { if ( answers == null ) { answers = new JSONObject ( ) ; } try { answers . put ( realm , answer ) ; if ( isAnswersFilled ( ) ) { resendRequest ( ) ; } } catch ( Throwable t ) { logger . error ( "submitAnswer failed with exception: " + t . getLocalizedMessage ( ) , t ) ; } }
Adds an expected challenge answer to collection of answers .
6,669
public boolean isAnswersFilled ( ) throws JSONException { if ( answers == null ) { return true ; } Iterator < String > it = answers . keys ( ) ; while ( it . hasNext ( ) ) { String key = it . next ( ) ; Object value = answers . get ( key ) ; if ( ( value instanceof String ) && value . equals ( "" ) ) { return false ; } } return true ; }
Verifies whether all expected challenges have been answered or not .
6,670
private void processRedirectResponse ( Response response ) throws RuntimeException , JSONException , MalformedURLException { ResponseImpl responseImpl = ( ResponseImpl ) response ; List < String > locationHeaders = responseImpl . getHeader ( LOCATION_HEADER_NAME ) ; String location = ( locationHeaders != null && locationHeaders . size ( ) > 0 ) ? locationHeaders . get ( 0 ) : null ; if ( location == null ) { throw new RuntimeException ( "Redirect response does not contain 'Location' header." ) ; } URL url = new URL ( location ) ; String query = url . getQuery ( ) ; if ( query . contains ( WL_RESULT ) ) { String result = Utils . getParameterValueFromQuery ( query , WL_RESULT ) ; JSONObject jsonResult = new JSONObject ( result ) ; JSONObject jsonFailures = jsonResult . optJSONObject ( AUTH_FAILURE_VALUE_NAME ) ; if ( jsonFailures != null ) { processFailures ( jsonFailures ) ; listener . onFailure ( response , null , null ) ; return ; } JSONObject jsonSuccesses = jsonResult . optJSONObject ( AUTH_SUCCESS_VALUE_NAME ) ; if ( jsonSuccesses != null ) { processSuccesses ( jsonSuccesses ) ; } } listener . onSuccess ( response ) ; }
Processes redirect response from authorization endpoint .
6,671
private void processResponse ( Response response ) { JSONObject jsonResponse = Utils . extractSecureJson ( response ) ; JSONObject jsonChallenges = ( jsonResponse == null ) ? null : jsonResponse . optJSONObject ( CHALLENGES_VALUE_NAME ) ; if ( jsonChallenges != null ) { startHandleChallenges ( jsonChallenges , response ) ; } else { listener . onSuccess ( response ) ; } }
Process a response from the server .
6,672
private void startHandleChallenges ( JSONObject jsonChallenges , Response response ) { ArrayList < String > challenges = getRealmsFromJson ( jsonChallenges ) ; MCAAuthorizationManager authManager = ( MCAAuthorizationManager ) BMSClient . getInstance ( ) . getAuthorizationManager ( ) ; if ( isAuthorizationRequired ( response ) ) { setExpectedAnswers ( challenges ) ; } for ( String realm : challenges ) { ChallengeHandler handler = authManager . getChallengeHandler ( realm ) ; if ( handler != null ) { JSONObject challenge = jsonChallenges . optJSONObject ( realm ) ; handler . handleChallenge ( this , challenge , context ) ; } else { throw new RuntimeException ( "Challenge handler for realm is not found: " + realm ) ; } } }
Handles authentication challenges .
6,673
private boolean isAuthorizationRequired ( Response response ) { if ( response != null && response . getStatus ( ) == 401 ) { ResponseImpl responseImpl = ( ResponseImpl ) response ; String challengesHeader = responseImpl . getFirstHeader ( AUTHENTICATE_HEADER_NAME ) ; if ( AUTHENTICATE_HEADER_VALUE . equalsIgnoreCase ( challengesHeader ) ) { return true ; } } return false ; }
Checks server response for MFP 401 error . This kind of response should contain MFP authentication challenges .
6,674
private void processFailures ( JSONObject jsonFailures ) { if ( jsonFailures == null ) { return ; } MCAAuthorizationManager authManager = ( MCAAuthorizationManager ) BMSClient . getInstance ( ) . getAuthorizationManager ( ) ; ArrayList < String > challenges = getRealmsFromJson ( jsonFailures ) ; for ( String realm : challenges ) { ChallengeHandler handler = authManager . getChallengeHandler ( realm ) ; if ( handler != null ) { JSONObject challenge = jsonFailures . optJSONObject ( realm ) ; handler . handleFailure ( context , challenge ) ; } else { logger . error ( "Challenge handler for realm is not found: " + realm ) ; } } }
Processes authentication failures .
6,675
private void processSuccesses ( JSONObject jsonSuccesses ) { if ( jsonSuccesses == null ) { return ; } MCAAuthorizationManager authManager = ( MCAAuthorizationManager ) BMSClient . getInstance ( ) . getAuthorizationManager ( ) ; ArrayList < String > challenges = getRealmsFromJson ( jsonSuccesses ) ; for ( String realm : challenges ) { ChallengeHandler handler = authManager . getChallengeHandler ( realm ) ; if ( handler != null ) { JSONObject challenge = jsonSuccesses . optJSONObject ( realm ) ; handler . handleSuccess ( context , challenge ) ; } else { logger . error ( "Challenge handler for realm is not found: " + realm ) ; } } }
Processes authentication successes .
6,676
public void requestFailed ( JSONObject info ) { logger . error ( "BaseRequest failed with info: " + ( info == null ? "info is null" : info . toString ( ) ) ) ; listener . onFailure ( null , null , info ) ; }
Called when a request to authorization server failed .
6,677
private ArrayList < String > getRealmsFromJson ( JSONObject jsonChallenges ) { Iterator < String > challengesIterator = jsonChallenges . keys ( ) ; ArrayList < String > challenges = new ArrayList < > ( ) ; while ( challengesIterator . hasNext ( ) ) { challenges . add ( challengesIterator . next ( ) ) ; } return challenges ; }
Iterates a JSON object containing authorization challenges and builds a list of reals .
6,678
public void onFailure ( Response response , Throwable t , JSONObject extendedInfo ) { if ( isAuthorizationRequired ( response ) ) { processResponseWrapper ( response , true ) ; } else { listener . onFailure ( response , t , extendedInfo ) ; } }
Called when request fails .
6,679
private void processResponseWrapper ( Response response , boolean isFailure ) { try { ResponseImpl responseImpl = ( ResponseImpl ) response ; if ( isFailure || ! responseImpl . isRedirect ( ) ) { processResponse ( response ) ; } else { processRedirectResponse ( response ) ; } } catch ( Throwable t ) { logger . error ( "processResponseWrapper caught exception: " + t . getLocalizedMessage ( ) ) ; listener . onFailure ( response , t , null ) ; } }
Called from onSuccess and onFailure . Handles all possible exceptions and notifies the listener if an exception occurs .
6,680
public static void assertNotNull ( final Object object , final StatusType status ) { RESTAssert . assertTrue ( object != null , status ) ; }
assert that object is not null
6,681
public static void assertNotEmpty ( final String string , final StatusType status ) { RESTAssert . assertNotNull ( string , status ) ; RESTAssert . assertFalse ( string . isEmpty ( ) , status ) ; }
assert that string is not null nor empty
6,682
public static void assertNotEmpty ( final Collection < ? > collection , final StatusType status ) { RESTAssert . assertNotNull ( collection , status ) ; RESTAssert . assertFalse ( collection . isEmpty ( ) , status ) ; }
assert that collection is not empty
6,683
public static void assertSingleElement ( final Collection < ? > collection , final StatusType status ) { RESTAssert . assertNotNull ( collection , status ) ; RESTAssert . assertTrue ( collection . size ( ) == 1 , status ) ; }
assert that collection has one element
6,684
public static Class < ? > getClass ( String classname ) { Class < ? > clazz = null ; try { clazz = Class . forName ( classname ) ; } catch ( Exception e ) { } if ( null == clazz ) { Exception classNotFoundEx = null ; try { clazz = Class . forName ( classname , true , new ClassLoaderResourceUtils ( ) . getClass ( ) . getClassLoader ( ) ) ; } catch ( Exception e ) { classNotFoundEx = e ; } if ( null == clazz ) { ClassLoader threadClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( null != threadClassLoader ) { try { clazz = Class . forName ( classname , true , threadClassLoader ) ; } catch ( Exception e ) { throw new BundlingProcessException ( e . getMessage ( ) + " [The custom class " + classname + " could not be instantiated, check wether it is available on the classpath and" + " verify that it has a zero-arg constructor].\n" + " The specific error message is: " + e . getClass ( ) . getName ( ) + ":" + e . getMessage ( ) , e ) ; } } else { throw new BundlingProcessException ( classNotFoundEx . getMessage ( ) + " [The custom class " + classname + " could not be instantiated, check wether it is available on the classpath and" + " verify that it has a zero-arg constructor].\n" + " The specific error message is: " + classNotFoundEx . getClass ( ) . getName ( ) + ":" + classNotFoundEx . getMessage ( ) , classNotFoundEx ) ; } } } return clazz ; }
Returns the class associated to the class name given in parameter
6,685
public TaskResult add ( String key , SparseArray < ? extends Parcelable > value ) { mBundle . putSparseParcelableArray ( key , value ) ; return this ; }
Inserts a SparseArray of Parcelable values into the mapping of this Bundle replacing any existing value for the given key . Either key or value may be null .
6,686
private void tryExpire ( boolean force , LongSupplier time ) { long now = time . getAsLong ( ) ; if ( force || now >= nextPruning ) { nextPruning = now + pruningDelay ; histogram . expire ( now ) ; } }
Expire the histogram if it is time to expire it or if force is true AND it is dirty
6,687
public static boolean isOnline ( Context context ) { ConnectivityManager cm = ( ConnectivityManager ) context . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; if ( cm == null ) { return false ; } NetworkInfo info = cm . getActiveNetworkInfo ( ) ; return info != null && info . isConnectedOrConnecting ( ) ; }
Checks whether there s a network connection .
6,688
public static boolean isCurrentConnectionWifi ( Context context ) { ConnectivityManager cm = ( ConnectivityManager ) context . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; if ( cm == null ) { return false ; } NetworkInfo info = cm . getActiveNetworkInfo ( ) ; return info != null && info . getType ( ) == ConnectivityManager . TYPE_WIFI ; }
Check if current connection is Wi - Fi .
6,689
public static void keepCpuAwake ( Context context , boolean awake ) { if ( cpuWakeLock == null ) { PowerManager pm = ( PowerManager ) context . getSystemService ( Context . POWER_SERVICE ) ; if ( pm != null ) { cpuWakeLock = pm . newWakeLock ( PowerManager . PARTIAL_WAKE_LOCK | PowerManager . ON_AFTER_RELEASE , TAG ) ; cpuWakeLock . setReferenceCounted ( true ) ; } } if ( cpuWakeLock != null ) { if ( awake ) { cpuWakeLock . acquire ( ) ; L . d ( TAG , "Adquired CPU lock" ) ; } else if ( cpuWakeLock . isHeld ( ) ) { cpuWakeLock . release ( ) ; L . d ( TAG , "Released CPU lock" ) ; } } }
Register a wake lock to power management in the device .
6,690
public static void keepWiFiOn ( Context context , boolean on ) { if ( wifiLock == null ) { WifiManager wm = ( WifiManager ) context . getSystemService ( Context . WIFI_SERVICE ) ; if ( wm != null ) { wifiLock = wm . createWifiLock ( WifiManager . WIFI_MODE_FULL , TAG ) ; wifiLock . setReferenceCounted ( true ) ; } } if ( wifiLock != null ) { if ( on ) { wifiLock . acquire ( ) ; L . d ( TAG , "Adquired WiFi lock" ) ; } else if ( wifiLock . isHeld ( ) ) { wifiLock . release ( ) ; L . d ( TAG , "Released WiFi lock" ) ; } } }
Register a WiFi lock to WiFi management in the device .
6,691
private ClassLoader createClassLoader ( File warFile , File tempDirectory ) { try { File condiLibDirectory = new File ( tempDirectory , "condi" ) ; condiLibDirectory . mkdirs ( ) ; File jettyWebappDirectory = new File ( tempDirectory , "webapp" ) ; jettyWebappDirectory . mkdirs ( ) ; List < URL > urls = new ArrayList < > ( ) ; JarInputStream in = new JarInputStream ( new FileInputStream ( warFile ) ) ; while ( true ) { JarEntry entry = in . getNextJarEntry ( ) ; if ( entry == null ) { break ; } String name = entry . getName ( ) ; String prefix = "META-INF/jettyconsole/lib/" ; if ( ! entry . isDirectory ( ) ) { if ( name . startsWith ( prefix ) ) { String simpleName = name . substring ( name . lastIndexOf ( "/" ) + 1 ) ; File file = new File ( condiLibDirectory , simpleName ) ; unpackFile ( in , file ) ; urls . add ( file . toURI ( ) . toURL ( ) ) ; } else if ( ! name . startsWith ( "META-INF/jettyconsole" ) && ! name . contains ( "JettyConsoleBootstrapMainClass" ) ) { File file = new File ( jettyWebappDirectory , name ) ; file . getParentFile ( ) . mkdirs ( ) ; unpackFile ( in , file ) ; } } } in . close ( ) ; return new URLClassLoader ( urls . toArray ( new URL [ urls . size ( ) ] ) , JettyConsoleBootstrapMainClass . class . getClassLoader ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Create a URL class loader containing all jar files in the given directory
6,692
private static File getWarLocation ( ) { URL resource = JettyConsoleBootstrapMainClass . class . getResource ( "/META-INF/jettyconsole/jettyconsole.properties" ) ; String file = resource . getFile ( ) ; file = file . substring ( "file:" . length ( ) , file . indexOf ( "!" ) ) ; try { file = URLDecoder . decode ( file , "utf-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } return new File ( file ) ; }
Return a File pointing to the location of the Jar file this Main method is executed from .
6,693
private static void unpackFile ( InputStream in , File file ) { byte [ ] buffer = new byte [ 4096 ] ; try { OutputStream out = new FileOutputStream ( file ) ; int read ; while ( ( read = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , read ) ; } out . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Write the contents of an InputStream to a file
6,694
public static Element getFirstChildElement ( Node node ) { if ( node instanceof NestableNode ) { return ( ( NestableNode ) node ) . getFirstElementChild ( ) ; } return null ; }
Get the first child node that is an element node .
6,695
public static final Element getNextSiblingElement ( Node node ) { List < Node > siblings = node . getParent ( ) . getChildren ( ) ; Node n = null ; int index = siblings . indexOf ( node ) + 1 ; if ( index > 0 && index < siblings . size ( ) ) { n = siblings . get ( index ) ; while ( ! ( n instanceof Element ) && ++ index < siblings . size ( ) ) { n = siblings . get ( index ) ; } if ( index == siblings . size ( ) ) { n = null ; } } return ( Element ) n ; }
Get the next sibling element .
6,696
public void registerTable ( String fullStatName , Supplier < Table > accessor ) { registerStatistic ( fullStatName , table ( accessor ) ) ; }
Directly register a TABLE stat with its accessors
6,697
public void registerGauge ( String fullStatName , Supplier < Number > accessor ) { registerStatistic ( fullStatName , gauge ( accessor ) ) ; }
Directly register a GAUGE stat with its accessor
6,698
public void registerCounter ( String fullStatName , Supplier < Number > accessor ) { registerStatistic ( fullStatName , counter ( accessor ) ) ; }
Directly register a COUNTER stat with its accessor
6,699
private void writePathDescriptor ( File consoleDir , Set < String > paths ) { try ( PrintWriter writer = new PrintWriter ( new FileOutputStream ( new File ( consoleDir , "jettyconsolepaths.txt" ) ) ) ) { for ( String path : paths ) { writer . println ( path ) ; } } catch ( FileNotFoundException e ) { throw new RuntimeException ( e ) ; } }
Write a txt file with one line for each unpacked class or resource from dependencies .