idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
137,500 | public static void main ( String ... args ) throws Exception { Options options = createOptions ( ) ; try { Parser parser = new PosixParser ( ) ; CommandLine cmd = parser . parse ( options , args ) ; if ( cmd . hasOption ( "version" ) ) { System . out . println ( "Version: " + Launcher . class . getPackage ( ) . getImplementationVersion ( ) ) ; } String scriptPathEntries = cmd . getOptionValue ( "scriptpath" , "src/test/scripts" ) ; String [ ] scriptPathEntryArray = scriptPathEntries . split ( ";" ) ; List < URL > scriptUrls = new ArrayList <> ( ) ; for ( String scriptPathEntry : scriptPathEntryArray ) { File scriptEntryFilePath = new File ( scriptPathEntry ) ; scriptUrls . add ( scriptEntryFilePath . toURI ( ) . toURL ( ) ) ; } String controlURI = cmd . getOptionValue ( "control" ) ; if ( controlURI == null ) { controlURI = "tcp://localhost:11642" ; } boolean verbose = cmd . hasOption ( "verbose" ) ; URLClassLoader scriptLoader = new URLClassLoader ( scriptUrls . toArray ( new URL [ 0 ] ) ) ; RobotServer server = new RobotServer ( URI . create ( controlURI ) , verbose , scriptLoader ) ; server . start ( ) ; server . join ( ) ; } catch ( ParseException ex ) { HelpFormatter helpFormatter = new HelpFormatter ( ) ; helpFormatter . printHelp ( Launcher . class . getSimpleName ( ) , options , true ) ; } } | Main entry point to running K3PO . | 359 | 9 |
137,501 | public static FunctionMapper newFunctionMapper ( ) { ServiceLoader < FunctionMapperSpi > loader = loadFunctionMapperSpi ( ) ; // load FunctionMapperSpi instances ConcurrentMap < String , FunctionMapperSpi > functionMappers = new ConcurrentHashMap <> ( ) ; for ( FunctionMapperSpi functionMapperSpi : loader ) { String prefixName = functionMapperSpi . getPrefixName ( ) ; FunctionMapperSpi oldFunctionMapperSpi = functionMappers . putIfAbsent ( prefixName , functionMapperSpi ) ; if ( oldFunctionMapperSpi != null ) { throw new ELException ( String . format ( "Duplicate prefix function mapper: %s" , prefixName ) ) ; } } return new FunctionMapper ( functionMappers ) ; } | Creates a new Function Mapper . | 184 | 8 |
137,502 | public Method resolveFunction ( String prefix , String localName ) { FunctionMapperSpi functionMapperSpi = findFunctionMapperSpi ( prefix ) ; return functionMapperSpi . resolveFunction ( localName ) ; } | Resolves a Function via prefix and local name . | 49 | 10 |
137,503 | public byte [ ] getPayload ( int payloadStart , int payloadSize ) { byte [ ] payloadBuffer = new byte [ payloadSize ] ; System . arraycopy ( currentBuffer , payloadStart , payloadBuffer , 0 , payloadSize ) ; return payloadBuffer ; } | Returns a portion of the internal buffer | 55 | 7 |
137,504 | public static Config stormConfig ( Properties source ) { Config result = new Config ( ) ; logger . debug ( "Mapping declared types for Storm properties..." ) ; for ( Field field : result . getClass ( ) . getDeclaredFields ( ) ) { if ( field . getType ( ) != String . class ) continue ; if ( field . getName ( ) . endsWith ( CONFIGURATION_TYPE_FIELD_SUFFIX ) ) continue ; try { String key = field . get ( result ) . toString ( ) ; String entry = source . getProperty ( key ) ; if ( entry == null ) continue ; String typeFieldName = field . getName ( ) + CONFIGURATION_TYPE_FIELD_SUFFIX ; Field typeField = result . getClass ( ) . getDeclaredField ( typeFieldName ) ; Object type = typeField . get ( result ) ; logger . trace ( "Detected key '{}' as: {}" , key , field ) ; Object value = null ; if ( type == String . class ) value = entry ; if ( type == ConfigValidation . IntegerValidator . class || type == ConfigValidation . PowerOf2Validator . class ) value = Integer . valueOf ( entry ) ; if ( type == Boolean . class ) value = Boolean . valueOf ( entry ) ; if ( type == ConfigValidation . StringOrStringListValidator . class ) value = asList ( entry . split ( LIST_CONTINUATION_PATTERN ) ) ; if ( value == null ) { logger . warn ( "No parser for key '{}' type: {}" , key , typeField ) ; value = entry ; } result . put ( key , value ) ; } catch ( ReflectiveOperationException e ) { logger . debug ( "Interpretation failure on {}: {}" , field , e ) ; } } // Copy remaining for ( Map . Entry < Object , Object > e : source . entrySet ( ) ) { String key = e . getKey ( ) . toString ( ) ; if ( result . containsKey ( key ) ) continue ; result . put ( key , e . getValue ( ) ) ; } return result ; } | Applies type conversion where needed . | 468 | 7 |
137,505 | public static FunctionSignature valueOf ( String serial ) { int paramStart = serial . indexOf ( "(" ) ; int paramEnd = serial . indexOf ( ")" ) ; if ( paramStart < 0 || paramEnd != serial . length ( ) - 1 ) throw new IllegalArgumentException ( "Malformed method signature: " + serial ) ; String function = serial . substring ( 0 , paramStart ) . trim ( ) ; String arguments = serial . substring ( paramStart + 1 , paramEnd ) ; StringTokenizer tokenizer = new StringTokenizer ( arguments , ", " ) ; String [ ] names = new String [ tokenizer . countTokens ( ) ] ; for ( int i = 0 ; i < names . length ; ++ i ) names [ i ] = tokenizer . nextToken ( ) ; return new FunctionSignature ( function , names ) ; } | Parses a signature . | 184 | 6 |
137,506 | public Method findMethod ( Class < ? > type ) throws ReflectiveOperationException { Method match = null ; for ( Method option : type . getDeclaredMethods ( ) ) { if ( ! getFunction ( ) . equals ( option . getName ( ) ) ) continue ; Class < ? > [ ] parameters = option . getParameterTypes ( ) ; if ( parameters . length != getArguments ( ) . length ) continue ; if ( match != null ) { if ( refines ( option , match ) ) continue ; if ( ! refines ( match , option ) ) throw ambiguity ( match , option ) ; } match = option ; } Class < ? > [ ] parents = { type . getSuperclass ( ) } ; if ( type . isInterface ( ) ) parents = type . getInterfaces ( ) ; for ( Class < ? > parent : parents ) { if ( parent == null ) continue ; try { Method superMatch = findMethod ( parent ) ; if ( match == null ) { match = superMatch ; continue ; } if ( ! refines ( superMatch , match ) ) throw ambiguity ( match , superMatch ) ; } catch ( NoSuchMethodException ignored ) { } } if ( match == null ) { String fmt = "No method %s#%s with %d parameters" ; String msg = format ( fmt , type , getFunction ( ) , getArguments ( ) . length ) ; throw new NoSuchMethodException ( msg ) ; } match . setAccessible ( true ) ; return match ; } | Gets a method match . | 320 | 6 |
137,507 | public static Modifiers getInstance ( int bitmask ) { switch ( bitmask ) { case 0 : return NONE ; case Modifier . PUBLIC : return PUBLIC ; case Modifier . PUBLIC | Modifier . ABSTRACT : return PUBLIC_ABSTRACT ; case Modifier . PUBLIC | Modifier . STATIC : return PUBLIC_STATIC ; case Modifier . PROTECTED : return PROTECTED ; case Modifier . PRIVATE : return PRIVATE ; } return new Modifiers ( bitmask ) ; } | Returns a Modifiers object with the given bitmask . | 109 | 11 |
137,508 | public Result < V > [ ] getMatches ( String lookup , int limit ) { int strLen = lookup . length ( ) ; char [ ] chars = new char [ strLen + 1 ] ; lookup . getChars ( 0 , strLen , chars , 0 ) ; chars [ strLen ] = ' ' ; List resultList = new ArrayList ( ) ; fillMatchResults ( chars , limit , resultList ) ; return ( Result [ ] ) resultList . toArray ( new Result [ resultList . size ( ) ] ) ; } | Returns an empty array if no matches . | 114 | 8 |
137,509 | public synchronized < U extends T > U put ( U obj ) { if ( obj == null ) { return null ; } Entry < T > [ ] entries = mEntries ; int hash = hashCode ( obj ) ; int index = ( hash & 0x7fffffff ) % entries . length ; for ( Entry < T > e = entries [ index ] , prev = null ; e != null ; e = e . mNext ) { T iobj = e . get ( ) ; if ( iobj == null ) { // Clean up after a cleared Reference. if ( prev == null ) { entries [ index ] = e . mNext ; } else { prev . mNext = e . mNext ; } mSize -- ; } else if ( e . mHash == hash && obj . getClass ( ) == iobj . getClass ( ) && equals ( obj , iobj ) ) { // Found canonical instance. return ( U ) iobj ; } else { prev = e ; } } if ( mSize >= mThreshold ) { cleanup ( ) ; if ( mSize >= mThreshold ) { rehash ( ) ; entries = mEntries ; index = ( hash & 0x7fffffff ) % entries . length ; } } entries [ index ] = new Entry < T > ( this , obj , hash , entries [ index ] ) ; mSize ++ ; return obj ; } | Pass in a candidate canonical object and get a unique instance from this set . The returned object will always be of the same type as that passed in . If the object passed in does not equal any object currently in the set it will be added to the set becoming canonical . | 293 | 54 |
137,510 | public static void fire ( Throwable t ) { if ( t != null ) { // Don't need to do anything special for unchecked exceptions. if ( t instanceof RuntimeException ) { throw ( RuntimeException ) t ; } if ( t instanceof Error ) { throw ( Error ) t ; } ThrowUnchecked impl = cImpl ; if ( impl == null ) { synchronized ( ThrowUnchecked . class ) { impl = cImpl ; if ( impl == null ) { cImpl = impl = AccessController . doPrivileged ( new PrivilegedAction < ThrowUnchecked > ( ) { public ThrowUnchecked run ( ) { return generateImpl ( ) ; } } ) ; } } } impl . doFire ( t ) ; } } | Throws the given exception even though it may be checked . This method only returns normally if the exception is null . | 152 | 23 |
137,511 | public static void fireFirstDeclared ( Throwable t , Class ... declaredTypes ) { Throwable cause = t ; while ( cause != null ) { cause = cause . getCause ( ) ; if ( cause == null ) { break ; } if ( declaredTypes != null ) { for ( Class declaredType : declaredTypes ) { if ( declaredType . isInstance ( cause ) ) { fire ( cause ) ; } } } if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } if ( cause instanceof Error ) { throw ( Error ) cause ; } } throw new UndeclaredThrowableException ( t ) ; } | Throws the either the original exception or the first found cause if it matches one of the given declared types or is unchecked . Otherwise the original exception is thrown as an UndeclaredThrowableException . This method only returns normally if the exception is null . | 135 | 52 |
137,512 | public static void fireCause ( Throwable t ) { if ( t != null ) { Throwable cause = t . getCause ( ) ; if ( cause == null ) { cause = t ; } fire ( cause ) ; } } | Throws the cause of the given exception even though it may be checked . If the cause is null then the original exception is thrown . This method only returns normally if the exception is null . | 48 | 38 |
137,513 | public static void fireDeclaredCause ( Throwable t , Class ... declaredTypes ) { if ( t != null ) { Throwable cause = t . getCause ( ) ; if ( cause == null ) { cause = t ; } fireDeclared ( cause , declaredTypes ) ; } } | Throws the cause of the given exception if it is unchecked or an instance of any of the given declared types . Otherwise it is thrown as an UndeclaredThrowableException . If the cause is null then the original exception is thrown . This method only returns normally if the exception is null . | 60 | 60 |
137,514 | public static void fireFirstDeclaredCause ( Throwable t , Class ... declaredTypes ) { Throwable cause = t ; while ( cause != null ) { cause = cause . getCause ( ) ; if ( cause == null ) { break ; } if ( declaredTypes != null ) { for ( Class declaredType : declaredTypes ) { if ( declaredType . isInstance ( cause ) ) { fire ( cause ) ; } } } if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } if ( cause instanceof Error ) { throw ( Error ) cause ; } } fireDeclaredCause ( t , declaredTypes ) ; } | Throws the first found cause that matches one of the given declared types or is unchecked . Otherwise the immediate cause is thrown as an UndeclaredThrowableException . If the immediate cause is null then the original exception is thrown . This method only returns normally if the exception is null . | 134 | 58 |
137,515 | public static void fireRootCause ( Throwable t ) { Throwable root = t ; while ( root != null ) { Throwable cause = root . getCause ( ) ; if ( cause == null ) { break ; } root = cause ; } fire ( root ) ; } | Throws the root cause of the given exception even though it may be checked . If the root cause is null then the original exception is thrown . This method only returns normally if the exception is null . | 57 | 40 |
137,516 | public static void fireDeclaredRootCause ( Throwable t , Class ... declaredTypes ) { Throwable root = t ; while ( root != null ) { Throwable cause = root . getCause ( ) ; if ( cause == null ) { break ; } root = cause ; } fireDeclared ( root , declaredTypes ) ; } | Throws the root cause of the given exception if it is unchecked or an instance of any of the given declared types . Otherwise it is thrown as an UndeclaredThrowableException . If the root cause is null then the original exception is thrown . This method only returns normally if the exception is null . | 69 | 62 |
137,517 | public void setCodeBuffer ( CodeBuffer code ) { mCodeBuffer = code ; mOldLineNumberTable = mLineNumberTable ; mOldLocalVariableTable = mLocalVariableTable ; mOldStackMapTable = mStackMapTable ; mAttributes . remove ( mLineNumberTable ) ; mAttributes . remove ( mLocalVariableTable ) ; mAttributes . remove ( mStackMapTable ) ; mLineNumberTable = null ; mLocalVariableTable = null ; mStackMapTable = null ; } | As a side effect of calling this method new line number and local variable tables are created . | 105 | 18 |
137,518 | public void localVariableUse ( LocalVariable localVar ) { if ( mLocalVariableTable == null ) { addAttribute ( new LocalVariableTableAttr ( getConstantPool ( ) ) ) ; } mLocalVariableTable . addEntry ( localVar ) ; } | Indicate a local variable s use information be recorded in the ClassFile as a debugging aid . If the LocalVariable doesn t provide both a start and end location then its information is not recorded . This method should be called at most once per LocalVariable instance . | 55 | 52 |
137,519 | public ConstantClassInfo addConstantClass ( String className , int dim ) { return ( ConstantClassInfo ) addConstant ( new ConstantClassInfo ( this , className , dim ) ) ; } | Get or create a constant from the constant pool representing an array class . | 42 | 14 |
137,520 | public void init ( Configuration configuration ) throws Exception { String baseName = configuration . getBootstrapPropertyResolver ( ) . getProperty ( "ResourceBundleFactory.Bundle" ) ; if ( baseName != null ) { this . baseName = baseName ; } } | Initialize the bundle factory . | 57 | 6 |
137,521 | public ResourceBundle getDefaultBundle ( Locale locale ) throws MissingResourceException { ResourceBundle bundle ; if ( locale == null ) { bundle = ResourceBundle . getBundle ( baseName ) ; } else { bundle = ResourceBundle . getBundle ( baseName , locale ) ; } return bundle ; } | Returns the ResourceBundle from which to messages for the specified locale by default . | 68 | 16 |
137,522 | public static < B > BeanPropertyMapFactory < B > forClass ( Class < B > clazz ) { synchronized ( cFactories ) { BeanPropertyMapFactory factory ; SoftReference < BeanPropertyMapFactory > ref = cFactories . get ( clazz ) ; if ( ref != null ) { factory = ref . get ( ) ; if ( factory != null ) { return factory ; } } final Map < String , BeanProperty > properties = BeanIntrospector . getAllProperties ( clazz ) ; Map < String , BeanProperty > supportedProperties = properties ; // Determine which properties are to be excluded. for ( Map . Entry < String , BeanProperty > entry : properties . entrySet ( ) ) { BeanProperty property = entry . getValue ( ) ; if ( property . getReadMethod ( ) == null || property . getWriteMethod ( ) == null || BeanPropertyAccessor . throwsCheckedException ( property . getReadMethod ( ) ) || BeanPropertyAccessor . throwsCheckedException ( property . getWriteMethod ( ) ) ) { // Exclude property. if ( supportedProperties == properties ) { supportedProperties = new HashMap < String , BeanProperty > ( properties ) ; } supportedProperties . remove ( entry . getKey ( ) ) ; } } if ( supportedProperties . size ( ) == 0 ) { factory = Empty . INSTANCE ; } else { factory = new Standard < B > ( BeanPropertyAccessor . forClass ( clazz , BeanPropertyAccessor . PropertySet . READ_WRITE_UNCHECKED_EXCEPTIONS ) , supportedProperties ) ; } cFactories . put ( clazz , new SoftReference < BeanPropertyMapFactory > ( factory ) ) ; return factory ; } } | Returns a new or cached BeanPropertyMapFactory for the given class . | 370 | 14 |
137,523 | public static SortedMap < String , Object > asMap ( Object bean ) { if ( bean == null ) { throw new IllegalArgumentException ( ) ; } BeanPropertyMapFactory factory = forClass ( bean . getClass ( ) ) ; return factory . createMap ( bean ) ; } | Returns a fixed - size map backed by the given bean . Map remove operations are unsupported as is access to excluded properties . | 61 | 24 |
137,524 | public TypeDesc [ ] getExceptions ( ) { if ( mExceptions == null ) { return new TypeDesc [ 0 ] ; } ConstantClassInfo [ ] classes = mExceptions . getExceptions ( ) ; TypeDesc [ ] types = new TypeDesc [ classes . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) { types [ i ] = classes [ i ] . getType ( ) ; } return types ; } | Returns the exceptions that this method is declared to throw . | 98 | 11 |
137,525 | public static final String createBoundary ( ) { final StringBuilder builder = new StringBuilder ( BOUNDARY_PREFIX ) ; builder . append ( ( int ) System . currentTimeMillis ( ) ) ; return builder . toString ( ) ; } | Creates and returns a boundary for multipart request . | 54 | 11 |
137,526 | public R visit ( String name , int pos , String value , P param ) { return null ; } | Override to visit Strings . | 21 | 6 |
137,527 | public R visit ( String name , int pos , Annotation [ ] value , P param ) { for ( int i = 0 ; i < value . length ; i ++ ) { visit ( null , i , value [ i ] , param ) ; } return null ; } | Visits each array element . | 56 | 6 |
137,528 | @ Override public int doStartTag ( ) throws JspException { // Retrieve the action bean and event handler to secure. ActionBean actionBean ; if ( bean == null ) { // Search in page, request, session (if valid) and application scopes, in that order. actionBean = ( ActionBean ) pageContext . findAttribute ( StripesConstants . REQ_ATTR_ACTION_BEAN ) ; LOG . debug ( "Determining access for the action bean of the form: " , actionBean ) ; } else { // Search in page, request, session (if valid) and application scopes, in that order. actionBean = ( ActionBean ) pageContext . findAttribute ( bean ) ; LOG . debug ( "Determining access for action bean \"" , bean , "\": " , actionBean ) ; } if ( actionBean == null ) { throw new StripesJspException ( "Could not find the action bean. This means that either you specified the name \n" + "of a bean that doesn't exist, or this tag is not used inside a Stripes Form." ) ; } Method handler ; try { if ( event == null ) { handler = StripesFilter . getConfiguration ( ) . getActionResolver ( ) . getDefaultHandler ( actionBean . getClass ( ) ) ; LOG . debug ( "Found a handler for the default event: " , handler ) ; } else { handler = StripesFilter . getConfiguration ( ) . getActionResolver ( ) . getHandler ( actionBean . getClass ( ) , event ) ; LOG . debug ( "Found a handler for event \"" , event , "\": %s" , handler ) ; } } catch ( StripesServletException e ) { throw new StripesJspException ( "Failed to get the handler for the event." , e ) ; } // Get the judgement of the security manager. SecurityManager securityManager = ( SecurityManager ) pageContext . getAttribute ( SecurityInterceptor . SECURITY_MANAGER , PageContext . REQUEST_SCOPE ) ; boolean haveSecurityManager = securityManager != null ; boolean eventAllowed ; if ( haveSecurityManager ) { LOG . debug ( "Determining access using this security manager: " , securityManager ) ; eventAllowed = Boolean . TRUE . equals ( securityManager . getAccessAllowed ( actionBean , handler ) ) ; } else { LOG . debug ( "There is no security manager; allowing access" ) ; eventAllowed = true ; } // Show the tag's content (or not) based on this //noinspection deprecation if ( haveSecurityManager && negate ) { LOG . debug ( "This tag negates the decision of the security manager." ) ; eventAllowed = ! eventAllowed ; } LOG . debug ( "Access is " , eventAllowed ? "allowed" : "denied" , ' ' ) ; return eventAllowed ? EVAL_BODY_INCLUDE : SKIP_BODY ; } | Determine if the body should be evaluated or not . | 652 | 12 |
137,529 | public void run ( ) { if ( maxTime < 0 ) { return ; } long timeMillis = ( long ) maxTime * 60 * 1000 ; endTime = new Date ( ( new Date ( ) ) . getTime ( ) + timeMillis ) ; while ( ! cancel && endTime . after ( new Date ( ) ) ) { try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { cancel = true ; } } if ( ! cancel && ! endTime . after ( new Date ( ) ) ) { session . removeAttribute ( key ) ; } } | Remove field from session after maxTime is elapsed . | 124 | 10 |
137,530 | public Collection < Instruction > getInstructions ( ) { return new AbstractCollection < Instruction > ( ) { public Iterator < Instruction > iterator ( ) { return new Iterator < Instruction > ( ) { private Instruction mNext = mFirst ; public boolean hasNext ( ) { return mNext != null ; } public Instruction next ( ) { if ( mNext == null ) { throw new NoSuchElementException ( ) ; } Instruction current = mNext ; mNext = mNext . mNext ; return current ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } public int size ( ) { int count = 0 ; for ( Instruction i = mFirst ; i != null ; i = i . mNext ) { count ++ ; } return count ; } } ; } | Returns an immutable collection of all the instructions in this InstructionList . | 167 | 13 |
137,531 | public LocalVariable createLocalParameter ( String name , TypeDesc type ) { LocalVariable var = new LocalVariableImpl ( mLocalVariables . size ( ) , name , type , mNextFixedVariableNumber ) ; mLocalVariables . add ( var ) ; mNextFixedVariableNumber += type . isDoubleWord ( ) ? 2 : 1 ; return var ; } | All parameters must be defined before adding instructions . | 76 | 9 |
137,532 | public Resolution intercept ( ExecutionContext context ) throws Exception { HttpServletRequest request = context . getActionBeanContext ( ) . getRequest ( ) ; if ( resourceBundleFactory != null ) { ResourceBundle bundle = resourceBundleFactory . getDefaultBundle ( request . getLocale ( ) ) ; setMessageResourceBundle ( request , bundle ) ; } setOtherResourceBundles ( request ) ; return context . proceed ( ) ; } | Invoked when intercepting the flow of execution . | 97 | 10 |
137,533 | public Resolution intercept ( ExecutionContext executionContext ) throws Exception { Resolution resolution ; if ( securityManager != null ) { // Add the security manager to the request. // This is used (for example) by the security tag. executionContext . getActionBeanContext ( ) . getRequest ( ) . setAttribute ( SecurityInterceptor . SECURITY_MANAGER , securityManager ) ; switch ( executionContext . getLifecycleStage ( ) ) { case BindingAndValidation : case CustomValidation : resolution = interceptBindingAndValidation ( executionContext ) ; break ; case EventHandling : resolution = interceptEventHandling ( executionContext ) ; break ; case ResolutionExecution : resolution = interceptResolutionExecution ( executionContext ) ; break ; default : // Should not happen (see @Intercepts annotation on class) resolution = executionContext . proceed ( ) ; break ; } } else { // There is no security manager, so everything is allowed. resolution = executionContext . proceed ( ) ; } return resolution ; } | Intercept execution . | 214 | 4 |
137,534 | protected Resolution interceptEventHandling ( ExecutionContext executionContext ) throws Exception { // Before handling the event, check if access is allowed. // If not explicitly allowed, access is denied. Resolution resolution ; if ( Boolean . TRUE . equals ( getAccessAllowed ( executionContext ) ) ) { resolution = executionContext . proceed ( ) ; } else { LOG . debug ( "The security manager has denied access." ) ; resolution = handleAccessDenied ( executionContext . getActionBean ( ) , executionContext . getHandler ( ) ) ; } return resolution ; } | Intercept execution for event handling . Checks if the security manager allows access before allowing the event . | 116 | 19 |
137,535 | public static TypeDesc forDescriptor ( final String desc ) throws IllegalArgumentException { TypeDesc type = cDescriptorsToInstances . get ( desc ) ; if ( type != null ) { return type ; } // TODO: Support generics in descriptor. String rootDesc = desc ; int cursor = 0 ; int dim = 0 ; try { char c ; while ( ( c = rootDesc . charAt ( cursor ++ ) ) == ' ' ) { dim ++ ; } switch ( c ) { case ' ' : type = VOID ; break ; case ' ' : type = BOOLEAN ; break ; case ' ' : type = CHAR ; break ; case ' ' : type = BYTE ; break ; case ' ' : type = SHORT ; break ; case ' ' : type = INT ; break ; case ' ' : type = LONG ; break ; case ' ' : type = FLOAT ; break ; case ' ' : type = DOUBLE ; break ; case ' ' : if ( dim > 0 ) { rootDesc = rootDesc . substring ( dim ) ; cursor = 1 ; } StringBuffer name = new StringBuffer ( rootDesc . length ( ) - 2 ) ; while ( ( c = rootDesc . charAt ( cursor ++ ) ) != ' ' ) { if ( c == ' ' ) { c = ' ' ; } name . append ( c ) ; } type = intern ( new ObjectType ( rootDesc , name . toString ( ) ) ) ; break ; default : throw invalidDescriptor ( desc ) ; } } catch ( NullPointerException e ) { throw invalidDescriptor ( desc ) ; } catch ( IndexOutOfBoundsException e ) { throw invalidDescriptor ( desc ) ; } if ( cursor != rootDesc . length ( ) ) { throw invalidDescriptor ( desc ) ; } while ( -- dim >= 0 ) { type = type . toArrayType ( ) ; } cDescriptorsToInstances . put ( desc , type ) ; return type ; } | Acquire a TypeDesc from a type descriptor . | 430 | 10 |
137,536 | public void valueUnbound ( HttpSessionBindingEvent event ) { for ( SessionFieldMapper fieldMapper : this . values ( ) ) { if ( fieldMapper . runnable != null ) fieldMapper . runnable . cancel ( ) ; } } | Cancel all threads from field mappers . | 58 | 9 |
137,537 | public void sessionWillPassivate ( HttpSessionEvent event ) { for ( Entry < String , SessionFieldMapper > entry : this . entrySet ( ) ) { if ( ! entry . getValue ( ) . serializable ) { event . getSession ( ) . removeAttribute ( entry . getKey ( ) ) ; } } } | Remove all non - serializable fields from session . | 71 | 10 |
137,538 | private void cleanup ( ) { Entry < K , V > [ ] tab = this . table ; for ( int i = tab . length ; i -- > 0 ; ) { for ( Entry < K , V > e = tab [ i ] , prev = null ; e != null ; e = e . next ) { if ( e . get ( ) == null ) { // Clean up after a cleared Reference. this . modCount ++ ; if ( prev != null ) { prev . next = e . next ; } else { tab [ i ] = e . next ; } this . count -- ; } else { prev = e ; } } } } | Scans the contents of this map removing all entries that have a cleared soft value . | 135 | 17 |
137,539 | @ Override protected void setMessageResourceBundle ( HttpServletRequest request , ResourceBundle bundle ) { request . setAttribute ( REQ_ATTR_MESSAGE_RESOURCE_BUNDLE , bundle ) ; } | Puts the resource bundle as a request - scope attribute . | 52 | 12 |
137,540 | public List < ProblemInput > getProblemInputs ( ) { return ( inputs == null ? Collections . emptyList ( ) : Arrays . asList ( inputs ) ) ; } | Getter for the problem inputs . | 37 | 7 |
137,541 | public ProblemInput getProblemInput ( final int index ) { final List < ProblemInput > inputs = getProblemInputs ( ) ; if ( index < 0 || inputs . size ( ) <= index ) { throw new ArrayIndexOutOfBoundsException ( ) ; } return inputs . get ( index ) ; } | Shortcut method for reducing law of Demeters issues . | 64 | 11 |
137,542 | private void readObject ( final ObjectInputStream stream ) throws OptionalDataException , ClassNotFoundException , IOException { stream . registerValidation ( this , 0 ) ; stream . defaultReadObject ( ) ; } | Custom readObject method that registers this object as a deserialization validator . | 44 | 16 |
137,543 | public final static boolean canThrowException ( byte opcode ) { switch ( opcode ) { default : return false ; case IALOAD : case LALOAD : case FALOAD : case DALOAD : case AALOAD : case BALOAD : case CALOAD : case SALOAD : case IASTORE : case LASTORE : case FASTORE : case DASTORE : case AASTORE : case BASTORE : case CASTORE : case SASTORE : case IDIV : case LDIV : case IREM : case LREM : case GETFIELD : case PUTFIELD : case INVOKEVIRTUAL : case INVOKESPECIAL : case INVOKESTATIC : case INVOKEINTERFACE : case NEWARRAY : case ANEWARRAY : case ARRAYLENGTH : case ATHROW : case CHECKCAST : case MONITORENTER : case MONITOREXIT : case MULTIANEWARRAY : return true ; } } | Returns true if the given opcode can throw an exception at runtime . | 210 | 14 |
137,544 | public static Map < String , BeanProperty > getAllProperties ( Class clazz ) { synchronized ( cPropertiesCache ) { Map < String , BeanProperty > properties ; SoftReference < Map < String , BeanProperty > > ref = cPropertiesCache . get ( clazz ) ; if ( ref != null ) { properties = ref . get ( ) ; if ( properties != null ) { return properties ; } } properties = createProperties ( clazz ) ; cPropertiesCache . put ( clazz , new SoftReference < Map < String , BeanProperty > > ( properties ) ) ; return properties ; } } | Returns a Map of all the available properties on a given class including write - only and indexed properties . | 129 | 20 |
137,545 | private static String extractPropertyName ( Method method , String prefix ) { String name = method . getName ( ) ; if ( ! name . startsWith ( prefix ) ) { return null ; } if ( name . length ( ) == prefix . length ( ) ) { return "" ; } name = name . substring ( prefix . length ( ) ) ; if ( ! Character . isUpperCase ( name . charAt ( 0 ) ) || name . indexOf ( ' ' ) >= 0 ) { return null ; } // Decapitalize the name only if it doesn't begin with two uppercase // letters. if ( name . length ( ) == 1 || ! Character . isUpperCase ( name . charAt ( 1 ) ) ) { char chars [ ] = name . toCharArray ( ) ; chars [ 0 ] = Character . toLowerCase ( chars [ 0 ] ) ; name = new String ( chars ) ; } return name . intern ( ) ; } | Returns null if prefix pattern doesn t match | 204 | 8 |
137,546 | protected void saveFields ( Collection < Field > fields , ActionBean actionBean , HttpSession session ) throws IllegalAccessException { for ( Field field : fields ) { if ( ! field . isAccessible ( ) ) { field . setAccessible ( true ) ; } setAttribute ( session , getFieldKey ( field , actionBean . getClass ( ) ) , field . get ( actionBean ) , ( ( Session ) field . getAnnotation ( Session . class ) ) . serializable ( ) , ( ( Session ) field . getAnnotation ( Session . class ) ) . maxTime ( ) ) ; } } | Saves all fields in session . | 134 | 7 |
137,547 | protected void restoreFields ( Collection < Field > fields , ActionBean actionBean , ActionBeanContext context ) throws IllegalAccessException { HttpSession session = context . getRequest ( ) . getSession ( false ) ; if ( session != null ) { Set < String > parameters = this . getParameters ( context . getRequest ( ) ) ; for ( Field field : fields ) { if ( ! field . isAccessible ( ) ) { field . setAccessible ( true ) ; } if ( ! parameters . contains ( field . getName ( ) ) ) { // Replace value. Object value = session . getAttribute ( getFieldKey ( field , actionBean . getClass ( ) ) ) ; // If value is null and field is primitive, don't set value. if ( ! ( value == null && field . getType ( ) . isPrimitive ( ) ) ) { field . set ( actionBean , value ) ; } } } } } | Restore all fields from value stored in session except if they . | 203 | 13 |
137,548 | protected Set < String > getParameters ( HttpServletRequest request ) { Set < String > parameters = new HashSet < String > ( ) ; Enumeration < ? > paramNames = request . getParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { String parameter = ( String ) paramNames . nextElement ( ) ; // Keep only first property. while ( parameter . contains ( "." ) || parameter . contains ( "[" ) ) { if ( parameter . contains ( "." ) ) { parameter = parameter . substring ( 0 , parameter . indexOf ( "." ) ) ; } if ( parameter . contains ( "[" ) ) { parameter = parameter . substring ( 0 , parameter . indexOf ( "[" ) ) ; } } parameters . add ( parameter ) ; } return parameters ; } | Returns all property that stripes will replace for request . | 175 | 10 |
137,549 | protected String getFieldKey ( Field field , Class < ? extends ActionBean > actionBeanClass ) { // Use key attribute if it is defined. String sessionKey = ( ( Session ) field . getAnnotation ( Session . class ) ) . key ( ) ; if ( sessionKey != null && ! "" . equals ( sessionKey ) ) { return sessionKey ; } else { // Use default key since no custom key is defined. return actionBeanClass + "#" + field . getName ( ) ; } } | Returns session key under which field should be saved or read . | 109 | 12 |
137,550 | protected Collection < Field > getSessionFields ( Class < ? > clazz ) { Collection < Field > fields = fieldMap . get ( clazz ) ; if ( fields == null ) { fields = ReflectUtil . getFields ( clazz ) ; Iterator < Field > iterator = fields . iterator ( ) ; while ( iterator . hasNext ( ) ) { Field field = iterator . next ( ) ; if ( ! field . isAnnotationPresent ( Session . class ) ) { iterator . remove ( ) ; } } fieldMap . put ( clazz , fields ) ; } return fields ; } | Returns all fields with Session annotation for a class . | 126 | 10 |
137,551 | @ Deprecated public static Object getAttribute ( HttpSession session , String key ) { return session . getAttribute ( key ) ; } | Returns an object in session . | 28 | 6 |
137,552 | protected Object setAttribute ( HttpSession session , String key , Object object , boolean serializable , int maxTime ) { if ( object == null ) { // If object is null, remove attribute. Object ret ; synchronized ( session ) { ret = session . getAttribute ( key ) ; session . removeAttribute ( key ) ; } return ret ; } else { // Set object in session. Object ret ; synchronized ( session ) { ret = session . getAttribute ( key ) ; session . setAttribute ( key , object ) ; } SessionMapper mapper = ( SessionMapper ) session . getAttribute ( MAPPER_ATTRIBUTE ) ; if ( mapper == null ) { // Register mapper for session. mapper = new SessionMapper ( ) ; session . setAttribute ( MAPPER_ATTRIBUTE , mapper ) ; } synchronized ( mapper ) { // Update field mapper. SessionFieldMapper fieldMapper = mapper . get ( key ) ; if ( fieldMapper == null ) { fieldMapper = new SessionFieldMapper ( serializable && object instanceof Serializable ) ; mapper . put ( key , fieldMapper ) ; } if ( maxTime > 0 ) { // Register runnable to remove attribute. if ( fieldMapper . runnable != null ) { // Cancel old runnable because a new one will be created. fieldMapper . runnable . cancel ( ) ; } // Register runnable. RemoveFieldRunnable runnable = new RemoveFieldRunnable ( key , maxTime , session ) ; fieldMapper . runnable = runnable ; ( new Thread ( runnable ) ) . start ( ) ; } } return ret ; } } | Saves an object in session for latter use . | 367 | 10 |
137,553 | @ Override protected void setMessageResourceBundle ( HttpServletRequest request , ResourceBundle bundle ) { Config . set ( request , Config . FMT_LOCALIZATION_CONTEXT , new LocalizationContext ( bundle , request . getLocale ( ) ) ) ; LOGGER . debug ( "Enabled JSTL localization using: " , bundle ) ; LOGGER . debug ( "Loaded resource bundle " , bundle , " as default bundle" ) ; } | Sets the message resource bundle in the request using the JSTL s mechanism . | 100 | 17 |
137,554 | @ Override protected void setOtherResourceBundles ( HttpServletRequest request ) { Locale locale = request . getLocale ( ) ; if ( errorBundleName != null ) { ResourceBundle errorBundle = getLocalizationBundleFactory ( ) . getErrorMessageBundle ( locale ) ; Config . set ( request , errorBundleName , new LocalizationContext ( errorBundle , locale ) ) ; LOGGER . debug ( "Loaded Stripes error message bundle " , errorBundle , " as " , errorBundleName ) ; } if ( fieldBundleName != null ) { ResourceBundle fieldBundle = getLocalizationBundleFactory ( ) . getFormFieldBundle ( locale ) ; Config . set ( request , fieldBundleName , new LocalizationContext ( fieldBundle , locale ) ) ; LOGGER . debug ( "Loaded Stripes field name bundle " , fieldBundle , " as " , fieldBundleName ) ; } } | Sets the Stripes error and field resource bundles in the request if their names have been configured . | 211 | 20 |
137,555 | private Object evaluateRoleExpression ( ActionBean bean , String expression ) { try { LOG . debug ( "Evaluating expression: '" + expression + ' ' ) ; // This is somewhat of a hack until the ExpressionEvaluator becomes more accessible. ParameterName name = new ParameterName ( "security" ) ; List < Object > values = new ArrayList < Object > ( ) ; values . add ( null ) ; ValidationMetadata metadata = new ValidationMetadata ( "security" ) . expression ( expression ) ; ValidationErrors errors = new ValidationErrors ( ) ; ExpressionValidator . evaluate ( bean , name , values , metadata , errors ) ; return errors . isEmpty ( ) ; } catch ( Exception exc ) { throw new StripesRuntimeException ( exc ) ; } } | Evaluate the given EL expression using the current action bean to resolve variables . | 172 | 16 |
137,556 | public static MethodDesc forDescriptor ( String desc ) throws IllegalArgumentException { try { int cursor = 0 ; char c ; if ( ( c = desc . charAt ( cursor ++ ) ) != ' ' ) { throw invalidDescriptor ( desc ) ; } StringBuffer buf = new StringBuffer ( ) ; List < TypeDesc > list = new ArrayList < TypeDesc > ( ) ; while ( ( c = desc . charAt ( cursor ++ ) ) != ' ' ) { switch ( c ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : buf . append ( c ) ; break ; case ' ' : buf . append ( c ) ; continue ; case ' ' : while ( true ) { buf . append ( c ) ; if ( c == ' ' ) { break ; } c = desc . charAt ( cursor ++ ) ; } break ; default : throw invalidDescriptor ( desc ) ; } list . add ( TypeDesc . forDescriptor ( buf . toString ( ) ) ) ; buf . setLength ( 0 ) ; } TypeDesc ret = TypeDesc . forDescriptor ( desc . substring ( cursor ) ) ; TypeDesc [ ] tds = list . toArray ( new TypeDesc [ list . size ( ) ] ) ; return intern ( new MethodDesc ( desc , ret , tds ) ) ; } catch ( NullPointerException e ) { throw invalidDescriptor ( desc ) ; } catch ( IndexOutOfBoundsException e ) { throw invalidDescriptor ( desc ) ; } } | Acquire a MethodDesc from a type descriptor . | 352 | 10 |
137,557 | public synchronized T get ( final int timeoutMillis ) throws E { if ( mReal != null ) { return mReal ; } if ( mBogus != null && mMinRetryDelayMillis < 0 ) { return mBogus ; } if ( mCreateThread == null ) { mCreateThread = new CreateThread ( ) ; cThreadPool . submit ( mCreateThread ) ; } if ( timeoutMillis != 0 ) { final long start = System . nanoTime ( ) ; try { if ( timeoutMillis < 0 ) { while ( mReal == null && mCreateThread != null ) { if ( timeoutMillis < 0 ) { wait ( ) ; } } } else { long remaining = timeoutMillis ; while ( mReal == null && mCreateThread != null && ! mFailed ) { wait ( remaining ) ; long elapsed = ( System . nanoTime ( ) - start ) / 1000000L ; if ( ( remaining -= elapsed ) <= 0 ) { break ; } } } } catch ( InterruptedException e ) { } if ( mReal != null ) { return mReal ; } long elapsed = ( System . nanoTime ( ) - start ) / 1000000L ; if ( elapsed >= timeoutMillis ) { timedOutNotification ( elapsed ) ; } } if ( mFailedError != null ) { // Take ownership of error. Also stitch traces together for // context. This gives the illusion that the creation attempt // occurred in this thread. Throwable error = mFailedError ; mFailedError = null ; StackTraceElement [ ] trace = error . getStackTrace ( ) ; error . fillInStackTrace ( ) ; StackTraceElement [ ] localTrace = error . getStackTrace ( ) ; StackTraceElement [ ] completeTrace = new StackTraceElement [ trace . length + localTrace . length ] ; System . arraycopy ( trace , 0 , completeTrace , 0 , trace . length ) ; System . arraycopy ( localTrace , 0 , completeTrace , trace . length , localTrace . length ) ; error . setStackTrace ( completeTrace ) ; ThrowUnchecked . fire ( error ) ; } if ( mBogus == null ) { mRef = new AtomicReference < T > ( createBogus ( ) ) ; mBogus = AccessController . doPrivileged ( new PrivilegedAction < T > ( ) { public T run ( ) { try { return getWrapper ( ) . newInstance ( mRef ) ; } catch ( Exception e ) { ThrowUnchecked . fire ( e ) ; return null ; } } } ) ; } return mBogus ; } | Returns real or bogus object . If real object is returned then future invocations of this method return the same real object instance . This method waits for the real object to be created if it is blocked . If real object creation fails immediately then this method will not wait returning a bogus object immediately instead . | 573 | 59 |
137,558 | private Constructor < T > getWrapper ( ) { Class < T > clazz ; synchronized ( cWrapperCache ) { clazz = ( Class < T > ) cWrapperCache . get ( mType ) ; if ( clazz == null ) { clazz = createWrapper ( ) ; cWrapperCache . put ( mType , clazz ) ; } } try { return clazz . getConstructor ( AtomicReference . class ) ; } catch ( NoSuchMethodException e ) { ThrowUnchecked . fire ( e ) ; return null ; } } | Returns a Constructor that accepts an AtomicReference to the wrapped object . | 120 | 14 |
137,559 | public void loadLocal ( LocalVariable local ) { if ( local == null ) { throw new IllegalArgumentException ( "No local variable specified" ) ; } int stackAdjust = local . getType ( ) . isDoubleWord ( ) ? 2 : 1 ; mInstructions . new LoadLocalInstruction ( stackAdjust , local ) ; } | load - local - to - stack style instructions | 71 | 9 |
137,560 | private void nullConvert ( Label end ) { LocalVariable temp = createLocalVariable ( "temp" , TypeDesc . OBJECT ) ; storeLocal ( temp ) ; loadLocal ( temp ) ; Label notNull = createLabel ( ) ; ifNullBranch ( notNull , false ) ; loadNull ( ) ; branch ( end ) ; notNull . setLocation ( ) ; loadLocal ( temp ) ; } | a NullPointerException . Assumes that from type and to type are objects . | 86 | 17 |
137,561 | public void invokeVirtual ( String methodName , TypeDesc ret , TypeDesc [ ] params ) { invokeVirtual ( mClassFile . getClassName ( ) , methodName , ret , params ) ; } | invocation style instructions | 42 | 4 |
137,562 | private Context getContext ( ExecutionContext executionContext ) { // Get context id. HttpServletRequest request = executionContext . getActionBeanContext ( ) . getRequest ( ) ; String parameter = request . getParameter ( ID_PARAMETER ) ; // Return context. if ( parameter != null ) { int id = Integer . parseInt ( parameter , 16 ) ; return contexts . get ( id ) ; } return null ; } | Returns wait context based on context id found in request . | 92 | 11 |
137,563 | private Resolution createContextAndRedirect ( ExecutionContext executionContext , WaitPage annotation ) throws IOException { // Create context used to call the event in background. Context context = this . createContext ( executionContext ) ; context . actionBean = executionContext . getActionBean ( ) ; context . eventHandler = executionContext . getHandler ( ) ; context . annotation = annotation ; context . resolution = new ForwardResolution ( annotation . path ( ) ) ; context . bindingFlashScope = FlashScope . getCurrent ( context . actionBean . getContext ( ) . getRequest ( ) , false ) ; int id = context . hashCode ( ) ; // Id of context. String ids = Integer . toHexString ( id ) ; // Create background request to execute event. HttpServletRequest request = executionContext . getActionBeanContext ( ) . getRequest ( ) ; UrlBuilder urlBuilder = new UrlBuilder ( executionContext . getActionBeanContext ( ) . getLocale ( ) , THREAD_URL , false ) ; // Add parameters from the original request in case there were some parameters that weren't bound but are used @ SuppressWarnings ( { "cast" , "unchecked" } ) Set < Map . Entry < String , String [ ] > > paramSet = ( Set < Map . Entry < String , String [ ] > > ) request . getParameterMap ( ) . entrySet ( ) ; for ( Map . Entry < String , String [ ] > param : paramSet ) for ( String value : param . getValue ( ) ) urlBuilder . addParameter ( param . getKey ( ) , value ) ; urlBuilder . addParameter ( ID_PARAMETER , ids ) ; if ( context . bindingFlashScope != null ) { urlBuilder . addParameter ( StripesConstants . URL_KEY_FLASH_SCOPE_ID , String . valueOf ( context . bindingFlashScope . key ( ) ) ) ; } urlBuilder . addParameter ( StripesConstants . URL_KEY_SOURCE_PAGE , CryptoUtil . encrypt ( executionContext . getActionBeanContext ( ) . getSourcePage ( ) ) ) ; context . url = new URL ( request . getScheme ( ) , request . getServerName ( ) , request . getServerPort ( ) , request . getContextPath ( ) + urlBuilder . toString ( ) ) ; context . cookies = request . getHeader ( "Cookie" ) ; // Save context. contexts . put ( id , context ) ; // Execute background request. context . thread = new Thread ( context ) ; context . thread . start ( ) ; // Redirect user to wait page. return new RedirectResolution ( StripesFilter . getConfiguration ( ) . getActionResolver ( ) . getUrlBinding ( context . actionBean . getClass ( ) ) ) { @ Override public RedirectResolution addParameter ( String key , Object ... value ) { // Leave flash scope to background request. if ( ! StripesConstants . URL_KEY_FLASH_SCOPE_ID . equals ( key ) ) { return super . addParameter ( key , value ) ; } return this ; } } . addParameter ( ID_PARAMETER , ids ) ; } | Create a wait context to execute event in background . | 698 | 10 |
137,564 | protected void copyErrors ( ActionBeanContext source , ActionBeanContext destination ) { destination . getValidationErrors ( ) . putAll ( source . getValidationErrors ( ) ) ; } | Copy errors from a context to another context . | 44 | 9 |
137,565 | protected void removeExpired ( Map < Integer , Context > contexts ) { Iterator < Context > contextsIter = contexts . values ( ) . iterator ( ) ; while ( contextsIter . hasNext ( ) ) { Context context = contextsIter . next ( ) ; if ( context . completeMoment != null && System . currentTimeMillis ( ) - context . completeMoment > contextTimeout ) { contextsIter . remove ( ) ; } } } | Remove all contexts that are expired . | 93 | 7 |
137,566 | public void init ( Configuration configuration ) throws Exception { if ( configuration . getBootstrapPropertyResolver ( ) . getProperty ( CONTEXT_TIMEOUT_NAME ) != null ) { log . debug ( "Configuring context timeout with value " , configuration . getBootstrapPropertyResolver ( ) . getProperty ( CONTEXT_TIMEOUT_NAME ) ) ; try { contextTimeout = Long . parseLong ( configuration . getBootstrapPropertyResolver ( ) . getProperty ( CONTEXT_TIMEOUT_NAME ) ) ; } catch ( NumberFormatException e ) { log . warn ( "Init parameter " , CONTEXT_TIMEOUT_NAME , " is not a parsable long, timeout will be " , " instead" ) ; contextTimeout = DEFAULT_CONTEXT_TIMEOUT ; } } } | Read context timeout if any . | 168 | 6 |
137,567 | public ClassFile [ ] getInnerClasses ( ) { if ( mInnerClasses == null ) { return new ClassFile [ 0 ] ; } return mInnerClasses . toArray ( new ClassFile [ mInnerClasses . size ( ) ] ) ; } | Returns all the inner classes defined in this class . If no inner classes are defined then an array of length zero is returned . | 60 | 25 |
137,568 | public MethodInfo addMethod ( String declaration ) { MethodDeclarationParser p = new MethodDeclarationParser ( declaration ) ; return addMethod ( p . getModifiers ( ) , p . getMethodName ( ) , p . getReturnType ( ) , p . getParameters ( ) ) ; } | Add a method to this class by declaration . | 62 | 9 |
137,569 | public void setTarget ( String target ) throws IllegalArgumentException { int major , minor ; if ( target == null || "1.0" . equals ( target ) || "1.1" . equals ( target ) ) { major = 45 ; minor = 3 ; if ( target == null ) { target = "1.0" ; } } else if ( "1.2" . equals ( target ) ) { major = 46 ; minor = 0 ; } else if ( "1.3" . equals ( target ) ) { major = 47 ; minor = 0 ; } else if ( "1.4" . equals ( target ) ) { major = 48 ; minor = 0 ; } else if ( "1.5" . equals ( target ) ) { major = 49 ; minor = 0 ; } else if ( "1.6" . equals ( target ) ) { major = 50 ; minor = 0 ; } else if ( "1.7" . equals ( target ) ) { major = 51 ; minor = 0 ; } else { throw new IllegalArgumentException ( "Unsupported target version: " + target ) ; } mVersion = ( minor << 16 ) | ( major & 0xffff ) ; mTarget = target . intern ( ) ; } | Specify what target virtual machine version classfile should generate for . Calling this method changes the major and minor version of the classfile format . | 265 | 28 |
137,570 | public void setVersion ( int major , int minor ) { if ( major > 65535 || minor > 65535 ) { throw new IllegalArgumentException ( "Version number element cannot exceed 65535" ) ; } mVersion = ( minor << 16 ) | ( major & 0xffff ) ; String target ; switch ( major ) { default : target = null ; break ; case 45 : target = minor == 3 ? "1.0" : null ; break ; case 46 : target = minor == 0 ? "1.2" : null ; break ; case 47 : target = minor == 0 ? "1.3" : null ; break ; case 48 : target = minor == 0 ? "1.4" : null ; break ; case 49 : target = minor == 0 ? "1.5" : null ; break ; case 50 : target = minor == 0 ? "1.6" : null ; break ; case 51 : target = minor == 0 ? "1.7" : null ; break ; } mTarget = target ; } | Sets the version to use when writing the generated classfile overriding the target . | 217 | 16 |
137,571 | public static void main ( String [ ] args ) throws Exception { if ( args . length == 0 ) { System . out . println ( "DisassemblyTool [-f <format style>] <file or class name>" ) ; System . out . println ( ) ; System . out . println ( "The format style may be \"assembly\" (the default) or \"builder\"" ) ; return ; } String style ; String name ; if ( "-f" . equals ( args [ 0 ] ) ) { style = args [ 1 ] ; name = args [ 2 ] ; } else { style = "assembly" ; name = args [ 0 ] ; } ClassFileDataLoader loader ; InputStream in ; try { final File file = new File ( name ) ; in = new FileInputStream ( file ) ; loader = new ClassFileDataLoader ( ) { public InputStream getClassData ( String name ) throws IOException { name = name . substring ( name . lastIndexOf ( ' ' ) + 1 ) ; File f = new File ( file . getParentFile ( ) , name + ".class" ) ; if ( f . exists ( ) ) { return new FileInputStream ( f ) ; } return null ; } } ; } catch ( FileNotFoundException e ) { if ( name . endsWith ( ".class" ) ) { System . err . println ( e ) ; return ; } loader = new ResourceClassFileDataLoader ( ) ; in = loader . getClassData ( name ) ; if ( in == null ) { System . err . println ( e ) ; return ; } } in = new BufferedInputStream ( in ) ; ClassFile cf = ClassFile . readFrom ( in , loader , null ) ; PrintWriter out = new PrintWriter ( System . out ) ; Printer p ; if ( style == null || style . equals ( "assembly" ) ) { p = new AssemblyStylePrinter ( ) ; } else if ( style . equals ( "builder" ) ) { p = new BuilderStylePrinter ( ) ; } else { System . err . println ( "Unknown format style: " + style ) ; return ; } p . disassemble ( cf , out ) ; out . flush ( ) ; } | Disassembles a class file sending the results to standard out . | 469 | 13 |
137,572 | protected Boolean determineAccessOnElement ( ActionBean bean , Method handler , AnnotatedElement element ) { // Default decision: none. Boolean allowed = null ; if ( element . isAnnotationPresent ( DenyAll . class ) ) { // The element denies access. allowed = false ; } else if ( element . isAnnotationPresent ( PermitAll . class ) ) { // The element allows access to all security roles (i.e. any authenticated user). allowed = isUserAuthenticated ( bean , handler ) ; } else { RolesAllowed rolesAllowed = element . getAnnotation ( RolesAllowed . class ) ; if ( rolesAllowed != null ) { // Still need to check if the users is authorized allowed = isUserAuthenticated ( bean , handler ) ; if ( allowed == null || allowed . booleanValue ( ) ) { // The element allows access if the user has one of the specified roles. allowed = false ; for ( String role : rolesAllowed . value ( ) ) { Boolean hasRole = hasRole ( bean , handler , role ) ; if ( hasRole != null && hasRole ) { allowed = true ; break ; } } } } } return allowed ; } | Decide if the annotated element allows access to the current user . | 252 | 14 |
137,573 | public void init ( Configuration configuration ) throws Exception { bundleName = configuration . getServletContext ( ) . getInitParameter ( Config . FMT_LOCALIZATION_CONTEXT ) ; if ( bundleName == null ) { throw new StripesRuntimeException ( "JSTL has no resource bundle configured. Please set the context " + "parameter " + Config . FMT_LOCALIZATION_CONTEXT + " to the name of the " + "ResourceBundle to use." ) ; } } | Invoked directly after instantiation to allow the configured component to perform one time initialization . Components are expected to fail loudly if they are not going to be in a valid state after initialization . | 108 | 37 |
137,574 | public void run ( ) { try { // Open connection to URL calling this interceptor. HttpURLConnection connection = ( HttpURLConnection ) url . openConnection ( ) ; // Pass in the session id cookie to maintain the same session. log . trace ( "passing in cookies: " , cookies ) ; connection . setRequestProperty ( "Cookie" , cookies ) ; // Invoke event in background. byte [ ] buff = new byte [ 1024 * 4 ] ; InputStream input = connection . getInputStream ( ) ; try { while ( input . read ( buff ) > - 1 ) ; } finally { input . close ( ) ; } } catch ( Exception e ) { // Log any exception that could have occurred. log . error ( e ) ; } } | Invoke event in a background request . | 161 | 8 |
137,575 | public Class defineClass ( ) { byte [ ] bytes ; try { ByteArrayOutputStream bout = new ByteArrayOutputStream ( ) ; writeTo ( bout ) ; bytes = bout . toByteArray ( ) ; } catch ( IOException e ) { InternalError ie = new InternalError ( e . toString ( ) ) ; ie . initCause ( e ) ; throw ie ; } if ( DEBUG ) { File file = new File ( getClassName ( ) . replace ( ' ' , ' ' ) + ".class" ) ; try { File tempDir = new File ( System . getProperty ( "java.io.tmpdir" ) ) ; file = new File ( tempDir , file . getPath ( ) ) ; } catch ( SecurityException e ) { } try { file . getParentFile ( ) . mkdirs ( ) ; System . out . println ( "RuntimeClassFile writing to " + file ) ; OutputStream out = new FileOutputStream ( file ) ; out . write ( bytes ) ; out . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } return mLoader . define ( getClassName ( ) , bytes ) ; } | Finishes the class definition . | 253 | 6 |
137,576 | private static int hashCapacity ( int min ) { BigInteger capacity = BigInteger . valueOf ( min * 2 + 1 ) ; while ( ! capacity . isProbablePrime ( 10 ) ) { capacity = capacity . add ( BigInteger . valueOf ( 2 ) ) ; } return capacity . intValue ( ) ; } | Returns a prime number at least twice as large as needed . This should minimize hash collisions . Since all the hash keys are known up front the capacity could be tweaked until there are no collisions but this technique is easier and deterministic . | 68 | 46 |
137,577 | private static List [ ] caseMethods ( int caseCount , BeanProperty [ ] props ) { List [ ] cases = new List [ caseCount ] ; for ( int i = 0 ; i < props . length ; i ++ ) { BeanProperty prop = props [ i ] ; int hashCode = prop . getName ( ) . hashCode ( ) ; int caseValue = ( hashCode & 0x7fffffff ) % caseCount ; List matches = cases [ caseValue ] ; if ( matches == null ) { matches = cases [ caseValue ] = new ArrayList ( ) ; } matches . add ( prop ) ; } return cases ; } | Returns an array of Lists of BeanProperties . The first index matches a switch case the second index provides a list of all the BeanProperties whose name hash matched on the case . | 134 | 37 |
137,578 | private static BeanProperty [ ] [ ] getBeanProperties ( Class beanType , PropertySet set ) { List readProperties = new ArrayList ( ) ; List writeProperties = new ArrayList ( ) ; Map map = BeanIntrospector . getAllProperties ( beanType ) ; Iterator it = map . values ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { BeanProperty bp = ( BeanProperty ) it . next ( ) ; if ( set == PropertySet . READ_WRITE || set == PropertySet . READ_WRITE_UNCHECKED_EXCEPTIONS ) { if ( bp . getReadMethod ( ) == null || bp . getWriteMethod ( ) == null ) { continue ; } } boolean checkedAllowed = set != PropertySet . UNCHECKED_EXCEPTIONS && set != PropertySet . READ_WRITE_UNCHECKED_EXCEPTIONS ; if ( bp . getReadMethod ( ) != null ) { if ( checkedAllowed || ! throwsCheckedException ( bp . getReadMethod ( ) ) ) { readProperties . add ( bp ) ; } } if ( bp . getWriteMethod ( ) != null ) { if ( checkedAllowed || ! throwsCheckedException ( bp . getWriteMethod ( ) ) ) { writeProperties . add ( bp ) ; } } } BeanProperty [ ] [ ] props = new BeanProperty [ 2 ] [ ] ; props [ 0 ] = new BeanProperty [ readProperties . size ( ) ] ; readProperties . toArray ( props [ 0 ] ) ; props [ 1 ] = new BeanProperty [ writeProperties . size ( ) ] ; writeProperties . toArray ( props [ 1 ] ) ; return props ; } | Returns two arrays of BeanProperties . Array 0 contains read BeanProperties array 1 contains the write BeanProperties . | 380 | 24 |
137,579 | public OutputStream openStream ( ) throws IllegalStateException { if ( mClass != null ) { throw new IllegalStateException ( "New class has already been defined" ) ; } ByteArrayOutputStream data = mData ; if ( data != null ) { throw new IllegalStateException ( "Stream already opened" ) ; } mData = data = new ByteArrayOutputStream ( ) ; return data ; } | Open a stream to define the new class into . | 84 | 10 |
137,580 | public Class defineClass ( ClassFile cf ) { try { cf . writeTo ( openStream ( ) ) ; } catch ( IOException e ) { throw new InternalError ( e . toString ( ) ) ; } return getNewClass ( ) ; } | Define the new class from a ClassFile object . | 53 | 11 |
137,581 | public Class getNewClass ( ) throws IllegalStateException , ClassFormatError { if ( mClass != null ) { return mClass ; } ByteArrayOutputStream data = mData ; if ( data == null ) { throw new IllegalStateException ( "Class not defined yet" ) ; } byte [ ] bytes = data . toByteArray ( ) ; if ( DEBUG ) { File file = new File ( mName . replace ( ' ' , ' ' ) + ".class" ) ; try { File tempDir = new File ( System . getProperty ( "java.io.tmpdir" ) ) ; file = new File ( tempDir , file . getPath ( ) ) ; } catch ( SecurityException e ) { } try { file . getParentFile ( ) . mkdirs ( ) ; System . out . println ( "ClassInjector writing to " + file ) ; OutputStream out = new FileOutputStream ( file ) ; out . write ( bytes ) ; out . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } mClass = mLoader . define ( mName , bytes ) ; mData = null ; return mClass ; } | Returns the newly defined class . | 252 | 6 |
137,582 | int available ( Context context ) { // package protected for access from I/O streams return context . buffer != null ? context . pos - context . readPos : 0 ; } | Returns the amount of buffered data available for reading . | 36 | 11 |
137,583 | public static Map < String , Object > parseData ( String data ) { Map < String , Object > ret = new HashMap < String , Object > ( ) ; String [ ] split = data . split ( "&" ) ; for ( String s : split ) { int idx = s . indexOf ( ' ' ) ; try { if ( idx != - 1 ) { ret . put ( URLDecoder . decode ( s . substring ( 0 , idx ) , "UTF-8" ) , URLDecoder . decode ( s . substring ( idx + 1 ) , "UTF-8" ) ) ; } else { ret . put ( URLDecoder . decode ( s , "UTF-8" ) , "true" ) ; } } catch ( UnsupportedEncodingException e ) { // Why. } } return ret ; } | Parse POST data or GET data from the request URI | 181 | 11 |
137,584 | public static String capitalizeHeader ( String header ) { StringTokenizer st = new StringTokenizer ( header , "-" ) ; StringBuilder out = new StringBuilder ( ) ; while ( st . hasMoreTokens ( ) ) { String l = st . nextToken ( ) ; out . append ( Character . toUpperCase ( l . charAt ( 0 ) ) ) ; if ( l . length ( ) > 1 ) { out . append ( l . substring ( 1 ) ) ; } if ( st . hasMoreTokens ( ) ) out . append ( ' ' ) ; } return out . toString ( ) ; } | Fixes capitalization on headers | 131 | 6 |
137,585 | private ExternalNode3 combineExternalNodes ( ExternalNode3 n1 , ExternalNode3 n2 ) { if ( n1 == null || n2 == null ) { throw new IllegalArgumentException ( "Input nodes must not be null" ) ; } DecisionType combinedDecision = algo . combine ( n1 . getDecision ( ) , n2 . getDecision ( ) ) ; ExternalNode3 n = new ExternalNode3 ( combinedDecision ) ; // only accept OE that match with combined decision. List < ObligationExpression > oes1 = getFulfilledObligationExpressions ( n1 . getObligationExpressions ( ) , combinedDecision ) ; List < ObligationExpression > oes2 = getFulfilledObligationExpressions ( n2 . getObligationExpressions ( ) , combinedDecision ) ; n . getObligationExpressions ( ) . addAll ( oes1 ) ; n . getObligationExpressions ( ) . addAll ( oes2 ) ; return n ; } | Combine two external nodes following the algorithm in this . algo | 229 | 13 |
137,586 | private List < ObligationExpression > getFulfilledObligationExpressions ( List < ObligationExpression > oes , DecisionType decision ) { List < ObligationExpression > fulfilledOEs = new ArrayList < ObligationExpression > ( ) ; if ( oes != null && oes . size ( ) > 0 ) { for ( ObligationExpression oe : oes ) { if ( oe . isFulfilled ( decision ) ) { fulfilledOEs . add ( oe ) ; } } } return fulfilledOEs ; } | Return OE in the list that are fulfilled the indicated decision . | 124 | 13 |
137,587 | private InternalNodeState combineInternalNodeStates ( InternalNodeState inState , ExternalNode3 externalNode ) { ExternalNode3 n1 = inState . getExternalNode ( ) ; ExternalNode3 n = combineExternalNodes ( n1 , externalNode ) ; return new InternalNodeState ( n ) ; } | Combine an indeterminate state of an internal node with an external node which use indicated combining algorithm . | 64 | 21 |
137,588 | @ SuppressWarnings ( "rawtypes" ) private void setEffectNode ( AbstractNode midd , ExternalNode3 extNode ) throws MIDDException { // Replace current external nodes in the MIDD with the extNode (XACML 3 external node) if ( ! ( midd instanceof InternalNode ) ) { throw new IllegalArgumentException ( "MIDD argument must not be an ExternalNode" ) ; } InternalNode currentNode = ( InternalNode ) midd ; Stack < InternalNode > stackNodes = new Stack < InternalNode > ( ) ; stackNodes . push ( currentNode ) ; while ( ! stackNodes . empty ( ) ) { InternalNode n = stackNodes . pop ( ) ; // Change indeterminate state of the internal node, // - By default is NotApplicable (XACML 3.0, sec 7.3.5, 7.19.3) // - If the attribute "MustBePresent" is true, then state is "Indeterminate_P" if Effect is "Permit", // "Indeterminate_D" if Effect is "Deny" - XACML 3.0, section 7.11 if ( n . getStateIN ( ) == DecisionType . Indeterminate ) { // this attribute has 'MustBePresent'=true if ( ruleEffect == DecisionType . Deny ) { n . setState ( new InternalNodeState ( nl . uva . sne . midd . DecisionType . Indeterminate_D ) ) ; } else if ( ruleEffect == DecisionType . Permit ) { n . setState ( new InternalNodeState ( nl . uva . sne . midd . DecisionType . Indeterminate_P ) ) ; } } // else { // n.setState(new InternalNodeState(nl.uva.sne.midd.DecisionType.NotApplicable)); // } // search for all children of the poped internal node @ SuppressWarnings ( "unchecked" ) Iterator < AbstractEdge > it = n . getEdges ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { AbstractEdge edge = it . next ( ) ; AbstractNode child = edge . getSubDiagram ( ) ; if ( child instanceof InternalNode ) { stackNodes . push ( ( InternalNode ) child ) ; } else { edge . setSubDiagram ( extNode ) ; // set the final edge pointing to the xacml3 external node. } } } } | Set indicated external - xacml3 node to be the leaves of the MIDD | 538 | 17 |
137,589 | public int read ( ) throws IOException { if ( leftover != null && leftover . remaining ( ) > 0 ) { int b = leftover . get ( ) ; if ( leftover . remaining ( ) == 0 ) { leftover = null ; } return b ; } return input . read ( ) ; } | Read a single byte except it will try to use the leftover bytes from the previous read first . | 61 | 19 |
137,590 | public String readLine ( ) throws IOException { StringBuilder bldr = new StringBuilder ( ) ; while ( true ) { int b = read ( ) ; if ( b == - 1 || b == 10 ) { break ; } else if ( b != ' ' ) { bldr . append ( ( char ) ( ( byte ) b ) ) ; } } return bldr . toString ( ) ; } | Reads a line up until \ r \ n This will act similar to BufferedReader . readLine | 88 | 21 |
137,591 | public String readLineUntilBoundary ( ) throws IOException { StringBuilder bldr = new StringBuilder ( ) ; while ( true ) { int b = read ( ) ; if ( bldr . indexOf ( boundary ) == 0 ) { leftover = ByteBuffer . wrap ( boundaryBytes ) ; return null ; } else if ( b == - 1 || b == 10 ) { break ; } else if ( b != ' ' ) { bldr . append ( ( char ) ( ( byte ) b ) ) ; } } return bldr . toString ( ) ; } | Reads a line up until \ r \ n OR the boundary This will act similar to BufferedReader . readLine except that it will stop at the defined boundary . | 122 | 34 |
137,592 | public static < V > V defaultIfException ( StatementWithReturnValue < V > statement , Class < ? extends Throwable > exceptionType , V defaultValue ) { try { return statement . evaluate ( ) ; } catch ( RuntimeException e ) { if ( exceptionType . isAssignableFrom ( e . getClass ( ) ) ) return defaultValue ; else throw e ; } catch ( Error e ) { if ( exceptionType . isAssignableFrom ( e . getClass ( ) ) ) return defaultValue ; else throw e ; } catch ( Throwable e ) { if ( exceptionType . isAssignableFrom ( e . getClass ( ) ) ) return defaultValue ; else throw new WrappedException ( e ) ; } } | Executes the given statement and returns the statement s return value if no exception is thrown or the default value if an exception of the specified type is thrown . | 155 | 31 |
137,593 | public String getValue ( String key ) { KeyValue kv = getKV ( key ) ; return kv == null ? null : kv . getValue ( ) ; } | Get the value for the key | 38 | 6 |
137,594 | public void setValue ( String key , String value ) { KeyValue kv = getKV ( key ) ; if ( kv != null ) { kv . setValue ( value ) ; } else if ( key != null ) { map . add ( new KeyValue ( key , value ) ) ; } } | Null value is totally legal! | 66 | 6 |
137,595 | public void removeKey ( String key ) { if ( key != null && ! key . isEmpty ( ) ) { for ( int i = 0 ; i < map . size ( ) ; i ++ ) { KeyValue kv = map . get ( i ) ; if ( key . equals ( kv . getKey ( ) ) ) { map . remove ( i ) ; return ; } } } } | Remove mappings for given key | 84 | 6 |
137,596 | public boolean match ( final T value ) throws MIDDException { for ( Interval < T > interval : this . intervals ) { if ( interval . hasValue ( value ) ) { return true ; } } return false ; } | Check if the value is matched with the edge s intervals | 47 | 11 |
137,597 | protected final < T > void doBind ( Multibinder < T > binder , Class < ? extends T > type ) { checkNotNull ( type ) ; binder . addBinding ( ) . to ( type ) ; } | Utility method to respect the DRY principle . | 49 | 10 |
137,598 | @ SuppressWarnings ( "unchecked" ) public void addChild ( final AbstractEdge < ? > edge , final AbstractNode child ) { if ( child == null || edge == null || edge . getIntervals ( ) == null || edge . getIntervals ( ) . size ( ) == 0 ) { throw new IllegalArgumentException ( "Cannot add null child or empty edge" ) ; } edge . setSubDiagram ( child ) ; edges . add ( ( AbstractEdge < T > ) edge ) ; } | Create an out - going edge to the given node . The edge and child node are mutable objects . If they are used in another tree it d better to clone before adding them . | 111 | 37 |
137,599 | public AbstractNode getChild ( Interval < T > interval ) throws MIDDException { for ( AbstractEdge < T > e : this . edges ) { if ( e . containsInterval ( interval ) ) { return e . getSubDiagram ( ) ; } } return null ; } | Return the child of the current node with equivalent interval on its incoming edge . | 60 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.