idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
11,200
public static String stringFor ( int m ) { switch ( m ) { case CUFFT_SUCCESS : return "CUFFT_SUCCESS" ; case CUFFT_INVALID_PLAN : return "CUFFT_INVALID_PLAN" ; case CUFFT_ALLOC_FAILED : return "CUFFT_ALLOC_FAILED" ; case CUFFT_INVALID_TYPE : return "CUFFT_INVALID_TYPE" ; case CUFFT_INVALID_VALUE : return "CUFFT_INVALID_VALUE" ; case CUFFT_INTERNAL_ERROR : return "CUFFT_INTERNAL_ERROR" ; case CUFFT_EXEC_FAILED : return "CUFFT_EXEC_FAILED" ; case CUFFT_SETUP_FAILED : return "CUFFT_SETUP_FAILED" ; case CUFFT_INVALID_SIZE : return "CUFFT_INVALID_SIZE" ; case CUFFT_UNALIGNED_DATA : return "CUFFT_UNALIGNED_DATA" ; case CUFFT_INCOMPLETE_PARAMETER_LIST : return "CUFFT_INCOMPLETE_PARAMETER_LIST" ; case CUFFT_INVALID_DEVICE : return "CUFFT_INVALID_DEVICE" ; case CUFFT_PARSE_ERROR : return "CUFFT_PARSE_ERROR" ; case CUFFT_NO_WORKSPACE : return "CUFFT_NO_WORKSPACE" ; case CUFFT_NOT_IMPLEMENTED : return "CUFFT_NOT_IMPLEMENTED" ; case CUFFT_LICENSE_ERROR : return "CUFFT_LICENSE_ERROR" ; case CUFFT_NOT_SUPPORTED : return "CUFFT_NOT_SUPPORTED" ; case JCUFFT_INTERNAL_ERROR : return "JCUFFT_INTERNAL_ERROR" ; } return "INVALID cufftResult: " + m ; }
Returns the String identifying the given cufftResult
480
9
11,201
protected SocialProfile parseProfile ( Map < String , Object > props ) { if ( ! props . containsKey ( "id" ) ) { throw new IllegalArgumentException ( "No id in profile" ) ; } SocialProfile profile = SocialProfile . with ( props ) . displayName ( "name" ) . first ( "first_name" ) . last ( "last_name" ) . id ( "id" ) . username ( "username" ) . profileUrl ( "link" ) . build ( ) ; profile . setThumbnailUrl ( getBaseUrl ( ) + "/" + profile . getId ( ) + "/picture" ) ; return profile ; }
Property names for Facebook - Override to customize
140
9
11,202
private void parsePackageClasses ( String name , List < JavaFileObject > files , ListBuffer < JCCompilationUnit > trees , List < String > excludedPackages ) throws IOException { if ( excludedPackages . contains ( name ) ) { return ; } docenv . notice ( "main.Loading_source_files_for_package" , name ) ; if ( files == null ) { Location location = docenv . fileManager . hasLocation ( StandardLocation . SOURCE_PATH ) ? StandardLocation . SOURCE_PATH : StandardLocation . CLASS_PATH ; ListBuffer < JavaFileObject > lb = new ListBuffer < JavaFileObject > ( ) ; for ( JavaFileObject fo : docenv . fileManager . list ( location , name , EnumSet . of ( JavaFileObject . Kind . SOURCE ) , false ) ) { String binaryName = docenv . fileManager . inferBinaryName ( location , fo ) ; String simpleName = getSimpleName ( binaryName ) ; if ( isValidClassName ( simpleName ) ) { lb . append ( fo ) ; } } files = lb . toList ( ) ; } if ( files . nonEmpty ( ) ) { for ( JavaFileObject fo : files ) { parse ( fo , trees , false ) ; } } else { messager . warning ( Messager . NOPOS , "main.no_source_files_for_package" , name . replace ( File . separatorChar , ' ' ) ) ; } }
search all directories in path for subdirectory name . Add all . java files found in such a directory to args .
319
23
11,203
private static boolean isValidJavaClassFile ( String file ) { if ( ! file . endsWith ( ".class" ) ) return false ; String clazzName = file . substring ( 0 , file . length ( ) - ".class" . length ( ) ) ; return isValidClassName ( clazzName ) ; }
Return true if given file name is a valid class file name .
68
13
11,204
public void enter ( Symbol sym , Scope s , Scope origin , boolean staticallyImported ) { Assert . check ( shared == 0 ) ; if ( nelems * 3 >= hashMask * 2 ) dble ( ) ; int hash = getIndex ( sym . name ) ; Entry old = table [ hash ] ; if ( old == null ) { old = sentinel ; nelems ++ ; } Entry e = makeEntry ( sym , old , elems , s , origin , staticallyImported ) ; table [ hash ] = e ; elems = e ; //notify listeners for ( List < ScopeListener > l = listeners ; l . nonEmpty ( ) ; l = l . tail ) { l . head . symbolAdded ( sym , this ) ; } }
Enter symbol sym in this scope but mark that it comes from given scope s accessed through origin . The last two arguments are only used in import scopes .
159
31
11,205
@ Override public void reportDependence ( Symbol from , Symbol to ) { // Capture dependencies between the packages. deps . collect ( from . packge ( ) . fullname , to . packge ( ) . fullname ) ; }
Collect dependencies in the enclosing class
50
7
11,206
public void put ( Object tree , int flags , int startPc , int endPc ) { entries . append ( new CRTEntry ( tree , flags , startPc , endPc ) ) ; }
Create a new CRTEntry and add it to the entries .
46
14
11,207
public int writeCRT ( ByteBuffer databuf , Position . LineMap lineMap , Log log ) { int crtEntries = 0 ; // compute source positions for the method new SourceComputer ( ) . csp ( methodTree ) ; for ( List < CRTEntry > l = entries . toList ( ) ; l . nonEmpty ( ) ; l = l . tail ) { CRTEntry entry = l . head ; // eliminate entries that do not produce bytecodes: // for example, empty blocks and statements if ( entry . startPc == entry . endPc ) continue ; SourceRange pos = positions . get ( entry . tree ) ; Assert . checkNonNull ( pos , "CRT: tree source positions are undefined" ) ; if ( ( pos . startPos == Position . NOPOS ) || ( pos . endPos == Position . NOPOS ) ) continue ; if ( crtDebug ) { System . out . println ( "Tree: " + entry . tree + ", type:" + getTypes ( entry . flags ) ) ; System . out . print ( "Start: pos = " + pos . startPos + ", pc = " + entry . startPc ) ; } // encode startPos into line/column representation int startPos = encodePosition ( pos . startPos , lineMap , log ) ; if ( startPos == Position . NOPOS ) continue ; if ( crtDebug ) { System . out . print ( "End: pos = " + pos . endPos + ", pc = " + ( entry . endPc - 1 ) ) ; } // encode endPos into line/column representation int endPos = encodePosition ( pos . endPos , lineMap , log ) ; if ( endPos == Position . NOPOS ) continue ; // write attribute databuf . appendChar ( entry . startPc ) ; // 'endPc - 1' because endPc actually points to start of the next command databuf . appendChar ( entry . endPc - 1 ) ; databuf . appendInt ( startPos ) ; databuf . appendInt ( endPos ) ; databuf . appendChar ( entry . flags ) ; crtEntries ++ ; } return crtEntries ; }
Compute source positions and write CRT to the databuf .
480
14
11,208
private String getTypes ( int flags ) { String types = "" ; if ( ( flags & CRT_STATEMENT ) != 0 ) types += " CRT_STATEMENT" ; if ( ( flags & CRT_BLOCK ) != 0 ) types += " CRT_BLOCK" ; if ( ( flags & CRT_ASSIGNMENT ) != 0 ) types += " CRT_ASSIGNMENT" ; if ( ( flags & CRT_FLOW_CONTROLLER ) != 0 ) types += " CRT_FLOW_CONTROLLER" ; if ( ( flags & CRT_FLOW_TARGET ) != 0 ) types += " CRT_FLOW_TARGET" ; if ( ( flags & CRT_INVOKE ) != 0 ) types += " CRT_INVOKE" ; if ( ( flags & CRT_CREATE ) != 0 ) types += " CRT_CREATE" ; if ( ( flags & CRT_BRANCH_TRUE ) != 0 ) types += " CRT_BRANCH_TRUE" ; if ( ( flags & CRT_BRANCH_FALSE ) != 0 ) types += " CRT_BRANCH_FALSE" ; return types ; }
Return string describing flags enabled .
272
6
11,209
@ GET @ Path ( "{id}" ) @ RolesAllowed ( { "ROLE_ADMIN" } ) public Response read ( @ PathParam ( "id" ) Long id ) { checkNotNull ( id ) ; return Response . ok ( userService . getById ( id ) ) . build ( ) ; }
Get details for a single user .
68
7
11,210
@ GET @ Path ( "search" ) @ RolesAllowed ( { "ROLE_ADMIN" } ) public Response search ( @ QueryParam ( "email" ) String email , @ QueryParam ( "username" ) String username , @ QueryParam ( "pageSize" ) @ DefaultValue ( "10" ) int pageSize , @ QueryParam ( "cursorKey" ) String cursorKey ) { final CursorPage < DUser > page ; if ( null != email ) { page = userService . findMatchingUsersByEmail ( email , pageSize , cursorKey ) ; } else if ( null != username ) { page = userService . findMatchingUsersByUserName ( username , pageSize , cursorKey ) ; } else { throw new BadRequestRestException ( "No search key provided" ) ; } return Response . ok ( page ) . build ( ) ; }
Search for users with matching email or username .
188
9
11,211
@ GET @ RolesAllowed ( { "ROLE_ADMIN" } ) public Response readPage ( @ QueryParam ( "pageSize" ) @ DefaultValue ( "10" ) int pageSize , @ QueryParam ( "cursorKey" ) String cursorKey ) { CursorPage < DUser > page = userService . readPage ( pageSize , cursorKey ) ; return Response . ok ( page ) . build ( ) ; }
Get a page of users .
94
6
11,212
@ POST @ Path ( "{id}/username" ) @ RolesAllowed ( { "ROLE_ADMIN" } ) public Response changeUsername ( @ PathParam ( "id" ) Long id , UsernameRequest usernameRequest ) { checkUsernameFormat ( usernameRequest . username ) ; userService . changeUsername ( id , usernameRequest . getUsername ( ) ) ; return Response . ok ( id ) . build ( ) ; }
Change a users username . The username must be unique
94
10
11,213
@ POST @ Path ( "{id}/password" ) @ PermitAll public Response changePassword ( @ PathParam ( "id" ) Long userId , PasswordRequest request ) { checkNotNull ( userId ) ; checkNotNull ( request . getToken ( ) ) ; checkPasswordFormat ( request . getNewPassword ( ) ) ; boolean isSuccess = userService . confirmResetPasswordUsingToken ( userId , request . getNewPassword ( ) , request . getToken ( ) ) ; return isSuccess ? Response . noContent ( ) . build ( ) : Response . status ( Response . Status . BAD_REQUEST ) . build ( ) ; }
Change password using a temporary token . Used during password reset flow .
138
13
11,214
@ POST @ Path ( "password/reset" ) @ PermitAll public Response resetPassword ( PasswordRequest request ) { checkNotNull ( request . getEmail ( ) ) ; userService . resetPassword ( request . getEmail ( ) ) ; return Response . noContent ( ) . build ( ) ; }
Reset user password by sending out a reset email .
64
11
11,215
@ POST @ Path ( "{id}/account/confirm" ) @ PermitAll public Response confirmAccount ( @ PathParam ( "id" ) Long userId , AccountRequest request ) { checkNotNull ( userId ) ; checkNotNull ( request . getToken ( ) ) ; boolean isSuccess = userService . confirmAccountUsingToken ( userId , request . getToken ( ) ) ; return isSuccess ? Response . noContent ( ) . build ( ) : Response . status ( Response . Status . BAD_REQUEST ) . build ( ) ; }
Confirm a newly create account using a temporary token .
118
11
11,216
@ POST @ Path ( "{id}/account/resend" ) @ PermitAll public Response resendVerifyAccountEmail ( @ PathParam ( "id" ) Long userId ) { checkNotNull ( userId ) ; boolean isSuccess = userService . resendVerifyAccountEmail ( userId ) ; return isSuccess ? Response . noContent ( ) . build ( ) : Response . status ( Response . Status . BAD_REQUEST ) . build ( ) ; }
Resend account verification email .
101
6
11,217
@ POST @ Path ( "{id}/email" ) @ RolesAllowed ( { "ROLE_ADMIN" } ) public Response changeEmail ( @ PathParam ( "id" ) Long userId , EmailRequest request ) { checkNotNull ( userId ) ; checkEmailFormat ( request . getEmail ( ) ) ; boolean isSuccess = userService . changeEmailAddress ( userId , request . getEmail ( ) ) ; return isSuccess ? Response . noContent ( ) . build ( ) : Response . status ( Response . Status . BAD_REQUEST ) . build ( ) ; }
Admin changing a users email .
126
6
11,218
@ POST @ Path ( "{id}/email/confirm" ) @ PermitAll public Response confirmChangeEmail ( @ PathParam ( "id" ) Long userId , EmailRequest request ) { checkNotNull ( userId ) ; checkNotNull ( request . getToken ( ) ) ; boolean isSuccess = userService . confirmEmailAddressChangeUsingToken ( userId , request . getToken ( ) ) ; return isSuccess ? Response . noContent ( ) . build ( ) : Response . status ( Response . Status . BAD_REQUEST ) . build ( ) ; }
User confirm changing email . The token is verified and the temporary stored email will not be permanently saved as the users email .
121
24
11,219
public static Protocol createInstance ( ProtocolVersion version , SocketManager socketManager ) { switch ( version ) { case _63 : return new Protocol63 ( socketManager ) ; case _72 : return new Protocol72 ( socketManager ) ; case _73 : return new Protocol73 ( socketManager ) ; case _74 : return new Protocol74 ( socketManager ) ; default : throw new IllegalArgumentException ( "Unknown protocol version: " + version ) ; } }
Create a new protocol instance . This instance cannot be used until the associated socket manager is connected .
94
19
11,220
public void prepareParameters ( Map < String , Object > extra ) { if ( paramConfig == null ) return ; for ( ParamConfig param : paramConfig ) { param . prepareParameter ( extra ) ; } }
Prepares the parameters for the report . This populates the Combo and ManyCombo box options if there is a groovy or report backing the data .
43
31
11,221
private FieldDoc getFieldDoc ( Configuration config , Tag tag , String name ) { if ( name == null || name . length ( ) == 0 ) { //Base case: no label. if ( tag . holder ( ) instanceof FieldDoc ) { return ( FieldDoc ) tag . holder ( ) ; } else { // If the value tag does not specify a parameter which is a valid field and // it is not used within the comments of a valid field, return null. return null ; } } StringTokenizer st = new StringTokenizer ( name , "#" ) ; String memberName = null ; ClassDoc cd = null ; if ( st . countTokens ( ) == 1 ) { //Case 2: @value in same class. Doc holder = tag . holder ( ) ; if ( holder instanceof MemberDoc ) { cd = ( ( MemberDoc ) holder ) . containingClass ( ) ; } else if ( holder instanceof ClassDoc ) { cd = ( ClassDoc ) holder ; } memberName = st . nextToken ( ) ; } else { //Case 3: @value in different class. cd = config . root . classNamed ( st . nextToken ( ) ) ; memberName = st . nextToken ( ) ; } if ( cd == null ) { return null ; } FieldDoc [ ] fields = cd . fields ( ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { if ( fields [ i ] . name ( ) . equals ( memberName ) ) { return fields [ i ] ; } } return null ; }
Given the name of the field return the corresponding FieldDoc . Return null due to invalid use of value tag if the name is null or empty string and if the value tag is not used on a field .
328
41
11,222
@ Constructed public void constructed ( ) { Context context = factory . enterContext ( ) ; try { scope = new ImporterTopLevel ( context ) ; } finally { Context . exit ( ) ; } Container container = Jaguar . component ( Container . class ) ; Object store = container . component ( container . contexts ( ) . get ( Application . class ) ) . store ( ) ; if ( store instanceof ServletContext ) { org . eiichiro . bootleg . Configuration configuration = new DefaultConfiguration ( ) ; configuration . init ( ( ServletContext ) store ) ; this . configuration = configuration ; } }
Sets up Mozilla Rhino s script scope . If the application is running on a Servlet container this method instantiates and initializes the Bootleg s default configuration internally .
128
34
11,223
@ Activated public void activated ( ) { logger . info ( "Importing core packages ['org.eiichiro.gig', 'org.eiichiro.bootleg', 'org.eiichiro.jaguar', 'org.eiichiro.jaguar.deployment'] into JavaScript context" ) ; Context context = factory . enterContext ( ) ; try { context . evaluateString ( scope , "importPackage(Packages.org.eiichiro.gig)" , Configuration . class . getSimpleName ( ) , 146 , null ) ; context . evaluateString ( scope , "importPackage(Packages.org.eiichiro.bootleg)" , Configuration . class . getSimpleName ( ) , 147 , null ) ; context . evaluateString ( scope , "importPackage(Packages.org.eiichiro.jaguar)" , Configuration . class . getSimpleName ( ) , 148 , null ) ; context . evaluateString ( scope , "importPackage(Packages.org.eiichiro.jaguar.deployment)" , Configuration . class . getSimpleName ( ) , 149 , null ) ; } finally { Context . exit ( ) ; } load ( COMPONENTS_JS ) ; load ( ROUTING_JS ) ; load ( SETTINGS_JS ) ; }
Attempts to load pre - defined configuration files .
282
9
11,224
public void load ( String file ) { Context context = factory . enterContext ( ) ; try { URL url = Thread . currentThread ( ) . getContextClassLoader ( ) . getResource ( file ) ; if ( url == null ) { logger . debug ( "Configuration [" + file + "] does not exist" ) ; return ; } File f = new File ( url . getPath ( ) ) ; if ( f . exists ( ) ) { logger . info ( "Loading configuration [" + file + "]" ) ; context . evaluateReader ( scope , new FileReader ( f ) , file . substring ( file . lastIndexOf ( "/" ) + 1 ) , 1 , null ) ; } } catch ( Exception e ) { logger . error ( "Failed to load configuration [" + file + "]" , e ) ; throw new UncheckedException ( e ) ; } finally { Context . exit ( ) ; } }
Loads the specified configuration file written in JavaScript .
194
10
11,225
public < T > void set ( String key , T value ) { Preconditions . checkArgument ( key != null && ! key . isEmpty ( ) , "Parameter 'key' must not be [" + key + "]" ) ; values . put ( key , value ) ; scope . put ( key , scope , value ) ; }
Sets the specified configuration setting with the specified key .
71
11
11,226
protected static char calcChecksumChar ( @ Nonnull final String sMsg , @ Nonnegative final int nLength ) { ValueEnforcer . notNull ( sMsg , "Msg" ) ; ValueEnforcer . isBetweenInclusive ( nLength , "Length" , 0 , sMsg . length ( ) ) ; return asChar ( calcChecksum ( sMsg . toCharArray ( ) , nLength ) ) ; }
Calculates the check character for a given message
91
10
11,227
protected char scanSurrogates ( ) { if ( surrogatesSupported && Character . isHighSurrogate ( ch ) ) { char high = ch ; scanChar ( ) ; if ( Character . isLowSurrogate ( ch ) ) { return high ; } ch = high ; } return 0 ; }
Scan surrogate pairs . If ch is a high surrogate and the next character is a low surrogate then put the low surrogate in ch and return the high surrogate . otherwise just return 0 .
64
36
11,228
@ Nonnull public static EValidity validateMessage ( @ Nullable final String sMsg ) { final int nLen = StringHelper . getLength ( sMsg ) ; if ( nLen >= 7 && nLen <= 8 ) if ( AbstractUPCEAN . validateMessage ( sMsg ) . isValid ( ) ) return EValidity . VALID ; return EValidity . INVALID ; }
Validates a EAN - 8 message . The method throws IllegalArgumentExceptions if an invalid message is passed .
84
24
11,229
protected String makeMethodString ( ExecutableElement e ) { StringBuilder result = new StringBuilder ( ) ; for ( Modifier modifier : e . getModifiers ( ) ) { result . append ( modifier . toString ( ) ) ; result . append ( " " ) ; } result . append ( e . getReturnType ( ) . toString ( ) ) ; result . append ( " " ) ; result . append ( e . toString ( ) ) ; List < ? extends TypeMirror > thrownTypes = e . getThrownTypes ( ) ; if ( ! thrownTypes . isEmpty ( ) ) { result . append ( " throws " ) ; for ( Iterator < ? extends TypeMirror > iterator = thrownTypes . iterator ( ) ; iterator . hasNext ( ) ; ) { TypeMirror typeMirror = iterator . next ( ) ; result . append ( typeMirror . toString ( ) ) ; if ( iterator . hasNext ( ) ) { result . append ( ", " ) ; } } } return result . toString ( ) ; }
Creates a String representation of a method element with everything necessary to track all public aspects of it in an API .
223
23
11,230
protected String makeVariableString ( VariableElement e ) { StringBuilder result = new StringBuilder ( ) ; for ( Modifier modifier : e . getModifiers ( ) ) { result . append ( modifier . toString ( ) ) ; result . append ( " " ) ; } result . append ( e . asType ( ) . toString ( ) ) ; result . append ( " " ) ; result . append ( e . toString ( ) ) ; Object value = e . getConstantValue ( ) ; if ( value != null ) { result . append ( " = " ) ; if ( e . asType ( ) . toString ( ) . equals ( "char" ) ) { int v = ( int ) value . toString ( ) . charAt ( 0 ) ; result . append ( "'\\u" + Integer . toString ( v , 16 ) + "'" ) ; } else { result . append ( value . toString ( ) ) ; } } return result . toString ( ) ; }
Creates a String representation of a variable element with everything necessary to track all public aspects of it in an API .
212
23
11,231
public void add ( Collection < Deployment > deployments ) { for ( Deployment deployment : deployments ) this . deployments . put ( deployment . getId ( ) , deployment ) ; }
Adds the deployment list to the deployments for the account .
37
11
11,232
Type generateReturnConstraints ( JCTree tree , Attr . ResultInfo resultInfo , MethodType mt , InferenceContext inferenceContext ) { InferenceContext rsInfoInfContext = resultInfo . checkContext . inferenceContext ( ) ; Type from = mt . getReturnType ( ) ; if ( mt . getReturnType ( ) . containsAny ( inferenceContext . inferencevars ) && rsInfoInfContext != emptyContext ) { from = types . capture ( from ) ; //add synthetic captured ivars for ( Type t : from . getTypeArguments ( ) ) { if ( t . hasTag ( TYPEVAR ) && ( ( TypeVar ) t ) . isCaptured ( ) ) { inferenceContext . addVar ( ( TypeVar ) t ) ; } } } Type qtype = inferenceContext . asUndetVar ( from ) ; Type to = resultInfo . pt ; if ( qtype . hasTag ( VOID ) ) { to = syms . voidType ; } else if ( to . hasTag ( NONE ) ) { to = from . isPrimitive ( ) ? from : syms . objectType ; } else if ( qtype . hasTag ( UNDETVAR ) ) { if ( resultInfo . pt . isReference ( ) ) { to = generateReturnConstraintsUndetVarToReference ( tree , ( UndetVar ) qtype , to , resultInfo , inferenceContext ) ; } else { if ( to . isPrimitive ( ) ) { to = generateReturnConstraintsPrimitive ( tree , ( UndetVar ) qtype , to , resultInfo , inferenceContext ) ; } } } Assert . check ( allowGraphInference || ! rsInfoInfContext . free ( to ) , "legacy inference engine cannot handle constraints on both sides of a subtyping assertion" ) ; //we need to skip capture? Warner retWarn = new Warner ( ) ; if ( ! resultInfo . checkContext . compatible ( qtype , rsInfoInfContext . asUndetVar ( to ) , retWarn ) || //unchecked conversion is not allowed in source 7 mode ( ! allowGraphInference && retWarn . hasLint ( Lint . LintCategory . UNCHECKED ) ) ) { throw inferenceException . setMessage ( "infer.no.conforming.instance.exists" , inferenceContext . restvars ( ) , mt . getReturnType ( ) , to ) ; } return from ; }
Generate constraints from the generic method s return type . If the method call occurs in a context where a type T is expected use the expected type to derive more constraints on the generic method inference variables .
526
40
11,233
private void instantiateAsUninferredVars ( List < Type > vars , InferenceContext inferenceContext ) { ListBuffer < Type > todo = new ListBuffer <> ( ) ; //step 1 - create fresh tvars for ( Type t : vars ) { UndetVar uv = ( UndetVar ) inferenceContext . asUndetVar ( t ) ; List < Type > upperBounds = uv . getBounds ( InferenceBound . UPPER ) ; if ( Type . containsAny ( upperBounds , vars ) ) { TypeSymbol fresh_tvar = new TypeVariableSymbol ( Flags . SYNTHETIC , uv . qtype . tsym . name , null , uv . qtype . tsym . owner ) ; fresh_tvar . type = new TypeVar ( fresh_tvar , types . makeIntersectionType ( uv . getBounds ( InferenceBound . UPPER ) ) , null ) ; todo . append ( uv ) ; uv . inst = fresh_tvar . type ; } else if ( upperBounds . nonEmpty ( ) ) { uv . inst = types . glb ( upperBounds ) ; } else { uv . inst = syms . objectType ; } } //step 2 - replace fresh tvars in their bounds List < Type > formals = vars ; for ( Type t : todo ) { UndetVar uv = ( UndetVar ) t ; TypeVar ct = ( TypeVar ) uv . inst ; ct . bound = types . glb ( inferenceContext . asInstTypes ( types . getBounds ( ct ) ) ) ; if ( ct . bound . isErroneous ( ) ) { //report inference error if glb fails reportBoundError ( uv , BoundErrorKind . BAD_UPPER ) ; } formals = formals . tail ; } }
Infer cyclic inference variables as described in 15 . 12 . 2 . 8 .
413
17
11,234
Type instantiatePolymorphicSignatureInstance ( Env < AttrContext > env , MethodSymbol spMethod , // sig. poly. method or null if none Resolve . MethodResolutionContext resolveContext , List < Type > argtypes ) { final Type restype ; //The return type for a polymorphic signature call is computed from //the enclosing tree E, as follows: if E is a cast, then use the //target type of the cast expression as a return type; if E is an //expression statement, the return type is 'void' - otherwise the //return type is simply 'Object'. A correctness check ensures that //env.next refers to the lexically enclosing environment in which //the polymorphic signature call environment is nested. switch ( env . next . tree . getTag ( ) ) { case TYPECAST : JCTypeCast castTree = ( JCTypeCast ) env . next . tree ; restype = ( TreeInfo . skipParens ( castTree . expr ) == env . tree ) ? castTree . clazz . type : syms . objectType ; break ; case EXEC : JCTree . JCExpressionStatement execTree = ( JCTree . JCExpressionStatement ) env . next . tree ; restype = ( TreeInfo . skipParens ( execTree . expr ) == env . tree ) ? syms . voidType : syms . objectType ; break ; default : restype = syms . objectType ; } List < Type > paramtypes = Type . map ( argtypes , new ImplicitArgType ( spMethod , resolveContext . step ) ) ; List < Type > exType = spMethod != null ? spMethod . getThrownTypes ( ) : List . of ( syms . throwableType ) ; // make it throw all exceptions MethodType mtype = new MethodType ( paramtypes , restype , exType , syms . methodClass ) ; return mtype ; }
Compute a synthetic method type corresponding to the requested polymorphic method signature . The target return type is computed from the immediately enclosing scope surrounding the polymorphic - signature call .
415
35
11,235
void checkWithinBounds ( InferenceContext inferenceContext , Warner warn ) throws InferenceException { MultiUndetVarListener mlistener = new MultiUndetVarListener ( inferenceContext . undetvars ) ; List < Type > saved_undet = inferenceContext . save ( ) ; try { while ( true ) { mlistener . reset ( ) ; if ( ! allowGraphInference ) { //in legacy mode we lack of transitivity, so bound check //cannot be run in parallel with other incoprporation rounds for ( Type t : inferenceContext . undetvars ) { UndetVar uv = ( UndetVar ) t ; IncorporationStep . CHECK_BOUNDS . apply ( uv , inferenceContext , warn ) ; } } for ( Type t : inferenceContext . undetvars ) { UndetVar uv = ( UndetVar ) t ; //bound incorporation EnumSet < IncorporationStep > incorporationSteps = allowGraphInference ? incorporationStepsGraph : incorporationStepsLegacy ; for ( IncorporationStep is : incorporationSteps ) { if ( is . accepts ( uv , inferenceContext ) ) { is . apply ( uv , inferenceContext , warn ) ; } } } if ( ! mlistener . changed || ! allowGraphInference ) break ; } } finally { mlistener . detach ( ) ; if ( incorporationCache . size ( ) == MAX_INCORPORATION_STEPS ) { inferenceContext . rollback ( saved_undet ) ; } incorporationCache . clear ( ) ; } }
Check bounds and perform incorporation
335
5
11,236
void checkCompatibleUpperBounds ( UndetVar uv , InferenceContext inferenceContext ) { List < Type > hibounds = Type . filter ( uv . getBounds ( InferenceBound . UPPER ) , new BoundFilter ( inferenceContext ) ) ; Type hb = null ; if ( hibounds . isEmpty ( ) ) hb = syms . objectType ; else if ( hibounds . tail . isEmpty ( ) ) hb = hibounds . head ; else hb = types . glb ( hibounds ) ; if ( hb == null || hb . isErroneous ( ) ) reportBoundError ( uv , BoundErrorKind . BAD_UPPER ) ; }
Make sure that the upper bounds we got so far lead to a solvable inference variable by making sure that a glb exists .
157
26
11,237
public JwwfServer bindWebapp ( final Class < ? extends User > user , String url ) { if ( ! url . endsWith ( "/" ) ) url = url + "/" ; context . addServlet ( new ServletHolder ( new WebClientServelt ( clientCreator ) ) , url + "" ) ; context . addServlet ( new ServletHolder ( new SkinServlet ( ) ) , url + "__jwwf/skins/*" ) ; ServletHolder fontServletHolder = new ServletHolder ( new ResourceServlet ( ) ) ; fontServletHolder . setInitParameter ( "basePackage" , "net/magik6k/jwwf/assets/fonts" ) ; context . addServlet ( fontServletHolder , url + "__jwwf/fonts/*" ) ; context . addServlet ( new ServletHolder ( new APISocketServlet ( new UserFactory ( ) { @ Override public User createUser ( ) { try { User u = user . getDeclaredConstructor ( ) . newInstance ( ) ; u . setServer ( jwwfServer ) ; return u ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; } } ) ) , url + "__jwwf/socket" ) ; for ( JwwfPlugin plugin : plugins ) { if ( plugin instanceof IPluginWebapp ) ( ( IPluginWebapp ) plugin ) . onWebappBound ( this , url ) ; } return this ; }
Binds webapp to address
340
6
11,238
public JwwfServer attachPlugin ( JwwfPlugin plugin ) { plugins . add ( plugin ) ; if ( plugin instanceof IPluginGlobal ) ( ( IPluginGlobal ) plugin ) . onAttach ( this ) ; return this ; }
Attahes new plugin to this server
50
8
11,239
public JwwfServer startAndJoin ( ) { try { server . start ( ) ; server . join ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return this ; }
Starts Jetty server and waits for it
46
9
11,240
public static InputStream decode ( DataBinder binder , InputStream stream ) throws ParserConfigurationException , SAXException , IOException { XML . newSAXParser ( ) . parse ( stream , new XDBHandler ( binder ) ) ; return stream ; }
Decodes an XML stream . Returns the input stream .
56
11
11,241
void addBridge ( DiagnosticPosition pos , MethodSymbol meth , MethodSymbol impl , ClassSymbol origin , boolean hypothetical , ListBuffer < JCTree > bridges ) { make . at ( pos ) ; Type origType = types . memberType ( origin . type , meth ) ; Type origErasure = erasure ( origType ) ; // Create a bridge method symbol and a bridge definition without a body. Type bridgeType = meth . erasure ( types ) ; long flags = impl . flags ( ) & AccessFlags | SYNTHETIC | BRIDGE | ( origin . isInterface ( ) ? DEFAULT : 0 ) ; if ( hypothetical ) flags |= HYPOTHETICAL ; MethodSymbol bridge = new MethodSymbol ( flags , meth . name , bridgeType , origin ) ; /* once JDK-6996415 is solved it should be checked if this approach can * be applied to method addOverrideBridgesIfNeeded */ bridge . params = createBridgeParams ( impl , bridge , bridgeType ) ; bridge . setAttributes ( impl ) ; if ( ! hypothetical ) { JCMethodDecl md = make . MethodDef ( bridge , null ) ; // The bridge calls this.impl(..), if we have an implementation // in the current class, super.impl(...) otherwise. JCExpression receiver = ( impl . owner == origin ) ? make . This ( origin . erasure ( types ) ) : make . Super ( types . supertype ( origin . type ) . tsym . erasure ( types ) , origin ) ; // The type returned from the original method. Type calltype = erasure ( impl . type . getReturnType ( ) ) ; // Construct a call of this.impl(params), or super.impl(params), // casting params and possibly results as needed. JCExpression call = make . Apply ( null , make . Select ( receiver , impl ) . setType ( calltype ) , translateArgs ( make . Idents ( md . params ) , origErasure . getParameterTypes ( ) , null ) ) . setType ( calltype ) ; JCStatement stat = ( origErasure . getReturnType ( ) . hasTag ( VOID ) ) ? make . Exec ( call ) : make . Return ( coerce ( call , bridgeType . getReturnType ( ) ) ) ; md . body = make . Block ( 0 , List . of ( stat ) ) ; // Add bridge to `bridges' buffer bridges . append ( md ) ; } // Add bridge to scope of enclosing class and `overridden' table. origin . members ( ) . enter ( bridge ) ; overridden . put ( bridge , meth ) ; }
Add a bridge definition and enter corresponding method symbol in local scope of origin .
564
15
11,242
void addBridges ( DiagnosticPosition pos , ClassSymbol origin , ListBuffer < JCTree > bridges ) { Type st = types . supertype ( origin . type ) ; while ( st . hasTag ( CLASS ) ) { // if (isSpecialization(st)) addBridges ( pos , st . tsym , origin , bridges ) ; st = types . supertype ( st ) ; } for ( List < Type > l = types . interfaces ( origin . type ) ; l . nonEmpty ( ) ; l = l . tail ) // if (isSpecialization(l.head)) addBridges ( pos , l . head . tsym , origin , bridges ) ; }
Add all necessary bridges to some class appending them to list buffer .
143
14
11,243
public void visitTypeApply ( JCTypeApply tree ) { JCTree clazz = translate ( tree . clazz , null ) ; result = clazz ; }
Visitor method for parameterized types .
35
8
11,244
public JCTree translateTopLevelClass ( JCTree cdef , TreeMaker make ) { // note that this method does NOT support recursion. this . make = make ; pt = null ; return translate ( cdef , null ) ; }
Translate a toplevel class definition .
51
9
11,245
protected void addAllProfilesLink ( Content div ) { Content linkContent = getHyperLink ( DocPaths . PROFILE_OVERVIEW_FRAME , allprofilesLabel , "" , "packageListFrame" ) ; Content span = HtmlTree . SPAN ( linkContent ) ; div . addContent ( span ) ; }
Adds All Profiles link for the top of the left - hand frame page to the documentation tree .
70
20
11,246
public BiStream < T , U > throwIfNull ( BiPredicate < ? super T , ? super U > biPredicate , Supplier < ? extends RuntimeException > e ) { Predicate < T > predicate = ( t ) - > biPredicate . test ( t , object ) ; return nonEmptyStream ( stream . filter ( predicate ) , e ) ; }
Compares the objects from stream to the injected object . If the rest of the stream equals null so exception is thrown .
78
24
11,247
void setCurrent ( TreePath path , DocCommentTree comment ) { currPath = path ; currDocComment = comment ; currElement = trees . getElement ( currPath ) ; currOverriddenMethods = ( ( JavacTypes ) types ) . getOverriddenMethods ( currElement ) ; AccessKind ak = AccessKind . PUBLIC ; for ( TreePath p = path ; p != null ; p = p . getParentPath ( ) ) { Element e = trees . getElement ( p ) ; if ( e != null && e . getKind ( ) != ElementKind . PACKAGE ) { ak = min ( ak , AccessKind . of ( e . getModifiers ( ) ) ) ; } } currAccess = ak ; }
Set the current declaration and its doc comment .
159
9
11,248
public static < E extends Enum < E > > Flags < E > valueOf ( Class < E > type , String values ) { Flags < E > flags = new Flags < E > ( type ) ; for ( String text : values . trim ( ) . split ( MULTI_VALUE_SEPARATOR ) ) { flags . set ( Enum . valueOf ( type , text ) ) ; } return flags ; }
Returns a Flags with a value represented by a string of concatenated enum literal names separated by any combination of a comma a colon or a white space .
89
31
11,249
public static void generate ( ConfigurationImpl configuration , PackageDoc packageDoc , int profileValue ) { ProfilePackageFrameWriter profpackgen ; try { String profileName = Profile . lookup ( profileValue ) . name ; profpackgen = new ProfilePackageFrameWriter ( configuration , packageDoc , profileName ) ; StringBuilder winTitle = new StringBuilder ( profileName ) ; String sep = " - " ; winTitle . append ( sep ) ; String pkgName = Util . getPackageName ( packageDoc ) ; winTitle . append ( pkgName ) ; Content body = profpackgen . getBody ( false , profpackgen . getWindowTitle ( winTitle . toString ( ) ) ) ; Content profName = new StringContent ( profileName ) ; Content sepContent = new StringContent ( sep ) ; Content pkgNameContent = new RawHtml ( pkgName ) ; Content heading = HtmlTree . HEADING ( HtmlConstants . TITLE_HEADING , HtmlStyle . bar , profpackgen . getTargetProfileLink ( "classFrame" , profName , profileName ) ) ; heading . addContent ( sepContent ) ; heading . addContent ( profpackgen . getTargetProfilePackageLink ( packageDoc , "classFrame" , pkgNameContent , profileName ) ) ; body . addContent ( heading ) ; HtmlTree div = new HtmlTree ( HtmlTag . DIV ) ; div . addStyle ( HtmlStyle . indexContainer ) ; profpackgen . addClassListing ( div , profileValue ) ; body . addContent ( div ) ; profpackgen . printHtmlDocument ( configuration . metakeywords . getMetaKeywords ( packageDoc ) , false , body ) ; profpackgen . close ( ) ; } catch ( IOException exc ) { configuration . standardmessage . error ( "doclet.exception_encountered" , exc . toString ( ) , DocPaths . PACKAGE_FRAME . getPath ( ) ) ; throw new DocletAbortException ( exc ) ; } }
Generate a profile package summary page for the left - hand bottom frame . Construct the ProfilePackageFrameWriter object and then uses it generate the file .
439
30
11,250
public static < First , Second > Pair < First , Second > from ( final First first , final Second second ) { return new ImmutablePair < First , Second > ( first , second ) ; }
Create a simple pair from it s first and second component .
42
12
11,251
public static < CommonSuperType , First extends CommonSuperType , Second extends CommonSuperType > CommonSuperType [ ] toArray ( final Pair < First , Second > pair , final Class < CommonSuperType > commonSuperType ) { @ SuppressWarnings ( "unchecked" ) final CommonSuperType [ ] array = ( CommonSuperType [ ] ) Array . newInstance ( commonSuperType , 2 ) ; return toArray ( pair , array , 0 ) ; }
Transform a pair into an array of the common super type of both components .
99
15
11,252
public static < CommonSuperType , First extends CommonSuperType , Second extends CommonSuperType > CommonSuperType [ ] toArray ( final Pair < First , Second > pair , final CommonSuperType [ ] target , final int offset ) { target [ offset ] = pair . getFirst ( ) ; target [ offset + 1 ] = pair . getSecond ( ) ; return target ; }
Write a pair into an array of the common super type of both components .
79
15
11,253
@ Override public void setFilter ( Service . Filter filter ) { _filter = _filter == null ? filter : new CompoundServiceFilter ( filter , _filter ) ; }
Installs a service filter .
37
6
11,254
public void setFilters ( List < Service . Filter > filters ) { for ( Service . Filter filter : filters ) setFilter ( filter ) ; }
Installs a list of service filters . This method is designed to facilitate Spring bean assembly .
31
18
11,255
private Interaction findContext ( String id ) { for ( int i = _currentInteractions . size ( ) - 1 ; i >= 0 ; i -- ) { Interaction ia = ( Interaction ) _currentInteractions . get ( i ) ; if ( ia . id . equals ( id ) ) { return ia ; } } return null ; }
Caller must hold lock on interactions
76
7
11,256
public List < RpcResponse > request ( List < RpcRequest > reqList ) { for ( RpcRequest req : reqList ) { this . reqList . add ( req ) ; } return null ; }
Adds all requests in reqList to internal request list
45
10
11,257
public static KindName kindName ( int kind ) { switch ( kind ) { case PCK : return KindName . PACKAGE ; case TYP : return KindName . CLASS ; case VAR : return KindName . VAR ; case VAL : return KindName . VAL ; case MTH : return KindName . METHOD ; default : throw new AssertionError ( "Unexpected kind: " + kind ) ; } }
A KindName representing a given symbol kind
89
8
11,258
public static KindName absentKind ( int kind ) { switch ( kind ) { case ABSENT_VAR : return KindName . VAR ; case WRONG_MTHS : case WRONG_MTH : case ABSENT_MTH : case WRONG_STATICNESS : return KindName . METHOD ; case ABSENT_TYP : return KindName . CLASS ; default : throw new AssertionError ( "Unexpected kind: " + kind ) ; } }
A KindName representing the kind of a missing symbol given an error kind .
101
15
11,259
@ Nonnull @ ReturnsMutableCopy public ICommonsList < IBANElementValue > parseToElementValues ( @ Nonnull final String sIBAN ) { ValueEnforcer . notNull ( sIBAN , "IBANString" ) ; final String sRealIBAN = IBANManager . unifyIBAN ( sIBAN ) ; if ( sRealIBAN . length ( ) != m_nExpectedLength ) throw new IllegalArgumentException ( "Passed IBAN has an invalid length. Expected " + m_nExpectedLength + " but found " + sRealIBAN . length ( ) ) ; final ICommonsList < IBANElementValue > ret = new CommonsArrayList <> ( m_aElements . size ( ) ) ; int nIndex = 0 ; for ( final IBANElement aElement : m_aElements ) { final String sIBANPart = sRealIBAN . substring ( nIndex , nIndex + aElement . getLength ( ) ) ; ret . add ( new IBANElementValue ( aElement , sIBANPart ) ) ; nIndex += aElement . getLength ( ) ; } return ret ; }
Parse a given IBAN number string and convert it to elements according to this country s definition of IBAN numbers .
253
24
11,260
@ Nonnull public static IBANCountryData createFromString ( @ Nonnull @ Nonempty final String sCountryCode , @ Nonnegative final int nExpectedLength , @ Nullable final String sLayout , @ Nullable final String sFixedCheckDigits , @ Nullable final LocalDate aValidFrom , @ Nullable final LocalDate aValidTo , @ Nonnull final String sDesc ) { ValueEnforcer . notEmpty ( sDesc , "Desc" ) ; if ( sDesc . length ( ) < 4 ) throw new IllegalArgumentException ( "Cannot converted passed string because it is too short!" ) ; final ICommonsList < IBANElement > aList = _parseElements ( sDesc ) ; final Pattern aPattern = _parseLayout ( sCountryCode , nExpectedLength , sFixedCheckDigits , sLayout ) ; // And we're done try { return new IBANCountryData ( nExpectedLength , aPattern , sFixedCheckDigits , aValidFrom , aValidTo , aList ) ; } catch ( final IllegalArgumentException ex ) { throw new IllegalArgumentException ( "Failed to parse '" + sDesc + "': " + ex . getMessage ( ) ) ; } }
This method is used to create an instance of this class from a string representation .
263
16
11,261
protected final void setControllerPath ( String path ) { requireNonNull ( path , "Global path cannot be change to 'null'" ) ; if ( ! "" . equals ( path ) && ! "/" . equals ( path ) ) { this . controllerPath = pathCorrector . apply ( path ) ; } }
Creates a resource part of the path unified for all routes defined in the inherited class
65
17
11,262
public void scan ( final String [ ] packages ) { LOGGER . info ( "Scanning packages {}:" , ArrayUtils . toString ( packages ) ) ; for ( final String pkg : packages ) { try { final String pkgFile = pkg . replace ( ' ' , ' ' ) ; final Enumeration < URL > urls = getRootClassloader ( ) . getResources ( pkgFile ) ; while ( urls . hasMoreElements ( ) ) { final URL url = urls . nextElement ( ) ; try { final URI uri = getURI ( url ) ; LOGGER . debug ( "Scanning {}" , uri ) ; scan ( uri , pkgFile ) ; } catch ( final URISyntaxException e ) { LOGGER . debug ( "URL {} cannot be converted to a URI" , url , e ) ; } } } catch ( final IOException ex ) { throw new RuntimeException ( "The resources for the package" + pkg + ", could not be obtained" , ex ) ; } } LOGGER . info ( "Found {} matching classes and {} matching files" , matchingClasses . size ( ) , matchingFiles . size ( ) ) ; }
Scans packages for matching Java classes .
257
8
11,263
int run ( String [ ] args ) { try { handleOptions ( args ) ; // the following gives consistent behavior with javac if ( classes == null || classes . size ( ) == 0 ) { if ( options . help || options . version || options . fullVersion ) return EXIT_OK ; else return EXIT_CMDERR ; } try { return run ( ) ; } finally { if ( defaultFileManager != null ) { try { defaultFileManager . close ( ) ; defaultFileManager = null ; } catch ( IOException e ) { throw new InternalError ( e ) ; } } } } catch ( BadArgs e ) { reportError ( e . key , e . args ) ; if ( e . showUsage ) { printLines ( getMessage ( "main.usage.summary" , progname ) ) ; } return EXIT_CMDERR ; } catch ( InternalError e ) { Object [ ] e_args ; if ( e . getCause ( ) == null ) e_args = e . args ; else { e_args = new Object [ e . args . length + 1 ] ; e_args [ 0 ] = e . getCause ( ) ; System . arraycopy ( e . args , 0 , e_args , 1 , e . args . length ) ; } reportError ( "err.internal.error" , e_args ) ; return EXIT_ABNORMAL ; } finally { log . flush ( ) ; } }
Compiler terminated abnormally
312
5
11,264
public String [ ] getMetaKeywords ( Profile profile ) { if ( configuration . keywords ) { String profileName = profile . name ; return new String [ ] { profileName + " " + "profile" } ; } else { return new String [ ] { } ; } }
Get the profile keywords .
58
5
11,265
public R scan ( Tree node , P p ) { return ( node == null ) ? null : node . accept ( this , p ) ; }
Scan a single node .
30
5
11,266
public void setAuthorizedPatternArray ( String [ ] patterns ) { Matcher matcher ; patterns : for ( String pattern : patterns ) { if ( ( matcher = IPv4_ADDRESS_PATTERN . matcher ( pattern ) ) . matches ( ) ) { short [ ] address = new short [ 4 ] ; for ( int i = 0 ; i < address . length ; ++ i ) { String p = matcher . group ( i + 1 ) ; try { address [ i ] = Short . parseShort ( p ) ; if ( address [ i ] > 255 ) { _logger . warning ( "Invalid pattern ignored: " + pattern ) ; continue patterns ; } } catch ( Exception x ) { if ( "*" . equals ( p ) ) { address [ i ] = 256 ; } else { _logger . warning ( "Invalid pattern ignored: " + pattern ) ; continue patterns ; } } } _logger . fine ( "normalized ipv4 address pattern = " + Strings . join ( address , ' ' ) ) ; _ipv4patterns . add ( address ) ; } else if ( ( matcher = IPv6_ADDRESS_PATTERN . matcher ( pattern ) ) . matches ( ) ) { short [ ] address = new short [ 16 ] ; for ( int i = 0 ; i < address . length ; i += 2 ) { String p = matcher . group ( i / 2 + 1 ) ; try { int v = Integer . parseInt ( p , 16 ) ; address [ i ] = ( short ) ( v >> 8 ) ; address [ i + 1 ] = ( short ) ( v & 0x00ff ) ; } catch ( Exception x ) { if ( "*" . equals ( p ) ) { address [ i ] = 256 ; address [ i + 1 ] = 256 ; } else { _logger . warning ( "Invalid pattern ignored: " + pattern ) ; continue patterns ; } } } _logger . fine ( "normalized ipv6 address pattern = " + Strings . join ( address , ' ' ) ) ; _ipv6patterns . add ( address ) ; } else { _logger . warning ( "Invalid pattern ignored: " + pattern ) ; } } }
Adds authorized address patterns as a String array .
482
9
11,267
private boolean findJavaSourceFiles ( String [ ] args ) { String prev = "" ; for ( String s : args ) { if ( s . endsWith ( ".java" ) && ! prev . equals ( "-xf" ) && ! prev . equals ( "-if" ) ) { return true ; } prev = s ; } return false ; }
Are java source files passed on the command line?
72
10
11,268
private boolean findAtFile ( String [ ] args ) { for ( String s : args ) { if ( s . startsWith ( "@" ) ) { return true ; } } return false ; }
Is an at file passed on the command line?
41
10
11,269
private String findLogLevel ( String [ ] args ) { for ( String s : args ) { if ( s . startsWith ( "--log=" ) && s . length ( ) > 6 ) { return s . substring ( 6 ) ; } if ( s . equals ( "-verbose" ) ) { return "info" ; } } return "info" ; }
Find the log level setting .
78
6
11,270
private static boolean makeSureExists ( File dir ) { // Make sure the dest directories exist. if ( ! dir . exists ( ) ) { if ( ! dir . mkdirs ( ) ) { Log . error ( "Could not create the directory " + dir . getPath ( ) ) ; return false ; } } return true ; }
Make sure directory exist create it if not .
71
9
11,271
private static void checkPattern ( String s ) throws ProblemException { // Package names like foo.bar.gamma are allowed, and // package names suffixed with .* like foo.bar.* are // also allowed. Pattern p = Pattern . compile ( "[a-zA-Z_]{1}[a-zA-Z0-9_]*(\\.[a-zA-Z_]{1}[a-zA-Z0-9_]*)*(\\.\\*)?+" ) ; Matcher m = p . matcher ( s ) ; if ( ! m . matches ( ) ) { throw new ProblemException ( "The string \"" + s + "\" is not a proper package name pattern." ) ; } }
Verify that a package pattern is valid .
164
9
11,272
private static void checkFilePattern ( String s ) throws ProblemException { // File names like foo/bar/gamma/Bar.java are allowed, // as well as /bar/jndi.properties as well as, // */bar/Foo.java Pattern p = null ; if ( File . separatorChar == ' ' ) { p = Pattern . compile ( "\\*?(.+\\\\)*.+" ) ; } else if ( File . separatorChar == ' ' ) { p = Pattern . compile ( "\\*?(.+/)*.+" ) ; } else { throw new ProblemException ( "This platform uses the unsupported " + File . separatorChar + " as file separator character. Please add support for it!" ) ; } Matcher m = p . matcher ( s ) ; if ( ! m . matches ( ) ) { throw new ProblemException ( "The string \"" + s + "\" is not a proper file name." ) ; } }
Verify that a source file name is valid .
211
10
11,273
private static boolean hasOption ( String [ ] args , String option ) { for ( String a : args ) { if ( a . equals ( option ) ) return true ; } return false ; }
Scan the arguments to find an option is used .
40
10
11,274
private static void rewriteOptions ( String [ ] args , String option , String new_option ) { for ( int i = 0 ; i < args . length ; ++ i ) { if ( args [ i ] . equals ( option ) ) { args [ i ] = new_option ; } } }
Rewrite a single option into something else .
62
9
11,275
private static File findDirectoryOption ( String [ ] args , String option , String name , boolean needed , boolean allow_dups , boolean create ) throws ProblemException , ProblemException { File dir = null ; for ( int i = 0 ; i < args . length ; ++ i ) { if ( args [ i ] . equals ( option ) ) { if ( dir != null ) { throw new ProblemException ( "You have already specified the " + name + " dir!" ) ; } if ( i + 1 >= args . length ) { throw new ProblemException ( "You have to specify a directory following " + option + "." ) ; } if ( args [ i + 1 ] . indexOf ( File . pathSeparatorChar ) != - 1 ) { throw new ProblemException ( "You must only specify a single directory for " + option + "." ) ; } dir = new File ( args [ i + 1 ] ) ; if ( ! dir . exists ( ) ) { if ( ! create ) { throw new ProblemException ( "This directory does not exist: " + dir . getPath ( ) ) ; } else if ( ! makeSureExists ( dir ) ) { throw new ProblemException ( "Cannot create directory " + dir . getPath ( ) ) ; } } if ( ! dir . isDirectory ( ) ) { throw new ProblemException ( "\"" + args [ i + 1 ] + "\" is not a directory." ) ; } } } if ( dir == null && needed ) { throw new ProblemException ( "You have to specify " + option ) ; } try { if ( dir != null ) return dir . getCanonicalFile ( ) ; } catch ( IOException e ) { throw new ProblemException ( "" + e ) ; } return null ; }
Scan the arguments to find an option that specifies a directory . Create the directory if necessary .
374
18
11,276
private static boolean shouldBeFollowedByPath ( String o ) { return o . equals ( "-s" ) || o . equals ( "-h" ) || o . equals ( "-d" ) || o . equals ( "-sourcepath" ) || o . equals ( "-classpath" ) || o . equals ( "-cp" ) || o . equals ( "-bootclasspath" ) || o . equals ( "-src" ) ; }
Option is followed by path .
92
6
11,277
private static String [ ] addSrcBeforeDirectories ( String [ ] args ) { List < String > newargs = new ArrayList < String > ( ) ; for ( int i = 0 ; i < args . length ; ++ i ) { File dir = new File ( args [ i ] ) ; if ( dir . exists ( ) && dir . isDirectory ( ) ) { if ( i == 0 || ! shouldBeFollowedByPath ( args [ i - 1 ] ) ) { newargs . add ( "-src" ) ; } } newargs . add ( args [ i ] ) ; } return newargs . toArray ( new String [ 0 ] ) ; }
Add - src before source root directories if not already there .
141
12
11,278
private static void checkSrcOption ( String [ ] args ) throws ProblemException { Set < File > dirs = new HashSet < File > ( ) ; for ( int i = 0 ; i < args . length ; ++ i ) { if ( args [ i ] . equals ( "-src" ) ) { if ( i + 1 >= args . length ) { throw new ProblemException ( "You have to specify a directory following -src." ) ; } StringTokenizer st = new StringTokenizer ( args [ i + 1 ] , File . pathSeparator ) ; while ( st . hasMoreElements ( ) ) { File dir = new File ( st . nextToken ( ) ) ; if ( ! dir . exists ( ) ) { throw new ProblemException ( "This directory does not exist: " + dir . getPath ( ) ) ; } if ( ! dir . isDirectory ( ) ) { throw new ProblemException ( "\"" + dir . getPath ( ) + "\" is not a directory." ) ; } if ( dirs . contains ( dir ) ) { throw new ProblemException ( "The src directory \"" + dir . getPath ( ) + "\" is specified more than once!" ) ; } dirs . add ( dir ) ; } } } if ( dirs . isEmpty ( ) ) { throw new ProblemException ( "You have to specify -src." ) ; } }
Check the - src options .
296
6
11,279
private static File findFileOption ( String [ ] args , String option , String name , boolean needed ) throws ProblemException , ProblemException { File file = null ; for ( int i = 0 ; i < args . length ; ++ i ) { if ( args [ i ] . equals ( option ) ) { if ( file != null ) { throw new ProblemException ( "You have already specified the " + name + " file!" ) ; } if ( i + 1 >= args . length ) { throw new ProblemException ( "You have to specify a file following " + option + "." ) ; } file = new File ( args [ i + 1 ] ) ; if ( file . isDirectory ( ) ) { throw new ProblemException ( "\"" + args [ i + 1 ] + "\" is not a file." ) ; } if ( ! file . exists ( ) && needed ) { throw new ProblemException ( "The file \"" + args [ i + 1 ] + "\" does not exist." ) ; } } } if ( file == null && needed ) { throw new ProblemException ( "You have to specify " + option ) ; } return file ; }
Scan the arguments to find an option that specifies a file .
243
12
11,280
public static boolean findBooleanOption ( String [ ] args , String option ) { for ( int i = 0 ; i < args . length ; ++ i ) { if ( args [ i ] . equals ( option ) ) return true ; } return false ; }
Look for a specific switch return true if found .
54
10
11,281
public static int findNumberOption ( String [ ] args , String option ) { int rc = 0 ; for ( int i = 0 ; i < args . length ; ++ i ) { if ( args [ i ] . equals ( option ) ) { if ( args . length > i + 1 ) { rc = Integer . parseInt ( args [ i + 1 ] ) ; } } } return rc ; }
Scan the arguments to find an option that specifies a number .
84
12
11,282
public static String toHexString ( byte [ ] raw ) { byte [ ] hex = new byte [ 2 * raw . length ] ; int index = 0 ; for ( byte b : raw ) { int v = b & 0x00ff ; hex [ index ++ ] = HEX_CHARS [ v >>> 4 ] ; hex [ index ++ ] = HEX_CHARS [ v & 0xf ] ; } try { return new String ( hex , "ASCII" ) ; } catch ( java . io . UnsupportedEncodingException x ) { throw new RuntimeException ( x . getMessage ( ) , x ) ; } }
Converts an array of bytes into a hexadecimal representation .
134
14
11,283
public static String toCamelCase ( String text , char separator , boolean strict ) { char [ ] chars = text . toCharArray ( ) ; int base = 0 , top = 0 ; while ( top < chars . length ) { while ( top < chars . length && chars [ top ] == separator ) { ++ top ; } if ( top < chars . length ) { chars [ base ++ ] = Character . toUpperCase ( chars [ top ++ ] ) ; } if ( strict ) { while ( top < chars . length && chars [ top ] != separator ) { chars [ base ++ ] = Character . toLowerCase ( chars [ top ++ ] ) ; } } else { while ( top < chars . length && chars [ top ] != separator ) { chars [ base ++ ] = chars [ top ++ ] ; } } } return new String ( chars , 0 , base ) ; }
Converts a word sequence into a single camel - case sequence .
190
13
11,284
public static String toLowerCamelCase ( String text , char separator ) { char [ ] chars = text . toCharArray ( ) ; int base = 0 , top = 0 ; do { while ( top < chars . length && chars [ top ] != separator ) { chars [ base ++ ] = Character . toLowerCase ( chars [ top ++ ] ) ; } while ( top < chars . length && chars [ top ] == separator ) { ++ top ; } if ( top < chars . length ) { chars [ base ++ ] = Character . toUpperCase ( chars [ top ++ ] ) ; } } while ( top < chars . length ) ; return new String ( chars , 0 , base ) ; }
Converts a word sequence into a single camel - case word that starts with a lowercase letter .
151
20
11,285
public static String splitCamelCase ( String text , String separator ) { return CAMEL_REGEX . matcher ( text ) . replaceAll ( separator ) ; }
Splits a single camel - case word into a word sequence .
37
13
11,286
public static String hash ( String text ) throws NoSuchAlgorithmException , UnsupportedEncodingException { return Strings . toHexString ( MessageDigest . getInstance ( "SHA" ) . digest ( text . getBytes ( "UTF-8" ) ) ) ; }
Generates a secure hash from a given text .
59
10
11,287
public static String extend ( String text , char filler , int length ) { if ( text . length ( ) < length ) { char [ ] buffer = new char [ length ] ; Arrays . fill ( buffer , 0 , length , filler ) ; System . arraycopy ( text . toCharArray ( ) , 0 , buffer , 0 , text . length ( ) ) ; return new String ( buffer ) ; } else { return text ; } }
Extends a string to have at least the given length . If the original string is already as long it is returned without modification .
92
26
11,288
public static String substringBefore ( String text , char stopper ) { int p = text . indexOf ( stopper ) ; return p < 0 ? text : text . substring ( 0 , p ) ; }
Returns a substring from position 0 up to just before the stopper character .
45
16
11,289
public static String substringAfter ( String text , char match ) { return text . substring ( text . indexOf ( match ) + 1 ) ; }
Returns the substring following a given character or the original if the character is not found .
32
18
11,290
public static String join ( Object array , char separator , Object ... pieces ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 , ii = Array . getLength ( array ) ; i < ii ; ++ i ) { Object element = Array . get ( array , i ) ; sb . append ( element != null ? element . toString ( ) : "null" ) . append ( separator ) ; } for ( int i = 0 ; i < pieces . length ; ++ i ) { sb . append ( pieces [ i ] != null ? pieces [ i ] . toString ( ) : "null" ) . append ( separator ) ; } if ( sb . length ( ) > 0 ) sb . setLength ( sb . length ( ) - 1 ) ; return sb . toString ( ) ; }
Concatenates elements in an array into a single String with elements separated by the given separator .
181
21
11,291
public static < T > String join ( Iterable < T > iterable , char separator , T ... pieces ) { StringBuilder sb = new StringBuilder ( ) ; for ( T element : iterable ) { sb . append ( element != null ? element . toString ( ) : "null" ) . append ( separator ) ; } for ( int i = 0 ; i < pieces . length ; ++ i ) { sb . append ( pieces [ i ] != null ? pieces [ i ] . toString ( ) : "null" ) . append ( separator ) ; } if ( sb . length ( ) > 0 ) sb . setLength ( sb . length ( ) - 1 ) ; return sb . toString ( ) ; }
Concatenates elements in an Iterable into a single String with elements separated by the given separator .
161
22
11,292
public static Class < ? > rawClassOf ( Type type ) { if ( type instanceof Class < ? > ) { return ( Class < ? > ) type ; } else if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; Type rawType = parameterizedType . getRawType ( ) ; return ( Class < ? > ) rawType ; } else if ( type instanceof GenericArrayType ) { Type componentType = ( ( GenericArrayType ) type ) . getGenericComponentType ( ) ; return Array . newInstance ( rawClassOf ( componentType ) , 0 ) . getClass ( ) ; } else if ( type instanceof TypeVariable ) { return Object . class ; } else { throw new IllegalArgumentException ( "Unsupported type " + type . getTypeName ( ) ) ; } }
Returns the raw class of the specified type .
184
9
11,293
public static Predicate < Class < ? > > classIs ( final Class < ? > reference ) { return candidate -> candidate != null && candidate . equals ( reference ) ; }
Checks if a candidate class is equal to the specified class .
36
13
11,294
public static Predicate < Class < ? > > classIsAssignableFrom ( Class < ? > ancestor ) { return candidate -> candidate != null && ancestor . isAssignableFrom ( candidate ) ; }
Check if a candidate class is assignable to the specified class .
43
13
11,295
public static Predicate < Class < ? > > classImplements ( Class < ? > anInterface ) { if ( ! anInterface . isInterface ( ) ) { throw new IllegalArgumentException ( "Class " + anInterface . getName ( ) + " is not an interface" ) ; } return candidate -> candidate != null && ! candidate . isInterface ( ) && anInterface . isAssignableFrom ( candidate ) ; }
Checks if a candidate class is an interface .
91
10
11,296
public static < T extends Executable > Predicate < T > executableModifierIs ( final int modifier ) { return candidate -> ( candidate . getModifiers ( ) & modifier ) != 0 ; }
Checks if a candidate class has the specified modifier .
41
11
11,297
public static Predicate < Class < ? > > atLeastOneConstructorIsPublic ( ) { return candidate -> candidate != null && Classes . from ( candidate ) . constructors ( ) . anyMatch ( executableModifierIs ( Modifier . PUBLIC ) ) ; }
Checks if a candidate class has at least one public constructor .
56
13
11,298
protected int getOffset ( long dt ) { int ret = 0 ; TimeZone tz = DateUtilities . getCurrentTimeZone ( ) ; if ( tz != null ) ret = tz . getOffset ( dt ) ; return ret ; }
Returns the current offset for the given date allowing for daylight savings .
54
13
11,299
public static boolean isDeprecated ( Doc doc ) { if ( doc . tags ( "deprecated" ) . length > 0 ) { return true ; } AnnotationDesc [ ] annotationDescList ; if ( doc instanceof PackageDoc ) annotationDescList = ( ( PackageDoc ) doc ) . annotations ( ) ; else annotationDescList = ( ( ProgramElementDoc ) doc ) . annotations ( ) ; for ( int i = 0 ; i < annotationDescList . length ; i ++ ) { if ( annotationDescList [ i ] . annotationType ( ) . qualifiedName ( ) . equals ( java . lang . Deprecated . class . getName ( ) ) ) { return true ; } } return false ; }
Return true if the given Doc is deprecated .
148
9