idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
5,400
|
public boolean isCollection ( Object obj , Field field ) { try { Object val = field . get ( obj ) ; boolean isCollResource = false ; if ( val != null ) { isCollResource = CollectionResource . class . equals ( val . getClass ( ) ) ; } return ( ! isCollResource && ! field . getType ( ) . equals ( CollectionResource . class ) ) && ( Collection . class . equals ( field . getType ( ) ) || ArrayUtils . contains ( field . getType ( ) . getInterfaces ( ) , Collection . class ) ) ; } catch ( Exception e ) { throw new Siren4JRuntimeException ( e ) ; } }
|
Determine if the field is a Collection class and not a CollectionResource class which needs special treatment .
|
5,401
|
public static Field getGetterField ( Method method ) { if ( method == null ) { throw new IllegalArgumentException ( "method cannot be null." ) ; } Class < ? > clazz = method . getDeclaringClass ( ) ; String fName = stripGetterPrefix ( method . getName ( ) ) ; Field field = null ; try { field = findField ( clazz , fName ) ; } catch ( Exception ignore ) { } return field ; }
|
Find the field for the getter method based on the get methods name . It finds the field on the declaring class .
|
5,402
|
public static List < ReflectedInfo > getExposedFieldInfo ( final Class < ? > clazz ) { List < ReflectedInfo > results = null ; try { results = fieldInfoCache . get ( clazz , new Callable < List < ReflectedInfo > > ( ) { public List < ReflectedInfo > call ( ) throws Exception { List < ReflectedInfo > exposed = new ArrayList < ReflectedInfo > ( ) ; for ( Method m : clazz . getMethods ( ) ) { if ( isIgnored ( m ) ) { continue ; } boolean methodIsSirenProperty = m . getAnnotation ( Siren4JProperty . class ) != null ; String methodAnnotationName = extractEffectiveName ( m , null ) ; if ( ReflectionUtils . isGetter ( m ) ) { Field f = getGetterField ( m ) ; if ( f != null && isIgnored ( f ) ) { continue ; } if ( f != null ) { String fieldAnnotationName = extractEffectiveName ( f , null ) ; String effectiveName = ( String ) findFirstNonNull ( Arrays . asList ( fieldAnnotationName , methodAnnotationName , f . getName ( ) ) . iterator ( ) ) ; exposed . add ( new ReflectedInfo ( f , m , ReflectionUtils . getSetter ( clazz , f ) , effectiveName ) ) ; } else if ( methodIsSirenProperty ) { exposed . add ( ReflectedInfoBuilder . aReflectedInfo ( ) . withGetter ( m ) . withEffectiveName ( extractEffectiveName ( m , stripGetterPrefix ( m . getName ( ) ) ) ) . build ( ) ) ; } } else if ( methodIsSirenProperty ) { exposed . add ( ReflectedInfoBuilder . aReflectedInfo ( ) . withGetter ( m ) . withEffectiveName ( extractEffectiveName ( m , m . getName ( ) ) ) . build ( ) ) ; } } return exposed ; } } ) ; } catch ( ExecutionException e ) { throw new Siren4JRuntimeException ( e ) ; } return results ; }
|
Retrieve all fields deemed as Exposed i . e . they are public or have a public accessor method or are marked by an annotation to be exposed .
|
5,403
|
public static boolean isGetter ( Method method ) { String name = method . getName ( ) ; String [ ] splitname = StringUtils . splitByCharacterTypeCamelCase ( name ) ; return ! method . getReturnType ( ) . equals ( void . class ) && Modifier . isPublic ( method . getModifiers ( ) ) && ( splitname [ 0 ] . equals ( GETTER_PREFIX_BOOLEAN ) || splitname [ 0 ] . equals ( GETTER_PREFIX ) ) ; }
|
Determine if the method is a getter .
|
5,404
|
public static boolean isSetter ( Method method ) { String name = method . getName ( ) ; String [ ] splitname = StringUtils . splitByCharacterTypeCamelCase ( name ) ; return method . getReturnType ( ) . equals ( void . class ) && Modifier . isPublic ( method . getModifiers ( ) ) && splitname [ 0 ] . equals ( SETTER_PREFIX ) ; }
|
Determine if the method is a setter .
|
5,405
|
public static String replaceFieldTokens ( Object obj , String str , List < ReflectedInfo > fields , boolean parentMode ) throws Siren4JException { Map < String , Field > index = new HashMap < String , Field > ( ) ; if ( StringUtils . isBlank ( str ) ) { return str ; } if ( fields != null ) { for ( ReflectedInfo info : fields ) { Field f = info . getField ( ) ; if ( f != null ) { index . put ( f . getName ( ) , f ) ; } } } try { for ( String key : ReflectionUtils . getTokenKeys ( str ) ) { if ( ( ! parentMode && ! key . startsWith ( "parent." ) ) || ( parentMode && key . startsWith ( "parent." ) ) ) { String fieldname = key . startsWith ( "parent." ) ? key . substring ( 7 ) : key ; if ( index . containsKey ( fieldname ) ) { Field f = index . get ( fieldname ) ; if ( f . getType ( ) . isEnum ( ) || ArrayUtils . contains ( propertyTypes , f . getType ( ) ) ) { String replacement = "" ; Object theObject = f . get ( obj ) ; if ( f . getType ( ) . isEnum ( ) ) { replacement = theObject == null ? "" : ( ( Enum ) theObject ) . name ( ) ; } else { replacement = theObject == null ? "" : theObject . toString ( ) ; } str = str . replaceAll ( "\\{" + key + "\\}" , Matcher . quoteReplacement ( "" + replacement ) ) ; } } } } } catch ( Exception e ) { throw new Siren4JException ( e ) ; } return str ; }
|
Replaces field tokens with the actual value in the fields . The field types must be simple property types
|
5,406
|
public static String flattenReservedTokens ( String str ) { if ( StringUtils . isBlank ( str ) ) { return str ; } return str . replaceAll ( "\\{\\[" , "{" ) . replaceAll ( "\\]\\}" , "}" ) ; }
|
Removes the square brackets that signify reserved from inside the tokens in the string .
|
5,407
|
public static Set < String > getTokenKeys ( String str ) { Set < String > results = new HashSet < String > ( ) ; String sDelim = "{" ; String eDelim = "}" ; if ( StringUtils . isBlank ( str ) ) { return results ; } int start = - 1 ; int end = 0 ; do { start = str . indexOf ( sDelim , end ) ; if ( start != - 1 ) { end = str . indexOf ( eDelim , start ) ; if ( end != - 1 ) { results . add ( str . substring ( start + sDelim . length ( ) , end ) ) ; } } } while ( start != - 1 && end != - 1 ) ; return results ; }
|
Retrieve all token keys from a string . A token is found by its its start and end delimiters which are open and close curly braces .
|
5,408
|
public static ReflectedInfo getFieldInfoByEffectiveName ( List < ReflectedInfo > infoList , String name ) { if ( infoList == null ) { throw new IllegalArgumentException ( "infoList cannot be null." ) ; } if ( StringUtils . isBlank ( name ) ) { throw new IllegalArgumentException ( "name cannot be null or empty." ) ; } ReflectedInfo result = null ; for ( ReflectedInfo info : infoList ) { if ( name . equals ( info . getEffectiveName ( ) ) ) { result = info ; break ; } } return result ; }
|
Helper method to find the field info by its effective name from the passed in list of info .
|
5,409
|
public static ReflectedInfo getFieldInfoByName ( List < ReflectedInfo > infoList , String name ) { if ( infoList == null ) { throw new IllegalArgumentException ( "infoList cannot be null." ) ; } if ( StringUtils . isBlank ( name ) ) { throw new IllegalArgumentException ( "name cannot be null or empty." ) ; } ReflectedInfo result = null ; for ( ReflectedInfo info : infoList ) { if ( info . getField ( ) == null ) { continue ; } if ( name . equals ( info . getField ( ) . getName ( ) ) ) { result = info ; break ; } } return result ; }
|
Helper method to find the field info by its name from the passed in list of info .
|
5,410
|
public static void setFieldValue ( Object obj , ReflectedInfo info , Object value ) throws Siren4JException { if ( obj == null ) { throw new IllegalArgumentException ( "obj cannot be null" ) ; } if ( info == null ) { throw new IllegalArgumentException ( "info cannot be null" ) ; } if ( info . getSetter ( ) != null ) { Method setter = info . getSetter ( ) ; setter . setAccessible ( true ) ; try { setter . invoke ( obj , new Object [ ] { value } ) ; } catch ( Exception e ) { throw new Siren4JException ( e ) ; } } else { try { info . getField ( ) . set ( obj , value ) ; } catch ( Exception e ) { throw new Siren4JException ( e ) ; } } }
|
Sets the fields value first by attempting to call the setter method if it exists and then falling back to setting the field directly .
|
5,411
|
@ SuppressWarnings ( "deprecation" ) private void init ( String ... packages ) throws Siren4JException { LOG . info ( "Siren4J scanning classpath for resource entries..." ) ; Reflections reflections = null ; ConfigurationBuilder builder = new ConfigurationBuilder ( ) ; Collection < URL > urls = new HashSet < URL > ( ) ; if ( packages != null && packages . length > 0 ) { for ( String pkg : packages ) { urls . addAll ( ClasspathHelper . forPackage ( pkg ) ) ; } } else { urls . addAll ( ClasspathHelper . forPackage ( "com." ) ) ; urls . addAll ( ClasspathHelper . forPackage ( "org." ) ) ; urls . addAll ( ClasspathHelper . forPackage ( "net." ) ) ; } urls . addAll ( ClasspathHelper . forPackage ( "com.google.code.siren4j.resource" ) ) ; builder . setUrls ( urls ) ; reflections = new Reflections ( builder ) ; Set < Class < ? > > types = reflections . getTypesAnnotatedWith ( Siren4JEntity . class ) ; for ( Class < ? > c : types ) { Siren4JEntity anno = c . getAnnotation ( Siren4JEntity . class ) ; String name = StringUtils . defaultIfBlank ( anno . name ( ) , anno . entityClass ( ) . length > 0 ? anno . entityClass ( ) [ 0 ] : c . getName ( ) ) ; putEntry ( StringUtils . defaultIfEmpty ( name , c . getName ( ) ) , c , false ) ; if ( ! containsEntityEntry ( c . getName ( ) ) ) { putEntry ( StringUtils . defaultIfEmpty ( c . getName ( ) , c . getName ( ) ) , c , false ) ; } } }
|
Scans the classpath for resources .
|
5,412
|
private void callMethod ( Object obj , Step step ) throws SecurityException , NoSuchMethodException , IllegalArgumentException , IllegalAccessException , InvocationTargetException { Class < ? > clazz = obj . getClass ( ) ; Method method = ReflectionUtils . findMethod ( clazz , step . getMethodName ( ) , step . getArgTypes ( ) ) ; method . invoke ( obj , step . getArguments ( ) ) ; }
|
Finds and calls the method specified by the step passed in .
|
5,413
|
private Class < ? > [ ] getTypes ( Object [ ] args ) { if ( args == null || args . length == 0 ) { return null ; } List < Class < ? > > classList = new ArrayList < Class < ? > > ( ) ; for ( Object obj : args ) { classList . add ( obj == null ? Object . class : obj . getClass ( ) ) ; } return classList . toArray ( new Class [ ] { } ) ; }
|
Attempts to determine the argument types based on the passed in object instances .
|
5,414
|
public static Entity getSubEntityByRel ( Entity entity , String ... rel ) { if ( entity == null ) { throw new IllegalArgumentException ( "entity cannot be null." ) ; } if ( ArrayUtils . isEmpty ( rel ) ) { throw new IllegalArgumentException ( "rel cannot be null or empty" ) ; } List < Entity > entities = entity . getEntities ( ) ; if ( entities == null ) return null ; Entity ent = null ; for ( Entity e : entities ) { if ( ArrayUtils . isNotEmpty ( e . getRel ( ) ) && ArrayUtils . toString ( rel ) . equals ( ArrayUtils . toString ( e . getRel ( ) ) ) ) { ent = e ; break ; } } return ent ; }
|
Retrieve a sub entity by its relationship .
|
5,415
|
public static Link getLinkByRel ( Entity entity , String ... rel ) { if ( entity == null ) { throw new IllegalArgumentException ( "entity cannot be null." ) ; } if ( ArrayUtils . isEmpty ( rel ) ) { throw new IllegalArgumentException ( "rel cannot be null or empty" ) ; } List < Link > links = entity . getLinks ( ) ; if ( links == null ) return null ; Link link = null ; for ( Link l : links ) { if ( ArrayUtils . isNotEmpty ( l . getRel ( ) ) && ArrayUtils . toString ( rel ) . equals ( ArrayUtils . toString ( l . getRel ( ) ) ) ) { link = l ; break ; } } return link ; }
|
Retrieve a link by its relationship .
|
5,416
|
public static Action getActionByName ( Entity entity , String name ) { if ( entity == null ) { throw new IllegalArgumentException ( "entity cannot be null." ) ; } if ( StringUtils . isBlank ( name ) ) { throw new IllegalArgumentException ( "name cannot be null or empty." ) ; } List < Action > actions = entity . getActions ( ) ; if ( actions == null ) return null ; Action action = null ; for ( Action a : actions ) { if ( a . getName ( ) . equals ( name ) ) { action = a ; break ; } } return action ; }
|
Retrieve an action by its name .
|
5,417
|
public static boolean isStringArrayEmpty ( String [ ] arr ) { boolean empty = true ; if ( arr != null ) { if ( arr . length > 0 ) { for ( String s : arr ) { if ( StringUtils . isNotBlank ( s ) ) { empty = false ; break ; } } } } return empty ; }
|
Determine if the string array is empty . It is considered empty if zero length or all items are blank strings ;
|
5,418
|
private Token unwindTo ( int targetIndent , Token copyFrom ) { assert dentsBuffer . isEmpty ( ) : dentsBuffer ; dentsBuffer . add ( createToken ( nlToken , copyFrom ) ) ; while ( true ) { int prevIndent = indentations . pop ( ) ; if ( prevIndent == targetIndent ) { break ; } if ( targetIndent > prevIndent ) { indentations . push ( prevIndent ) ; dentsBuffer . add ( createToken ( indentToken , copyFrom ) ) ; break ; } dentsBuffer . add ( createToken ( dedentToken , copyFrom ) ) ; } indentations . push ( targetIndent ) ; return dentsBuffer . remove ( ) ; }
|
Returns a DEDENT token and also queues up additional DEDENTS as necessary .
|
5,419
|
public static void initialize ( HttpServletRequest request ) { if ( factory == null ) { throw new RuntimeException ( "RaygunClient is not initialized. Call RaygunClient.Initialize()" ) ; } client . set ( factory . newClient ( request ) ) ; }
|
Initialize the static accessor for the given request
|
5,420
|
public RaygunClientFactory withData ( Object key , Object value ) { factoryData . put ( key , value ) ; return this ; }
|
This data will be added to every error sent
|
5,421
|
public RaygunClient withData ( Object key , Object value ) { clientData . put ( key , value ) ; return this ; }
|
This data will be added to all errors sent from this instance of the client
|
5,422
|
public RaygunDuplicateErrorFilter create ( ) { RaygunDuplicateErrorFilter filter = instance . get ( ) ; if ( filter == null ) { filter = new RaygunDuplicateErrorFilter ( ) ; instance . set ( filter ) ; return filter ; } else { instance . remove ( ) ; return filter ; } }
|
this will haunt me for eternity
|
5,423
|
public static void main ( String [ ] args ) throws Throwable { final Exception exceptionToThrowLater = new Exception ( "Raygun4Java test exception" ) ; Thread . setDefaultUncaughtExceptionHandler ( MyExceptionHandler . instance ( ) ) ; MyExceptionHandler . getClient ( ) . recordBreadcrumb ( "App starting up" ) ; RaygunIdentifier userIdentity = new RaygunIdentifier ( "a@b.com" ) . withEmail ( "a@b.com" ) . withFirstName ( "Foo" ) . withFullName ( "Foo Bar" ) . withAnonymous ( false ) . withUuid ( UUID . randomUUID ( ) . toString ( ) ) ; MyExceptionHandler . getClient ( ) . setUser ( userIdentity ) ; new Thread ( new Runnable ( ) { public void run ( ) { MyExceptionHandler . getClient ( ) . recordBreadcrumb ( "different thread starting" ) ; try { MyExceptionHandler . getClient ( ) . recordBreadcrumb ( "throwing exception" ) ; throw exceptionToThrowLater ; } catch ( Exception e ) { MyExceptionHandler . getClient ( ) . recordBreadcrumb ( "handling exception" ) ; Map < String , String > customData = new HashMap < String , String > ( ) ; customData . put ( "thread id" , "" + Thread . currentThread ( ) . getId ( ) ) ; MyExceptionHandler . getClient ( ) . withTag ( "thrown from thread" ) . withTag ( "no user withData" ) . withData ( "thread id" , "" + Thread . currentThread ( ) . getId ( ) ) . send ( exceptionToThrowLater ) ; MyExceptionHandler . getClient ( ) . recordBreadcrumb ( "This should not appear because we're sending the same exception on the same thread" ) ; Set < String > tags = new HashSet < String > ( ) ; tags . add ( "should not appear in console" ) ; MyExceptionHandler . getClient ( ) . send ( exceptionToThrowLater , tags ) ; } RaygunSettings . getSettings ( ) . setHttpProxy ( "nothing here" , 80 ) ; System . out . println ( "No Send below this line" ) ; MyExceptionHandler . getClient ( ) . send ( new Exception ( "occurred while offline offline" ) ) ; System . out . println ( "No Send above this lines ^" ) ; RaygunSettings . getSettings ( ) . setHttpProxy ( null , 80 ) ; MyExceptionHandler . getClient ( ) . send ( new Exception ( "This should trigger offline" ) ) ; } } ) . start ( ) ; MyExceptionHandler . getClient ( ) . recordBreadcrumb ( "Throwing exception on main thread" ) ; throw exceptionToThrowLater ; }
|
An example of how to use Raygun4Java
|
5,424
|
public ParsedPolicy parse ( File file ) throws Exception { if ( file == null || ! file . exists ( ) ) { if ( debug ) { if ( file == null ) { ProGradePolicyDebugger . log ( "Given File is null" ) ; } else { if ( ! file . exists ( ) ) { ProGradePolicyDebugger . log ( "Policy file " + file . getCanonicalPath ( ) + " doesn't exists." ) ; } } } throw new Exception ( "ER007: File with policy doesn't exists!" ) ; } if ( debug ) { ProGradePolicyDebugger . log ( "Parsing policy " + file . getCanonicalPath ( ) ) ; } final InputStreamReader reader = new InputStreamReader ( new FileInputStream ( file ) , "UTF-8" ) ; try { return parse ( reader ) ; } finally { reader . close ( ) ; } }
|
Parse content of text policy file to ParsedPolicy object which represent this policy .
|
5,425
|
private ParsedPrincipal parsePrincipal ( ) throws Exception { lookahead = st . nextToken ( ) ; switch ( lookahead ) { case '*' : lookahead = st . nextToken ( ) ; if ( lookahead == '*' ) { return new ParsedPrincipal ( null , null ) ; } else { throw new Exception ( "ER018: There have to be name wildcard after type wildcard." ) ; } case '\"' : return new ParsedPrincipal ( st . sval ) ; case StreamTokenizer . TT_WORD : String principalClass = st . sval ; lookahead = st . nextToken ( ) ; switch ( lookahead ) { case '*' : return new ParsedPrincipal ( principalClass , null ) ; case '\"' : return new ParsedPrincipal ( principalClass , st . sval ) ; default : throw new Exception ( "ER019: Principal name or * expected." ) ; } default : throw new Exception ( "ER020: Principal type, *, or keystore alias expected." ) ; } }
|
Private method for parsing principal part of policy entry .
|
5,426
|
private ParsedPermission parsePermission ( ) throws Exception { ParsedPermission permission = new ParsedPermission ( ) ; lookahead = st . nextToken ( ) ; if ( lookahead == StreamTokenizer . TT_WORD ) { permission . setPermissionType ( st . sval ) ; } else { throw new Exception ( "ER021: Permission type expected." ) ; } lookahead = st . nextToken ( ) ; if ( lookahead == '\"' ) { permission . setPermissionName ( st . sval ) ; } else { if ( lookahead == ';' ) { return permission ; } throw new Exception ( "ER022: Permission name or or [;] expected." ) ; } lookahead = st . nextToken ( ) ; if ( lookahead == ',' ) { lookahead = st . nextToken ( ) ; boolean shouldBeSigned = false ; if ( lookahead == '\"' ) { String actionsWords = st . sval ; permission . setActions ( actionsWords ) ; lookahead = st . nextToken ( ) ; switch ( lookahead ) { case ',' : shouldBeSigned = true ; break ; case ';' : return permission ; default : throw new Exception ( "ER023: Unexpected symbol, expected [,] or [;]." ) ; } lookahead = st . nextToken ( ) ; } if ( lookahead == StreamTokenizer . TT_WORD ) { String signedByWord = st . sval ; if ( ! signedByWord . toLowerCase ( ) . equals ( "signedby" ) ) { throw new Exception ( "ER024: [signedBy] expected but was [" + signedByWord + "]." ) ; } } else if ( shouldBeSigned ) { throw new Exception ( "ER025: [signedBy] expected after [,]." ) ; } else { throw new Exception ( "ER026: Actions or [signedBy] expected after [,]." ) ; } lookahead = st . nextToken ( ) ; if ( lookahead == '\"' ) { permission . setSignedBy ( st . sval ) ; } else { throw new Exception ( "ER027: signedBy attribute expected." ) ; } lookahead = st . nextToken ( ) ; } if ( lookahead == ';' ) { return permission ; } else { throw new Exception ( "ER028: [;] expected." ) ; } }
|
Private method for parsing permission part of policy entry .
|
5,427
|
private void parseKeystore ( ) throws Exception { String tempKeystoreURL = null ; String tempKeystoreType = null ; String tempKeystoreProvider = null ; lookahead = st . nextToken ( ) ; if ( lookahead == '\"' ) { tempKeystoreURL = st . sval ; } else { throw new Exception ( "ER029: [\"keystore_URL\"] expected." ) ; } lookahead = st . nextToken ( ) ; if ( lookahead == ',' ) { lookahead = st . nextToken ( ) ; if ( lookahead == '\"' ) { tempKeystoreType = st . sval ; } else { throw new Exception ( "ER030: [\"keystore_type\"] expected." ) ; } lookahead = st . nextToken ( ) ; if ( lookahead == ',' ) { lookahead = st . nextToken ( ) ; if ( lookahead == '\"' ) { tempKeystoreProvider = st . sval ; } else { throw new Exception ( "ER031: [\"keystore_provider\"] expected." ) ; } lookahead = st . nextToken ( ) ; } } if ( lookahead == ';' ) { if ( keystoreEntry == null ) { keystoreEntry = new ParsedKeystoreEntry ( tempKeystoreURL , tempKeystoreType , tempKeystoreProvider ) ; } } else { throw new Exception ( "ER032: [;] expected at the end of keystore entry." ) ; } }
|
Private method for parsing keystore entry .
|
5,428
|
private void parseKeystorePassword ( ) throws Exception { lookahead = st . nextToken ( ) ; if ( lookahead == '\"' ) { if ( keystorePasswordURL == null ) { keystorePasswordURL = st . sval ; } } else { throw new Exception ( "ER033: [\"keystore_password\"] expected." ) ; } lookahead = st . nextToken ( ) ; if ( lookahead == ';' ) { return ; } else { throw new Exception ( "ER034: [;] expected at the end of keystorePasswordURL entry." ) ; } }
|
Private method for parsing keystorePasswordURL entry .
|
5,429
|
private void parsePriority ( ) throws Exception { lookahead = st . nextToken ( ) ; if ( lookahead == '\"' ) { if ( priority == null ) { String pr = st . sval ; if ( pr . toLowerCase ( ) . equals ( "grant" ) ) { priority = Priority . GRANT ; } else { if ( pr . toLowerCase ( ) . equals ( "deny" ) ) { priority = Priority . DENY ; } else { throw new Exception ( "ER035: grant or deny priority expected." ) ; } } } } else { throw new Exception ( "ER036: quotes expected after priority keyword." ) ; } lookahead = st . nextToken ( ) ; if ( lookahead == ';' ) { return ; } else { throw new Exception ( "ER037: [;] expected at the end of priority entry." ) ; } }
|
Private method for parsing priority entry .
|
5,430
|
static Policy getPolicy ( ) { final SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { return AccessController . doPrivileged ( new PrivilegedAction < Policy > ( ) { public Policy run ( ) { return Policy . getPolicy ( ) ; } } ) ; } else { return Policy . getPolicy ( ) ; } }
|
Returns the installed policy object .
|
5,431
|
public void refresh ( ) { FileReader fr = null ; if ( file != null ) { try { fr = new FileReader ( file ) ; } catch ( Exception e ) { System . err . println ( "Unable to read policy file " + file + ": " + e . getMessage ( ) ) ; } } loadPolicy ( fr , skipDefaultPolicies ) ; }
|
Method which loads policy data from policy file .
|
5,432
|
private void addParsedPolicyEntries ( List < ParsedPolicyEntry > parsedEntries , List < ProGradePolicyEntry > entries , KeyStore keystore , boolean grant ) throws Exception { for ( ParsedPolicyEntry p : parsedEntries ) { try { entries . add ( initializePolicyEntry ( p , keystore , grant ) ) ; } catch ( Exception e ) { System . err . println ( "Unable to initialize policy entry: " + e . getMessage ( ) ) ; } } }
|
Private method which adds parsedEntries to entries .
|
5,433
|
private ProGradePolicyEntry initializePolicyEntry ( ParsedPolicyEntry parsedEntry , KeyStore keystore , boolean grant ) throws Exception { ProGradePolicyEntry entry = new ProGradePolicyEntry ( grant , debug ) ; if ( parsedEntry . getCodebase ( ) != null || parsedEntry . getSignedBy ( ) != null ) { CodeSource cs = createCodeSource ( parsedEntry , keystore ) ; if ( cs != null ) { entry . setCodeSource ( cs ) ; } else { entry . setNeverImplies ( true ) ; return entry ; } } for ( ParsedPrincipal p : parsedEntry . getPrincipals ( ) ) { if ( p . hasAlias ( ) ) { String principal = gainPrincipalFromAlias ( expandStringWithProperty ( p . getAlias ( ) ) , keystore ) ; if ( principal != null ) { entry . addPrincipal ( new ProGradePrincipal ( "javax.security.auth.x500.X500Principal" , principal , false , false ) ) ; } else { entry . setNeverImplies ( true ) ; return entry ; } } else { entry . addPrincipal ( new ProGradePrincipal ( p . getPrincipalClass ( ) , expandStringWithProperty ( p . getPrincipalName ( ) ) , p . hasClassWildcard ( ) , p . hasNameWildcard ( ) ) ) ; } } for ( ParsedPermission p : parsedEntry . getPermissions ( ) ) { Permission perm = createPermission ( p , keystore ) ; if ( perm != null ) { entry . addPermission ( perm ) ; } } return entry ; }
|
Private method for initializing one policy entry .
|
5,434
|
private boolean entriesImplyPermission ( List < ProGradePolicyEntry > policyEntriesList , ProtectionDomain domain , Permission permission ) { for ( ProGradePolicyEntry entry : policyEntriesList ) { if ( entry . implies ( domain , permission ) ) { return true ; } } return false ; }
|
Private method for determining whether grant or deny entries of ProgradePolicyFile imply given Permission .
|
5,435
|
private String expandStringWithProperty ( String s ) throws Exception { if ( ! expandProperties ) { return s ; } if ( s == null || s . indexOf ( "${" ) == - 1 ) { return s ; } String toReturn = "" ; String [ ] split = s . split ( Pattern . quote ( "${" ) ) ; toReturn += split [ 0 ] ; for ( int i = 1 ; i < split . length ; i ++ ) { String part = split [ i ] ; if ( part . startsWith ( "{" ) ) { toReturn += ( "${" + part ) ; continue ; } String [ ] splitPart = part . split ( "}" , 2 ) ; if ( splitPart . length < 2 ) { throw new Exception ( "ER001: Expand property without end } or inner property expansion!" ) ; } else { if ( splitPart [ 0 ] . equals ( "/" ) ) { toReturn += File . separator ; } else { toReturn += SecurityActions . getSystemProperty ( splitPart [ 0 ] ) ; } toReturn += splitPart [ 1 ] ; } } return toReturn ; }
|
Private method for expanding String which contains any property .
|
5,436
|
private CodeSource createCodeSource ( ParsedPolicyEntry parsedEntry , KeyStore keystore ) throws Exception { String parsedCodebase = expandStringWithProperty ( parsedEntry . getCodebase ( ) ) ; String parsedCertificates = expandStringWithProperty ( parsedEntry . getSignedBy ( ) ) ; String [ ] splitCertificates = new String [ 0 ] ; if ( parsedCertificates != null ) { splitCertificates = parsedCertificates . split ( "," ) ; } if ( splitCertificates . length > 0 && keystore == null ) { throw new Exception ( "ER002: Keystore must be defined if signedBy is used" ) ; } List < Certificate > certList = new ArrayList < Certificate > ( ) ; for ( int i = 0 ; i < splitCertificates . length ; i ++ ) { Certificate certificate = keystore . getCertificate ( splitCertificates [ i ] ) ; if ( certificate != null ) { certList . add ( certificate ) ; } else { return null ; } } Certificate [ ] certificates ; if ( certList . isEmpty ( ) ) { certificates = null ; } else { certificates = new Certificate [ certList . size ( ) ] ; certList . toArray ( certificates ) ; } URL url ; if ( parsedCodebase == null ) { url = null ; } else { url = new URL ( parsedCodebase ) ; } CodeSource cs = new CodeSource ( adaptURL ( url ) , certificates ) ; return cs ; }
|
Private method for creating new CodeSource object from ParsedEntry .
|
5,437
|
private URL adaptURL ( URL url ) throws Exception { if ( url != null && url . getProtocol ( ) . equals ( "file" ) ) { url = new URL ( fixEncodedURI ( url . toURI ( ) . toASCIIString ( ) ) ) ; } return url ; }
|
Private method for adapting URL for using of this ProgradePolicyFile .
|
5,438
|
private KeyStore createKeystore ( ParsedKeystoreEntry parsedKeystoreEntry , String keystorePasswordURL , File policyFile ) throws Exception { if ( parsedKeystoreEntry == null ) { return null ; } KeyStore toReturn ; String keystoreURL = expandStringWithProperty ( parsedKeystoreEntry . getKeystoreURL ( ) ) ; String keystoreType = expandStringWithProperty ( parsedKeystoreEntry . getKeystoreType ( ) ) ; String keystoreProvider = expandStringWithProperty ( parsedKeystoreEntry . getKeystoreProvider ( ) ) ; if ( keystoreURL == null ) { throw new Exception ( "ER003: Null keystore url!" ) ; } if ( keystoreType == null ) { keystoreType = KeyStore . getDefaultType ( ) ; } if ( keystoreProvider == null ) { toReturn = KeyStore . getInstance ( keystoreType ) ; } else { toReturn = KeyStore . getInstance ( keystoreType , keystoreProvider ) ; } char [ ] keystorePassword = null ; if ( keystorePasswordURL != null ) { keystorePassword = readKeystorePassword ( expandStringWithProperty ( keystorePasswordURL ) , policyFile ) ; } String path = getPolicyFileHome ( policyFile ) ; File f = null ; if ( path != null ) { f = new File ( path , keystoreURL ) ; } if ( f == null || ! f . exists ( ) ) { f = new File ( keystoreURL ) ; if ( ! f . exists ( ) ) { throw new Exception ( "ER004: KeyStore doesn't exists!" ) ; } } FileInputStream fis = null ; try { fis = new FileInputStream ( f ) ; toReturn . load ( fis , keystorePassword ) ; } finally { if ( fis != null ) { fis . close ( ) ; } } return toReturn ; }
|
Private method for creating KeyStore object from ParsedKeystoreEntry and other information from policy file .
|
5,439
|
private char [ ] readKeystorePassword ( String keystorePasswordURL , File policyFile ) throws Exception { File f = new File ( getPolicyFileHome ( policyFile ) , keystorePasswordURL ) ; if ( ! f . exists ( ) ) { f = new File ( keystorePasswordURL ) ; if ( ! f . exists ( ) ) { throw new Exception ( "ER005: File on keystorePasswordURL doesn't exists!" ) ; } } Reader reader = new FileReader ( f ) ; StringBuilder sb = new StringBuilder ( ) ; char buffer [ ] = new char [ 64 ] ; int len ; while ( ( len = reader . read ( buffer ) ) > 0 ) { sb . append ( buffer , 0 , len ) ; } reader . close ( ) ; return sb . toString ( ) . trim ( ) . toCharArray ( ) ; }
|
Private method for reading password for keystore from file .
|
5,440
|
private String gainPrincipalFromAlias ( String alias , KeyStore keystore ) throws Exception { if ( keystore == null ) { return null ; } if ( ! keystore . containsAlias ( alias ) ) { return null ; } Certificate certificate = keystore . getCertificate ( alias ) ; if ( certificate == null || ! ( certificate instanceof X509Certificate ) ) { return null ; } X509Certificate x509Certificate = ( X509Certificate ) certificate ; X500Principal principal = new X500Principal ( x509Certificate . getSubjectX500Principal ( ) . toString ( ) ) ; return principal . getName ( ) ; }
|
Private method for gaining X500Principal from keystore according its alias .
|
5,441
|
private String getPolicyFileHome ( File file ) { if ( file == null || ! file . exists ( ) ) { return null ; } return file . getAbsoluteFile ( ) . getParent ( ) ; }
|
Private method for gaining absolute path of folder with policy file .
|
5,442
|
private List < ParsedPolicy > getJavaPolicies ( ) { List < ParsedPolicy > list = new ArrayList < ParsedPolicy > ( ) ; int counter = 1 ; String policyUrl = null ; while ( ( policyUrl = SecurityActions . getSecurityProperty ( "policy.url." + counter ) ) != null ) { try { policyUrl = expandStringWithProperty ( policyUrl ) ; } catch ( Exception ex ) { System . err . println ( "Expanding filepath in policy policy.url." + counter + "=" + policyUrl + " failed. Exception message: " + ex . getMessage ( ) ) ; counter ++ ; continue ; } ParsedPolicy p = null ; InputStreamReader reader = null ; try { reader = new InputStreamReader ( new URL ( policyUrl ) . openStream ( ) , "UTF-8" ) ; p = new Parser ( debug ) . parse ( reader ) ; if ( p != null ) { list . add ( p ) ; } else { System . err . println ( "Parsed policy policy.url." + counter + "=" + policyUrl + " is null" ) ; } } catch ( Exception ex ) { System . err . println ( "Policy policy.url." + counter + "=" + policyUrl + " wasn't successfully parsed. Exception message: " + ex . getMessage ( ) ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } counter ++ ; } return list ; }
|
Private method for gaining and parsing all policies defined in java . security file .
|
5,443
|
private void initializeStaticPolicy ( List < ProGradePolicyEntry > grantEntriesList ) throws Exception { ProGradePolicyEntry p1 = new ProGradePolicyEntry ( true , debug ) ; Certificate [ ] certificates = null ; URL url = new URL ( expandStringWithProperty ( "file:${{java.ext.dirs}}/*" ) ) ; CodeSource cs = new CodeSource ( adaptURL ( url ) , certificates ) ; p1 . setCodeSource ( cs ) ; p1 . addPermission ( new AllPermission ( ) ) ; grantEntriesList . add ( p1 ) ; ProGradePolicyEntry p2 = new ProGradePolicyEntry ( true , debug ) ; p2 . addPermission ( new RuntimePermission ( "stopThread" ) ) ; p2 . addPermission ( new SocketPermission ( "localhost:1024-" , "listen" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vendor" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vendor.url" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.class.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "os.name" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "os.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "os.arch" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "file.separator" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "path.separator" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "line.separator" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.specification.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.specification.vendor" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.specification.name" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.specification.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.specification.vendor" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.specification.name" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.vendor" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.name" , "read" ) ) ; grantEntriesList . add ( p2 ) ; }
|
Private method for initializing static policy .
|
5,444
|
private Certificate [ ] getCertificates ( String parsedCertificates , KeyStore keystore ) throws Exception { String [ ] splitCertificates = new String [ 0 ] ; if ( parsedCertificates != null ) { splitCertificates = parsedCertificates . split ( "," ) ; } if ( splitCertificates . length > 0 && keystore == null ) { throw new Exception ( "ER006: Keystore must be defined if signedBy is used" ) ; } List < Certificate > certList = new ArrayList < Certificate > ( ) ; for ( int i = 0 ; i < splitCertificates . length ; i ++ ) { Certificate certificate = keystore . getCertificate ( splitCertificates [ i ] ) ; if ( certificate != null ) { certList . add ( certificate ) ; } else { return null ; } } Certificate [ ] certificates ; if ( certList . isEmpty ( ) ) { certificates = null ; } else { certificates = new Certificate [ certList . size ( ) ] ; certList . toArray ( certificates ) ; } return certificates ; }
|
Private method for getting certificates from KeyStore .
|
5,445
|
public static Symbol newSymbol ( String prefix , String name ) { checkArguments ( prefix , name ) ; return new Symbol ( prefix , name ) ; }
|
Provide a Symbol with the given prefix and name .
|
5,446
|
public static boolean isValidValue ( JsonReader in ) throws IOException { if ( in . peek ( ) == JsonToken . NULL ) { in . skipValue ( ) ; return false ; } return true ; }
|
Determines whether the next value within the reader is not null .
|
5,447
|
public static < T > void assertThat ( String whatTheObjectIs , T actual , Matcher < ? super T > matcher ) { Description description = new StringDescription ( ) ; if ( matcher . matches ( actual ) ) { description . appendText ( whatTheObjectIs ) ; description . appendText ( " " ) ; matcher . describeTo ( description ) ; pass ( description . toString ( ) ) ; } else { description . appendText ( "asserted that it " ) . appendDescriptionOf ( matcher ) . appendText ( " but " ) ; matcher . describeMismatch ( actual , description ) ; fail ( "assertion on " + whatTheObjectIs + " failed" , description . toString ( ) ) ; } }
|
Assert using a Hamcrest matcher .
|
5,448
|
public static void pass ( String message ) { if ( Boolean . getBoolean ( "visibleassertions.silence" ) || Boolean . getBoolean ( "visibleassertions.silence.passes" ) ) { return ; } System . out . println ( " " + green ( TICK_MARK + " " + message ) ) ; }
|
Indicate that something passed .
|
5,449
|
protected ByteVector write ( final ClassWriter cw , final byte [ ] code , final int len , final int maxStack , final int maxLocals ) { ByteVector v = new ByteVector ( ) ; v . data = value ; v . length = value . length ; return v ; }
|
Returns the byte array form of this attribute .
|
5,450
|
final int getCount ( ) { int count = 0 ; Attribute attr = this ; while ( attr != null ) { count += 1 ; attr = attr . next ; } return count ; }
|
Returns the length of the attribute list that begins with this attribute .
|
5,451
|
final int getSize ( final ClassWriter cw , final byte [ ] code , final int len , final int maxStack , final int maxLocals ) { Attribute attr = this ; int size = 0 ; while ( attr != null ) { cw . newUTF8 ( attr . type ) ; size += attr . write ( cw , code , len , maxStack , maxLocals ) . length + 6 ; attr = attr . next ; } return size ; }
|
Returns the size of all the attributes in this attribute list .
|
5,452
|
final void put ( final ClassWriter cw , final byte [ ] code , final int len , final int maxStack , final int maxLocals , final ByteVector out ) { Attribute attr = this ; while ( attr != null ) { ByteVector b = attr . write ( cw , code , len , maxStack , maxLocals ) ; out . putShort ( cw . newUTF8 ( attr . type ) ) . putInt ( b . length ) ; out . putByteArray ( b . data , 0 , b . length ) ; attr = attr . next ; } }
|
Writes all the attributes of this attribute list in the given byte vector .
|
5,453
|
private void addReference ( final int sourcePosition , final int referencePosition ) { if ( srcAndRefPositions == null ) { srcAndRefPositions = new int [ 6 ] ; } if ( referenceCount >= srcAndRefPositions . length ) { int [ ] a = new int [ srcAndRefPositions . length + 6 ] ; System . arraycopy ( srcAndRefPositions , 0 , a , 0 , srcAndRefPositions . length ) ; srcAndRefPositions = a ; } srcAndRefPositions [ referenceCount ++ ] = sourcePosition ; srcAndRefPositions [ referenceCount ++ ] = referencePosition ; }
|
Adds a forward reference to this label . This method must be called only for a true forward reference i . e . only if this label is not resolved yet . For backward references the offset of the reference can be and must be computed and stored directly .
|
5,454
|
boolean inSameSubroutine ( final Label block ) { for ( int i = 0 ; i < srcAndRefPositions . length ; ++ i ) { if ( ( srcAndRefPositions [ i ] & block . srcAndRefPositions [ i ] ) != 0 ) { return true ; } } return false ; }
|
Returns true if this basic block and the given one belong to a common subroutine .
|
5,455
|
void visitSubroutine ( final Label JSR , final long id , final int nbSubroutines ) { if ( JSR != null ) { if ( ( status & VISITED ) != 0 ) { return ; } status |= VISITED ; if ( ( status & RET ) != 0 ) { if ( ! inSameSubroutine ( JSR ) ) { Edge e = new Edge ( ) ; e . info = inputStackTop ; e . successor = JSR . successors . successor ; e . next = successors ; successors = e ; } } } else { if ( inSubroutine ( id ) ) { return ; } addToSubroutine ( id , nbSubroutines ) ; } Edge e = successors ; while ( e != null ) { if ( ( status & Label . JSR ) == 0 || e != successors . next ) { e . successor . visitSubroutine ( JSR , id , nbSubroutines ) ; } e = e . next ; } }
|
Finds the basic blocks that belong to a given subroutine and marks these blocks as belonging to this subroutine . This recursive method follows the control flow graph to find all the blocks that are reachable from the current block WITHOUT following any JSR target .
|
5,456
|
private void noSuccessor ( ) { if ( compute == FRAMES ) { Label l = new Label ( ) ; l . frame = new Frame ( ) ; l . frame . owner = l ; l . resolve ( this , code . length , code . data ) ; previousBlock . successor = l ; previousBlock = l ; } else { currentBlock . outputStackMax = maxStackSize ; } currentBlock = null ; }
|
Ends the current basic block . This method must be used in the case where the current basic block does not have any successor .
|
5,457
|
private void visitFrame ( final Frame f ) { int i , t ; int nTop = 0 ; int nLocal = 0 ; int nStack = 0 ; int [ ] locals = f . inputLocals ; int [ ] stacks = f . inputStack ; for ( i = 0 ; i < locals . length ; ++ i ) { t = locals [ i ] ; if ( t == Frame . TOP ) { ++ nTop ; } else { nLocal += nTop + 1 ; nTop = 0 ; } if ( t == Frame . LONG || t == Frame . DOUBLE ) { ++ i ; } } for ( i = 0 ; i < stacks . length ; ++ i ) { t = stacks [ i ] ; ++ nStack ; if ( t == Frame . LONG || t == Frame . DOUBLE ) { ++ i ; } } startFrame ( f . owner . position , nLocal , nStack ) ; for ( i = 0 ; nLocal > 0 ; ++ i , -- nLocal ) { t = locals [ i ] ; frame [ frameIndex ++ ] = t ; if ( t == Frame . LONG || t == Frame . DOUBLE ) { ++ i ; } } for ( i = 0 ; i < stacks . length ; ++ i ) { t = stacks [ i ] ; frame [ frameIndex ++ ] = t ; if ( t == Frame . LONG || t == Frame . DOUBLE ) { ++ i ; } } endFrame ( ) ; }
|
Visits a frame that has been computed from scratch .
|
5,458
|
static int readInt ( final byte [ ] b , final int index ) { return ( ( b [ index ] & 0xFF ) << 24 ) | ( ( b [ index + 1 ] & 0xFF ) << 16 ) | ( ( b [ index + 2 ] & 0xFF ) << 8 ) | ( b [ index + 3 ] & 0xFF ) ; }
|
Reads a signed int value in the given byte array .
|
5,459
|
static void writeShort ( final byte [ ] b , final int index , final int s ) { b [ index ] = ( byte ) ( s >>> 8 ) ; b [ index + 1 ] = ( byte ) s ; }
|
Writes a short value in the given byte array .
|
5,460
|
static void getNewOffset ( final int [ ] indexes , final int [ ] sizes , final Label label ) { if ( ( label . status & Label . RESIZED ) == 0 ) { label . position = getNewOffset ( indexes , sizes , 0 , label . position ) ; label . status |= Label . RESIZED ; } }
|
Updates the offset of the given label .
|
5,461
|
private static byte [ ] readClass ( final InputStream is ) throws IOException { if ( is == null ) { throw new IOException ( "Class not found" ) ; } byte [ ] b = new byte [ is . available ( ) ] ; int len = 0 ; while ( true ) { int n = is . read ( b , len , b . length - len ) ; if ( n == - 1 ) { if ( len < b . length ) { byte [ ] c = new byte [ len ] ; System . arraycopy ( b , 0 , c , 0 , len ) ; b = c ; } return b ; } len += n ; if ( len == b . length ) { byte [ ] c = new byte [ b . length + 1000 ] ; System . arraycopy ( b , 0 , c , 0 , len ) ; b = c ; } } }
|
Reads the bytecode of a class .
|
5,462
|
private void readParameterAnnotations ( int v , final String desc , final char [ ] buf , final boolean visible , final MethodVisitor mv ) { int i ; int n = b [ v ++ ] & 0xFF ; int synthetics = Type . getArgumentTypes ( desc ) . length - n ; AnnotationVisitor av ; for ( i = 0 ; i < synthetics ; ++ i ) { av = mv . visitParameterAnnotation ( i , "Ljava/lang/Synthetic;" , false ) ; if ( av != null ) { av . visitEnd ( ) ; } } for ( ; i < n + synthetics ; ++ i ) { int j = readUnsignedShort ( v ) ; v += 2 ; for ( ; j > 0 ; -- j ) { av = mv . visitParameterAnnotation ( i , readUTF8 ( v , buf ) , visible ) ; v = readAnnotationValues ( v + 2 , buf , true , av ) ; } } }
|
Reads parameter annotations and makes the given visitor visit them .
|
5,463
|
private void push ( final int type ) { if ( outputStack == null ) { outputStack = new int [ 10 ] ; } int n = outputStack . length ; if ( outputStackTop >= n ) { int [ ] t = new int [ Math . max ( outputStackTop + 1 , 2 * n ) ] ; System . arraycopy ( outputStack , 0 , t , 0 , n ) ; outputStack = t ; } outputStack [ outputStackTop ++ ] = type ; int top = owner . inputStackTop + outputStackTop ; if ( top > owner . outputStackMax ) { owner . outputStackMax = top ; } }
|
Pushes a new type onto the output frame stack .
|
5,464
|
private void pop ( final String desc ) { char c = desc . charAt ( 0 ) ; if ( c == '(' ) { pop ( ( MethodWriter . getArgumentsAndReturnSizes ( desc ) >> 2 ) - 1 ) ; } else if ( c == 'J' || c == 'D' ) { pop ( 2 ) ; } else { pop ( 1 ) ; } }
|
Pops a type from the output frame stack .
|
5,465
|
void initInputFrame ( final ClassWriter cw , final int access , final Type [ ] args , final int maxLocals ) { inputLocals = new int [ maxLocals ] ; inputStack = new int [ 0 ] ; int i = 0 ; if ( ( access & Opcodes . ACC_STATIC ) == 0 ) { if ( ( access & MethodWriter . ACC_CONSTRUCTOR ) == 0 ) { inputLocals [ i ++ ] = OBJECT | cw . addType ( cw . thisName ) ; } else { inputLocals [ i ++ ] = UNINITIALIZED_THIS ; } } for ( int j = 0 ; j < args . length ; ++ j ) { int t = type ( cw , args [ j ] . getDescriptor ( ) ) ; inputLocals [ i ++ ] = t ; if ( t == LONG || t == DOUBLE ) { inputLocals [ i ++ ] = TOP ; } } while ( i < maxLocals ) { inputLocals [ i ++ ] = TOP ; } }
|
Initializes the input frame of the first basic block from the method descriptor .
|
5,466
|
int getSize ( ) { int size = 0 ; AnnotationWriter aw = this ; while ( aw != null ) { size += aw . bv . length ; aw = aw . next ; } return size ; }
|
Returns the size of this annotation writer list .
|
5,467
|
void put ( final ByteVector out ) { int n = 0 ; int size = 2 ; AnnotationWriter aw = this ; AnnotationWriter last = null ; while ( aw != null ) { ++ n ; size += aw . bv . length ; aw . visitEnd ( ) ; aw . prev = last ; last = aw ; aw = aw . next ; } out . putInt ( size ) ; out . putShort ( n ) ; aw = last ; while ( aw != null ) { out . putByteArray ( aw . bv . data , 0 , aw . bv . length ) ; aw = aw . prev ; } }
|
Puts the annotations of this annotation writer list into the given byte vector .
|
5,468
|
static void put ( final AnnotationWriter [ ] panns , final int off , final ByteVector out ) { int size = 1 + 2 * ( panns . length - off ) ; for ( int i = off ; i < panns . length ; ++ i ) { size += panns [ i ] == null ? 0 : panns [ i ] . getSize ( ) ; } out . putInt ( size ) . putByte ( panns . length - off ) ; for ( int i = off ; i < panns . length ; ++ i ) { AnnotationWriter aw = panns [ i ] ; AnnotationWriter last = null ; int n = 0 ; while ( aw != null ) { ++ n ; aw . visitEnd ( ) ; aw . prev = last ; last = aw ; aw = aw . next ; } out . putShort ( n ) ; aw = last ; while ( aw != null ) { out . putByteArray ( aw . bv . data , 0 , aw . bv . length ) ; aw = aw . prev ; } } }
|
Puts the given annotation lists into the given byte vector .
|
5,469
|
public static Type getType ( final Class c ) { if ( c . isPrimitive ( ) ) { if ( c == Integer . TYPE ) { return INT_TYPE ; } else if ( c == Void . TYPE ) { return VOID_TYPE ; } else if ( c == Boolean . TYPE ) { return BOOLEAN_TYPE ; } else if ( c == Byte . TYPE ) { return BYTE_TYPE ; } else if ( c == Character . TYPE ) { return CHAR_TYPE ; } else if ( c == Short . TYPE ) { return SHORT_TYPE ; } else if ( c == Double . TYPE ) { return DOUBLE_TYPE ; } else if ( c == Float . TYPE ) { return FLOAT_TYPE ; } else { return LONG_TYPE ; } } else { return getType ( getDescriptor ( c ) ) ; } }
|
Returns the Java type corresponding to the given class .
|
5,470
|
public static Type [ ] getArgumentTypes ( final Method method ) { Class [ ] classes = method . getParameterTypes ( ) ; Type [ ] types = new Type [ classes . length ] ; for ( int i = classes . length - 1 ; i >= 0 ; -- i ) { types [ i ] = getType ( classes [ i ] ) ; } return types ; }
|
Returns the Java types corresponding to the argument types of the given method .
|
5,471
|
public static Type getReturnType ( final String methodDescriptor ) { char [ ] buf = methodDescriptor . toCharArray ( ) ; return getType ( buf , methodDescriptor . indexOf ( ')' ) + 1 ) ; }
|
Returns the Java type corresponding to the return type of the given method descriptor .
|
5,472
|
public String getClassName ( ) { switch ( sort ) { case VOID : return "void" ; case BOOLEAN : return "boolean" ; case CHAR : return "char" ; case BYTE : return "byte" ; case SHORT : return "short" ; case INT : return "int" ; case FLOAT : return "float" ; case LONG : return "long" ; case DOUBLE : return "double" ; case ARRAY : StringBuffer b = new StringBuffer ( getElementType ( ) . getClassName ( ) ) ; for ( int i = getDimensions ( ) ; i > 0 ; -- i ) { b . append ( "[]" ) ; } return b . toString ( ) ; default : return new String ( buf , off , len ) . replace ( '/' , '.' ) ; } }
|
Returns the name of the class corresponding to this type .
|
5,473
|
private void getDescriptor ( final StringBuffer buf ) { switch ( sort ) { case VOID : buf . append ( 'V' ) ; return ; case BOOLEAN : buf . append ( 'Z' ) ; return ; case CHAR : buf . append ( 'C' ) ; return ; case BYTE : buf . append ( 'B' ) ; return ; case SHORT : buf . append ( 'S' ) ; return ; case INT : buf . append ( 'I' ) ; return ; case FLOAT : buf . append ( 'F' ) ; return ; case LONG : buf . append ( 'J' ) ; return ; case DOUBLE : buf . append ( 'D' ) ; return ; case ARRAY : buf . append ( this . buf , off , len ) ; return ; default : buf . append ( 'L' ) ; buf . append ( this . buf , off , len ) ; buf . append ( ';' ) ; } }
|
Appends the descriptor corresponding to this Java type to the given string buffer .
|
5,474
|
public int getOpcode ( final int opcode ) { if ( opcode == Opcodes . IALOAD || opcode == Opcodes . IASTORE ) { switch ( sort ) { case BOOLEAN : case BYTE : return opcode + 5 ; case CHAR : return opcode + 6 ; case SHORT : return opcode + 7 ; case INT : return opcode ; case FLOAT : return opcode + 2 ; case LONG : return opcode + 1 ; case DOUBLE : return opcode + 3 ; default : return opcode + 4 ; } } else { switch ( sort ) { case VOID : return opcode + 5 ; case BOOLEAN : case CHAR : case BYTE : case SHORT : case INT : return opcode ; case FLOAT : return opcode + 2 ; case LONG : return opcode + 1 ; case DOUBLE : return opcode + 3 ; default : return opcode + 4 ; } } }
|
Returns a JVM instruction opcode adapted to this Java type .
|
5,475
|
int getSize ( ) { int size = 8 ; if ( value != 0 ) { cw . newUTF8 ( "ConstantValue" ) ; size += 8 ; } if ( ( access & Opcodes . ACC_SYNTHETIC ) != 0 && ( cw . version & 0xffff ) < Opcodes . V1_5 ) { cw . newUTF8 ( "Synthetic" ) ; size += 6 ; } if ( ( access & Opcodes . ACC_DEPRECATED ) != 0 ) { cw . newUTF8 ( "Deprecated" ) ; size += 6 ; } if ( ClassReader . SIGNATURES && signature != 0 ) { cw . newUTF8 ( "Signature" ) ; size += 8 ; } if ( ClassReader . ANNOTATIONS && anns != null ) { cw . newUTF8 ( "RuntimeVisibleAnnotations" ) ; size += 8 + anns . getSize ( ) ; } if ( ClassReader . ANNOTATIONS && ianns != null ) { cw . newUTF8 ( "RuntimeInvisibleAnnotations" ) ; size += 8 + ianns . getSize ( ) ; } if ( attrs != null ) { size += attrs . getSize ( cw , null , 0 , - 1 , - 1 ) ; } return size ; }
|
Returns the size of this field .
|
5,476
|
void put ( final ByteVector out ) { out . putShort ( access ) . putShort ( name ) . putShort ( desc ) ; int attributeCount = 0 ; if ( value != 0 ) { ++ attributeCount ; } if ( ( access & Opcodes . ACC_SYNTHETIC ) != 0 && ( cw . version & 0xffff ) < Opcodes . V1_5 ) { ++ attributeCount ; } if ( ( access & Opcodes . ACC_DEPRECATED ) != 0 ) { ++ attributeCount ; } if ( ClassReader . SIGNATURES && signature != 0 ) { ++ attributeCount ; } if ( ClassReader . ANNOTATIONS && anns != null ) { ++ attributeCount ; } if ( ClassReader . ANNOTATIONS && ianns != null ) { ++ attributeCount ; } if ( attrs != null ) { attributeCount += attrs . getCount ( ) ; } out . putShort ( attributeCount ) ; if ( value != 0 ) { out . putShort ( cw . newUTF8 ( "ConstantValue" ) ) ; out . putInt ( 2 ) . putShort ( value ) ; } if ( ( access & Opcodes . ACC_SYNTHETIC ) != 0 && ( cw . version & 0xffff ) < Opcodes . V1_5 ) { out . putShort ( cw . newUTF8 ( "Synthetic" ) ) . putInt ( 0 ) ; } if ( ( access & Opcodes . ACC_DEPRECATED ) != 0 ) { out . putShort ( cw . newUTF8 ( "Deprecated" ) ) . putInt ( 0 ) ; } if ( ClassReader . SIGNATURES && signature != 0 ) { out . putShort ( cw . newUTF8 ( "Signature" ) ) ; out . putInt ( 2 ) . putShort ( signature ) ; } if ( ClassReader . ANNOTATIONS && anns != null ) { out . putShort ( cw . newUTF8 ( "RuntimeVisibleAnnotations" ) ) ; anns . put ( out ) ; } if ( ClassReader . ANNOTATIONS && ianns != null ) { out . putShort ( cw . newUTF8 ( "RuntimeInvisibleAnnotations" ) ) ; ianns . put ( out ) ; } if ( attrs != null ) { attrs . put ( cw , null , 0 , - 1 , - 1 , out ) ; } }
|
Puts the content of this field into the given byte vector .
|
5,477
|
static Class < ? > loadViewClass ( Context context , String name ) throws ClassNotFoundException { return context . getClassLoader ( ) . loadClass ( name ) . asSubclass ( View . class ) ; }
|
Loads class for the given class name .
|
5,478
|
static Class < ? > findViewClass ( Context context , String name ) throws ClassNotFoundException { if ( name . indexOf ( '.' ) >= 0 ) { return loadViewClass ( context , name ) ; } for ( String prefix : VIEW_CLASS_PREFIX_LIST ) { try { return loadViewClass ( context , prefix + name ) ; } catch ( ClassNotFoundException e ) { continue ; } } throw new ClassNotFoundException ( "Couldn't load View class for " + name ) ; }
|
Tries to load class using a predefined list of class prefixes for Android views .
|
5,479
|
private void scheduleAuthentication ( final int appId , final String bridgeId , final CallStatsHttp2Client httpClient ) { scheduler . schedule ( new Runnable ( ) { public void run ( ) { sendAsyncAuthenticationRequest ( appId , bridgeId , httpClient ) ; } } , authenticationRetryTimeout , TimeUnit . MILLISECONDS ) ; }
|
Schedule authentication .
|
5,480
|
public void startKeepAliveSender ( String authToken ) { this . token = authToken ; stopKeepAliveSender ( ) ; logger . info ( "Starting keepAlive Sender" ) ; future = scheduler . scheduleAtFixedRate ( new Runnable ( ) { public void run ( ) { sendKeepAliveBridgeMessage ( appId , bridgeId , token , httpClient ) ; } } , 0 , keepAliveInterval , TimeUnit . MILLISECONDS ) ; }
|
Start keep alive sender .
|
5,481
|
private void sendKeepAliveBridgeMessage ( int appId , String bridgeId , String token , final CallStatsHttp2Client httpClient ) { long apiTS = System . currentTimeMillis ( ) ; BridgeKeepAliveMessage message = new BridgeKeepAliveMessage ( bridgeId , apiTS ) ; String requestMessageString = gson . toJson ( message ) ; httpClient . sendBridgeAlive ( keepAliveEventUrl , token , requestMessageString , new CallStatsHttp2ResponseListener ( ) { public void onResponse ( Response response ) { int responseStatus = response . code ( ) ; BridgeKeepAliveResponse keepAliveResponse ; try { String responseString = response . body ( ) . string ( ) ; keepAliveResponse = gson . fromJson ( responseString , BridgeKeepAliveResponse . class ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } catch ( JsonSyntaxException e ) { logger . error ( "Json Syntax Exception " + e . getMessage ( ) , e ) ; e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } httpClient . setDisrupted ( false ) ; if ( responseStatus == CallStatsResponseStatus . RESPONSE_STATUS_SUCCESS ) { keepAliveStatusListener . onSuccess ( ) ; } else if ( responseStatus == CallStatsResponseStatus . INVALID_AUTHENTICATION_TOKEN ) { stopKeepAliveSender ( ) ; keepAliveStatusListener . onKeepAliveError ( CallStatsErrors . AUTH_ERROR , keepAliveResponse . getMsg ( ) ) ; } else { httpClient . setDisrupted ( true ) ; } } public void onFailure ( Exception e ) { logger . info ( "Response exception " + e . toString ( ) ) ; httpClient . setDisrupted ( true ) ; } } ) ; }
|
Send keep alive bridge message .
|
5,482
|
public void sendCallStatsBridgeStatusUpdate ( BridgeStatusInfo bridgeStatusInfo ) { if ( ! isInitialized ( ) ) { bridgeStatusInfoQueue . push ( bridgeStatusInfo ) ; return ; } long epoch = System . currentTimeMillis ( ) ; String token = getToken ( ) ; BridgeStatusUpdateMessage eventMessage = new BridgeStatusUpdateMessage ( bridgeId , epoch , bridgeStatusInfo ) ; String requestMessageString = gson . toJson ( eventMessage ) ; String url = "/" + appId + "/stats/bridge/status" ; httpClient . sendBridgeStatistics ( url , token , requestMessageString , new CallStatsHttp2ResponseListener ( ) { public void onResponse ( Response response ) { int responseStatus = response . code ( ) ; BridgeStatusUpdateResponse eventResponseMessage ; try { String responseString = response . body ( ) . string ( ) ; eventResponseMessage = gson . fromJson ( responseString , BridgeStatusUpdateResponse . class ) ; } catch ( IOException e ) { logger . error ( "IO Exception " + e . getMessage ( ) , e ) ; throw new RuntimeException ( e ) ; } catch ( JsonSyntaxException e ) { logger . error ( "Json Syntax Exception " + e . getMessage ( ) , e ) ; e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } logger . debug ( "BridgeStatusUpdate Response " + eventResponseMessage . getStatus ( ) + ":" + eventResponseMessage . getMsg ( ) ) ; httpClient . setDisrupted ( false ) ; if ( responseStatus == CallStatsResponseStatus . RESPONSE_STATUS_SUCCESS ) { sendCallStatsBridgeStatusUpdateFromQueue ( ) ; } else if ( responseStatus == CallStatsResponseStatus . INVALID_AUTHENTICATION_TOKEN ) { bridgeKeepAliveManager . stopKeepAliveSender ( ) ; authenticator . doAuthentication ( ) ; } else { httpClient . setDisrupted ( true ) ; } } public void onFailure ( Exception e ) { logger . error ( "Response exception" + e . getMessage ( ) , e ) ; httpClient . setDisrupted ( true ) ; } } ) ; }
|
Send call stats bridge status update .
|
5,483
|
private PrivateKey readEcPrivateKey ( String fileName ) throws InvalidKeySpecException , NoSuchAlgorithmException , IOException , NoSuchProviderException { StringBuilder sb = new StringBuilder ( ) ; BufferedReader br = new BufferedReader ( new FileReader ( fileName ) ) ; try { char [ ] cbuf = new char [ 1024 ] ; for ( int i = 0 ; i <= 10 * 1024 ; i ++ ) { if ( ! br . ready ( ) ) break ; int len = br . read ( cbuf , i * 1024 , 1024 ) ; sb . append ( cbuf , 0 , len ) ; } if ( br . ready ( ) ) { throw new IndexOutOfBoundsException ( "JWK file larger than 10MB" ) ; } Type mapType = new TypeToken < Map < String , String > > ( ) { } . getType ( ) ; Map < String , String > son = new Gson ( ) . fromJson ( sb . toString ( ) , mapType ) ; try { @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) EllipticCurveJsonWebKey jwk = new EllipticCurveJsonWebKey ( ( Map < String , Object > ) ( Map ) son ) ; Base64Encoder enc = new Base64Encoder ( ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; enc . encode ( jwk . getPrivateKey ( ) . getEncoded ( ) , 0 , jwk . getPrivateKey ( ) . getEncoded ( ) . length , os ) ; return jwk . getPrivateKey ( ) ; } catch ( JoseException e1 ) { e1 . printStackTrace ( ) ; } return null ; } finally { br . close ( ) ; } }
|
Reads JWK into PrivateKEy instance
|
5,484
|
public void setLocalID ( String userID ) { try { this . localID = URLEncoder . encode ( userID , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { logger . error ( "UnsupportedEncodingException " + e . getMessage ( ) , e ) ; e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } ; }
|
Sets the bridge id .
|
5,485
|
public static final int daysBetween ( Date early , Date late ) { java . util . GregorianCalendar calst = new java . util . GregorianCalendar ( ) ; java . util . GregorianCalendar caled = new java . util . GregorianCalendar ( ) ; calst . setTime ( early ) ; caled . setTime ( late ) ; calst . set ( java . util . GregorianCalendar . HOUR_OF_DAY , 0 ) ; calst . set ( java . util . GregorianCalendar . MINUTE , 0 ) ; calst . set ( java . util . GregorianCalendar . SECOND , 0 ) ; caled . set ( java . util . GregorianCalendar . HOUR_OF_DAY , 0 ) ; caled . set ( java . util . GregorianCalendar . MINUTE , 0 ) ; caled . set ( java . util . GregorianCalendar . SECOND , 0 ) ; int days = ( ( int ) ( caled . getTime ( ) . getTime ( ) / 1000 / 3600 / 24 ) - ( int ) ( calst . getTime ( ) . getTime ( ) / 1000 / 3600 / 24 ) ) ; return days ; }
|
Returns the days between two dates . Positive values indicate that the second date is after the first and negative values indicate well the opposite . Relying on specific times is problematic .
|
5,486
|
public String toXml ( Object root , String encoding ) { try { StringWriter writer = new StringWriter ( ) ; createMarshaller ( encoding ) . marshal ( root , writer ) ; return writer . toString ( ) ; } catch ( JAXBException e ) { throw new RuntimeException ( e ) ; } }
|
Java Object - > Xml .
|
5,487
|
public UiBinder < ? , ? > getFake ( final Class < ? > type ) { return ( UiBinder < ? , ? > ) Proxy . newProxyInstance ( FakeUiBinderProvider . class . getClassLoader ( ) , new Class < ? > [ ] { type } , new InvocationHandler ( ) { public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Exception { for ( Field field : getAllFields ( args [ 0 ] . getClass ( ) ) ) { if ( field . isAnnotationPresent ( UiField . class ) && ! field . getAnnotation ( UiField . class ) . provided ( ) ) { field . setAccessible ( true ) ; field . set ( args [ 0 ] , GWT . create ( field . getType ( ) ) ) ; } } return GWT . create ( getUiRootType ( type ) ) ; } } ) ; }
|
Returns a new instance of FakeUiBinder that implements the given interface . This is accomplished by returning a dynamic proxy object that delegates calls to a backing FakeUiBinder .
|
5,488
|
@ SuppressWarnings ( "unchecked" ) private < T > T createFakeResource ( Class < T > type , final String name ) { return ( T ) Proxy . newProxyInstance ( FakeClientBundleProvider . class . getClassLoader ( ) , new Class < ? > [ ] { type } , new InvocationHandler ( ) { public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Exception { Class < ? > returnType = method . getReturnType ( ) ; if ( returnType == String . class ) { return name ; } else if ( returnType == SafeHtml . class ) { return SafeHtmlUtils . fromTrustedString ( name ) ; } else if ( returnType == SafeUri . class ) { return UriUtils . fromTrustedString ( name ) ; } else if ( returnType == boolean . class ) { return false ; } else if ( returnType == int . class ) { return 0 ; } else if ( method . getParameterTypes ( ) [ 0 ] == ResourceCallback . class ) { Class < ? > resourceType = ( Class < ? > ) ( ( ParameterizedType ) args [ 0 ] . getClass ( ) . getGenericInterfaces ( ) [ 0 ] ) . getActualTypeArguments ( ) [ 0 ] ; ( ( ResourceCallback < ResourcePrototype > ) args [ 0 ] ) . onSuccess ( ( ResourcePrototype ) createFakeResource ( resourceType , name ) ) ; return null ; } else { throw new IllegalArgumentException ( "Unexpected return type for method " + method . getName ( ) ) ; } } } ) ; }
|
Creates a fake resource class that returns its own name where possible .
|
5,489
|
public static boolean shouldStub ( CtMethod method , Collection < Class < ? > > classesToStub ) { if ( STUB_METHODS . containsKey ( new ClassAndMethod ( method . getDeclaringClass ( ) . getName ( ) , method . getName ( ) ) ) ) { return true ; } for ( Class < ? > clazz : classesToStub ) { if ( declaringClassIs ( method , clazz ) && ( method . getModifiers ( ) & Modifier . ABSTRACT ) == 0 ) { return true ; } } if ( ( method . getModifiers ( ) & Modifier . NATIVE ) != 0 ) { return true ; } return false ; }
|
Returns whether the behavior of the given method should be replaced .
|
5,490
|
public static Object invoke ( Class < ? > returnType , String className , String methodName ) { if ( STUB_METHODS . containsKey ( new ClassAndMethod ( className , methodName ) ) ) { return STUB_METHODS . get ( new ClassAndMethod ( className , methodName ) ) . invoke ( ) ; } if ( returnType == String . class ) { return "" ; } else if ( returnType == Boolean . class ) { return false ; } else if ( returnType == Byte . class ) { return ( byte ) 0 ; } else if ( returnType == Character . class ) { return ( char ) 0 ; } else if ( returnType == Double . class ) { return ( double ) 0 ; } else if ( returnType == Integer . class ) { return ( int ) 0 ; } else if ( returnType == Float . class ) { return ( float ) 0 ; } else if ( returnType == Long . class ) { return ( long ) 0 ; } else if ( returnType == Short . class ) { return ( short ) 0 ; } else { return Mockito . mock ( returnType , new ReturnsCustomMocks ( ) ) ; } }
|
Invokes the stubbed behavior of the given method .
|
5,491
|
public static CompilationFailedException create ( final IMessage [ ] errors ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "AJC compiler errors:" ) . append ( LINE_SEPARATOR ) ; for ( final IMessage error : errors ) { sb . append ( error . toString ( ) ) . append ( LINE_SEPARATOR ) ; } return new CompilationFailedException ( sb . toString ( ) ) ; }
|
Factory method which creates a CompilationFailedException from the supplied AJC IMessages .
|
5,492
|
private void writeDocument ( Document document , File file ) throws TransformerException , FileNotFoundException { document . normalize ( ) ; DOMSource source = new DOMSource ( document ) ; StreamResult result = new StreamResult ( new FileOutputStream ( file ) ) ; Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . transform ( source , result ) ; }
|
write document to the file
|
5,493
|
@ SuppressWarnings ( "unchecked" ) public static String createClassPath ( MavenProject project , List < Artifact > pluginArtifacts , List < String > outDirs ) { String cp = new String ( ) ; Set < Artifact > classPathElements = Collections . synchronizedSet ( new LinkedHashSet < Artifact > ( ) ) ; Set < Artifact > dependencyArtifacts = project . getDependencyArtifacts ( ) ; classPathElements . addAll ( dependencyArtifacts == null ? Collections . < Artifact > emptySet ( ) : dependencyArtifacts ) ; classPathElements . addAll ( project . getArtifacts ( ) ) ; classPathElements . addAll ( pluginArtifacts == null ? Collections . < Artifact > emptySet ( ) : pluginArtifacts ) ; for ( Artifact classPathElement : classPathElements ) { File artifact = classPathElement . getFile ( ) ; if ( null != artifact ) { String type = classPathElement . getType ( ) ; if ( ! type . equals ( "pom" ) ) { cp += classPathElement . getFile ( ) . getAbsolutePath ( ) ; cp += File . pathSeparatorChar ; } } } Iterator < String > outIter = outDirs . iterator ( ) ; while ( outIter . hasNext ( ) ) { cp += outIter . next ( ) ; cp += File . pathSeparatorChar ; } if ( cp . endsWith ( "" + File . pathSeparatorChar ) ) { cp = cp . substring ( 0 , cp . length ( ) - 1 ) ; } cp = StringUtils . replace ( cp , "//" , "/" ) ; return cp ; }
|
Constructs AspectJ compiler classpath string
|
5,494
|
public static Set < String > getBuildFilesForAjdtFile ( String ajdtBuildDefFile , File basedir ) throws MojoExecutionException { Set < String > result = new LinkedHashSet < String > ( ) ; Properties ajdtBuildProperties = new Properties ( ) ; try { ajdtBuildProperties . load ( new FileInputStream ( new File ( basedir , ajdtBuildDefFile ) ) ) ; } catch ( FileNotFoundException e ) { throw new MojoExecutionException ( "Build properties file specified not found" , e ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "IO Error reading build properties file specified" , e ) ; } result . addAll ( resolveIncludeExcludeString ( ajdtBuildProperties . getProperty ( "src.includes" ) , basedir ) ) ; Set < String > exludes = resolveIncludeExcludeString ( ajdtBuildProperties . getProperty ( "src.excludes" ) , basedir ) ; result . removeAll ( exludes ) ; return result ; }
|
Based on a AJDT build properties file resolves the combination of all include and exclude statements and returns a set of all the files to be compiled and weaved .
|
5,495
|
public static Set < String > getBuildFilesForSourceDirs ( List < String > sourceDirs , String [ ] includes , String [ ] excludes ) throws MojoExecutionException { Set < String > result = new LinkedHashSet < String > ( ) ; for ( String sourceDir : sourceDirs ) { try { if ( FileUtils . fileExists ( sourceDir ) ) { result . addAll ( FileUtils . getFileNames ( new File ( sourceDir ) , ( null == includes || 0 == includes . length ) ? DEFAULT_INCLUDES : getAsCsv ( includes ) , ( null == excludes || 0 == excludes . length ) ? DEFAULT_EXCLUDES : getAsCsv ( excludes ) , true ) ) ; } } catch ( IOException e ) { throw new MojoExecutionException ( "IO Error resolving sourcedirs" , e ) ; } } return result ; }
|
Based on a set of sourcedirs apply include and exclude statements and returns a set of all the files to be compiled and weaved .
|
5,496
|
public static Set < String > getWeaveSourceFiles ( String [ ] weaveDirs ) throws MojoExecutionException { Set < String > result = new HashSet < String > ( ) ; for ( int i = 0 ; i < weaveDirs . length ; i ++ ) { String weaveDir = weaveDirs [ i ] ; if ( FileUtils . fileExists ( weaveDir ) ) { try { result . addAll ( FileUtils . getFileNames ( new File ( weaveDir ) , "**/*.class" , DEFAULT_EXCLUDES , true ) ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "IO Error resolving weavedirs" , e ) ; } } } return result ; }
|
Based on a set of weavedirs returns a set of all the files to be weaved .
|
5,497
|
public static List < String > readBuildConfigFile ( String fileName , File outputDir ) throws IOException { List < String > arguments = new ArrayList < String > ( ) ; File argFile = new File ( outputDir , fileName ) ; if ( FileUtils . fileExists ( argFile . getAbsolutePath ( ) ) ) { FileReader reader = new FileReader ( argFile ) ; BufferedReader bufRead = new BufferedReader ( reader ) ; String line = null ; do { line = bufRead . readLine ( ) ; if ( null != line ) { arguments . add ( line ) ; } } while ( null != line ) ; } return arguments ; }
|
Reads a build config file and returns the List of all compiler arguments .
|
5,498
|
protected static String getAsCsv ( String [ ] strings ) { String csv = "" ; if ( null != strings ) { for ( int i = 0 ; i < strings . length ; i ++ ) { csv += strings [ i ] ; if ( i < ( strings . length - 1 ) ) { csv += "," ; } } } return csv ; }
|
Convert a string array to a comma separated list
|
5,499
|
protected static Set < String > resolveIncludeExcludeString ( String input , File basedir ) throws MojoExecutionException { Set < String > inclExlSet = new LinkedHashSet < String > ( ) ; try { if ( null == input || input . trim ( ) . equals ( "" ) ) { return inclExlSet ; } String [ ] elements = input . split ( "," ) ; if ( null != elements ) { for ( int i = 0 ; i < elements . length ; i ++ ) { String element = elements [ i ] ; if ( element . endsWith ( ".java" ) || element . endsWith ( ".aj" ) ) { inclExlSet . addAll ( FileUtils . getFileNames ( basedir , element , "" , true ) ) ; } else { File lookupBaseDir = new File ( basedir , element ) ; if ( FileUtils . fileExists ( lookupBaseDir . getAbsolutePath ( ) ) ) { inclExlSet . addAll ( FileUtils . getFileNames ( lookupBaseDir , DEFAULT_INCLUDES , "" , true ) ) ; } } } } } catch ( IOException e ) { throw new MojoExecutionException ( "Could not resolve java or aspect sources to compile" , e ) ; } return inclExlSet ; }
|
Helper method to find all . java or . aj files specified by the includeString . The includeString is a comma separated list over files or directories relative to the specified basedir . Examples of correct listings
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.