idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
14,100 | 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 . |
14,101 | public void init ( Configuration configuration ) throws Exception { String baseName = configuration . getBootstrapPropertyResolver ( ) . getProperty ( "ResourceBundleFactory.Bundle" ) ; if ( baseName != null ) { this . baseName = baseName ; } } | Initialize the bundle factory . |
14,102 | 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 . |
14,103 | 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 ; 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 ( ) ) ) { 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 . |
14,104 | 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 . |
14,105 | 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 . |
14,106 | 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 . |
14,107 | public R visit ( String name , int pos , String value , P param ) { return null ; } | Override to visit Strings . |
14,108 | 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 . |
14,109 | public int doStartTag ( ) throws JspException { ActionBean actionBean ; if ( bean == null ) { actionBean = ( ActionBean ) pageContext . findAttribute ( StripesConstants . REQ_ATTR_ACTION_BEAN ) ; LOG . debug ( "Determining access for the action bean of the form: " , actionBean ) ; } else { 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 ) ; } 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 ; } 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 . |
14,110 | 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 . |
14,111 | 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 . |
14,112 | 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 . |
14,113 | 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 . |
14,114 | public Resolution intercept ( ExecutionContext executionContext ) throws Exception { Resolution resolution ; if ( securityManager != null ) { 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 : resolution = executionContext . proceed ( ) ; break ; } } else { resolution = executionContext . proceed ( ) ; } return resolution ; } | Intercept execution . |
14,115 | protected Resolution interceptEventHandling ( ExecutionContext executionContext ) throws Exception { 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 . |
14,116 | public static TypeDesc forDescriptor ( final String desc ) throws IllegalArgumentException { TypeDesc type = cDescriptorsToInstances . get ( desc ) ; if ( type != null ) { return type ; } String rootDesc = desc ; int cursor = 0 ; int dim = 0 ; try { char c ; while ( ( c = rootDesc . charAt ( cursor ++ ) ) == '[' ) { dim ++ ; } switch ( c ) { case 'V' : type = VOID ; break ; case 'Z' : type = BOOLEAN ; break ; case 'C' : type = CHAR ; break ; case 'B' : type = BYTE ; break ; case 'S' : type = SHORT ; break ; case 'I' : type = INT ; break ; case 'J' : type = LONG ; break ; case 'F' : type = FLOAT ; break ; case 'D' : type = DOUBLE ; break ; case 'L' : 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 . |
14,117 | public void valueUnbound ( HttpSessionBindingEvent event ) { for ( SessionFieldMapper fieldMapper : this . values ( ) ) { if ( fieldMapper . runnable != null ) fieldMapper . runnable . cancel ( ) ; } } | Cancel all threads from field mappers . |
14,118 | 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 . |
14,119 | 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 ) { 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 . |
14,120 | protected void setMessageResourceBundle ( HttpServletRequest request , ResourceBundle bundle ) { request . setAttribute ( REQ_ATTR_MESSAGE_RESOURCE_BUNDLE , bundle ) ; } | Puts the resource bundle as a request - scope attribute . |
14,121 | public List < ProblemInput > getProblemInputs ( ) { return ( inputs == null ? Collections . emptyList ( ) : Arrays . asList ( inputs ) ) ; } | Getter for the problem inputs . |
14,122 | 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 . |
14,123 | 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 . |
14,124 | 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 . |
14,125 | 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 . |
14,126 | 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 ; } 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 |
14,127 | 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 . |
14,128 | 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 ( ) ) ) { Object value = session . getAttribute ( getFieldKey ( field , actionBean . getClass ( ) ) ) ; if ( ! ( value == null && field . getType ( ) . isPrimitive ( ) ) ) { field . set ( actionBean , value ) ; } } } } } | Restore all fields from value stored in session except if they . |
14,129 | protected Set < String > getParameters ( HttpServletRequest request ) { Set < String > parameters = new HashSet < String > ( ) ; Enumeration < ? > paramNames = request . getParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { String parameter = ( String ) paramNames . nextElement ( ) ; 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 . |
14,130 | protected String getFieldKey ( Field field , Class < ? extends ActionBean > actionBeanClass ) { String sessionKey = ( ( Session ) field . getAnnotation ( Session . class ) ) . key ( ) ; if ( sessionKey != null && ! "" . equals ( sessionKey ) ) { return sessionKey ; } else { return actionBeanClass + "#" + field . getName ( ) ; } } | Returns session key under which field should be saved or read . |
14,131 | 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 . |
14,132 | public static Object getAttribute ( HttpSession session , String key ) { return session . getAttribute ( key ) ; } | Returns an object in session . |
14,133 | protected Object setAttribute ( HttpSession session , String key , Object object , boolean serializable , int maxTime ) { if ( object == null ) { Object ret ; synchronized ( session ) { ret = session . getAttribute ( key ) ; session . removeAttribute ( key ) ; } return ret ; } else { Object ret ; synchronized ( session ) { ret = session . getAttribute ( key ) ; session . setAttribute ( key , object ) ; } SessionMapper mapper = ( SessionMapper ) session . getAttribute ( MAPPER_ATTRIBUTE ) ; if ( mapper == null ) { mapper = new SessionMapper ( ) ; session . setAttribute ( MAPPER_ATTRIBUTE , mapper ) ; } synchronized ( mapper ) { SessionFieldMapper fieldMapper = mapper . get ( key ) ; if ( fieldMapper == null ) { fieldMapper = new SessionFieldMapper ( serializable && object instanceof Serializable ) ; mapper . put ( key , fieldMapper ) ; } if ( maxTime > 0 ) { if ( fieldMapper . runnable != null ) { fieldMapper . runnable . cancel ( ) ; } RemoveFieldRunnable runnable = new RemoveFieldRunnable ( key , maxTime , session ) ; fieldMapper . runnable = runnable ; ( new Thread ( runnable ) ) . start ( ) ; } } return ret ; } } | Saves an object in session for latter use . |
14,134 | 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 . |
14,135 | 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 . |
14,136 | private Object evaluateRoleExpression ( ActionBean bean , String expression ) { try { LOG . debug ( "Evaluating expression: '" + expression + '\'' ) ; 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 . |
14,137 | 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 'V' : case 'I' : case 'C' : case 'Z' : case 'D' : case 'F' : case 'J' : case 'B' : case 'S' : buf . append ( c ) ; break ; case '[' : buf . append ( c ) ; continue ; case 'L' : 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 . |
14,138 | 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 ) { 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 . |
14,139 | 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 . |
14,140 | 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 |
14,141 | 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 . |
14,142 | public void invokeVirtual ( String methodName , TypeDesc ret , TypeDesc [ ] params ) { invokeVirtual ( mClassFile . getClassName ( ) , methodName , ret , params ) ; } | invocation style instructions |
14,143 | private Context getContext ( ExecutionContext executionContext ) { HttpServletRequest request = executionContext . getActionBeanContext ( ) . getRequest ( ) ; String parameter = request . getParameter ( ID_PARAMETER ) ; 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 . |
14,144 | private Resolution createContextAndRedirect ( ExecutionContext executionContext , WaitPage annotation ) throws IOException { 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 ( ) ; String ids = Integer . toHexString ( id ) ; HttpServletRequest request = executionContext . getActionBeanContext ( ) . getRequest ( ) ; UrlBuilder urlBuilder = new UrlBuilder ( executionContext . getActionBeanContext ( ) . getLocale ( ) , THREAD_URL , false ) ; @ 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" ) ; contexts . put ( id , context ) ; context . thread = new Thread ( context ) ; context . thread . start ( ) ; return new RedirectResolution ( StripesFilter . getConfiguration ( ) . getActionResolver ( ) . getUrlBinding ( context . actionBean . getClass ( ) ) ) { public RedirectResolution addParameter ( String key , Object ... value ) { 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 . |
14,145 | private Resolution checkStatus ( ExecutionContext executionContext , Context context ) throws Exception { synchronized ( context . actionBean ) { if ( context . status == Context . Status . INIT ) { if ( context . annotation . delay ( ) > 0 ) context . actionBean . wait ( context . annotation . delay ( ) ) ; if ( context . status == Context . Status . INIT ) { context . status = Context . Status . WAITING ; } } else if ( context . status == Context . Status . WAITING ) { log . trace ( "waiting to be signaled" ) ; context . actionBean . wait ( context . annotation . refresh ( ) > 0 ? context . annotation . refresh ( ) : DEFAULT_REFRESH_TIMEOUT ) ; } Resolution resolution = context . resolution ; executionContext . setActionBean ( context . actionBean ) ; executionContext . getActionBeanContext ( ) . getRequest ( ) . setAttribute ( "actionBean" , context . actionBean ) ; executionContext . getActionBeanContext ( ) . getRequest ( ) . setAttribute ( StripesFilter . getConfiguration ( ) . getActionResolver ( ) . getUrlBinding ( context . actionBean . getClass ( ) ) , context . actionBean ) ; if ( context . bindingFlashScope != null ) { this . copyFlashScope ( context . bindingFlashScope , FlashScope . getCurrent ( executionContext . getActionBeanContext ( ) . getRequest ( ) , true ) ) ; } if ( context . eventFlashScope != null ) { this . copyFlashScope ( context . eventFlashScope , FlashScope . getCurrent ( executionContext . getActionBeanContext ( ) . getRequest ( ) , true ) ) ; } if ( executionContext . getActionBeanContext ( ) . getRequest ( ) . getParameter ( AJAX ) != null ) { resolution = new ForwardResolution ( context . annotation . ajax ( ) . length ( ) > 0 ? context . annotation . ajax ( ) : context . annotation . path ( ) ) ; } else if ( context . status == Context . Status . COMPLETE ) { log . trace ( "the processor is finished so we'll remove it from the map" ) ; contexts . remove ( context . hashCode ( ) ) ; this . copyErrors ( context . actionBean . getContext ( ) , executionContext . getActionBeanContext ( ) ) ; context . actionBean . setContext ( executionContext . getActionBeanContext ( ) ) ; if ( context . throwable != null ) { if ( ( "" . equals ( context . annotation . error ( ) ) ) && ( context . throwable instanceof Exception ) ) { throw ( Exception ) context . throwable ; } else { executionContext . getActionBeanContext ( ) . getRequest ( ) . setAttribute ( "exception" , context . throwable ) ; resolution = new ForwardResolution ( context . annotation . error ( ) ) ; } } executionContext . setResolution ( resolution ) ; } return resolution ; } } | Return wait page resolution or event s resolution depending on completion status . |
14,146 | protected void copyErrors ( ActionBeanContext source , ActionBeanContext destination ) { destination . getValidationErrors ( ) . putAll ( source . getValidationErrors ( ) ) ; } | Copy errors from a context to another context . |
14,147 | 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 . |
14,148 | 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 . |
14,149 | 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 . |
14,150 | 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 . |
14,151 | 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 . |
14,152 | 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 . |
14,153 | 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 . |
14,154 | protected Boolean determineAccessOnElement ( ActionBean bean , Method handler , AnnotatedElement element ) { Boolean allowed = null ; if ( element . isAnnotationPresent ( DenyAll . class ) ) { allowed = false ; } else if ( element . isAnnotationPresent ( PermitAll . class ) ) { allowed = isUserAuthenticated ( bean , handler ) ; } else { RolesAllowed rolesAllowed = element . getAnnotation ( RolesAllowed . class ) ; if ( rolesAllowed != null ) { allowed = isUserAuthenticated ( bean , handler ) ; if ( allowed == null || allowed . booleanValue ( ) ) { 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 . |
14,155 | 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 . |
14,156 | public void run ( ) { try { HttpURLConnection connection = ( HttpURLConnection ) url . openConnection ( ) ; log . trace ( "passing in cookies: " , cookies ) ; connection . setRequestProperty ( "Cookie" , cookies ) ; byte [ ] buff = new byte [ 1024 * 4 ] ; InputStream input = connection . getInputStream ( ) ; try { while ( input . read ( buff ) > - 1 ) ; } finally { input . close ( ) ; } } catch ( Exception e ) { log . error ( e ) ; } } | Invoke event in a background request . |
14,157 | 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 . |
14,158 | 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 . |
14,159 | 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 . |
14,160 | 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 . |
14,161 | 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 . |
14,162 | 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 . |
14,163 | 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 . |
14,164 | int available ( Context context ) { return context . buffer != null ? context . pos - context . readPos : 0 ; } | Returns the amount of buffered data available for reading . |
14,165 | 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 ) { } } return ret ; } | Parse POST data or GET data from the request URI |
14,166 | 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 |
14,167 | 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 ) ; 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 |
14,168 | 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 . |
14,169 | 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 . |
14,170 | @ SuppressWarnings ( "rawtypes" ) private void setEffectNode ( AbstractNode midd , ExternalNode3 extNode ) throws MIDDException { 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 ( ) ; if ( n . getStateIN ( ) == DecisionType . Indeterminate ) { 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 ) ) ; } } @ 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 indicated external - xacml3 node to be the leaves of the MIDD |
14,171 | 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 . |
14,172 | public String readLine ( ) throws IOException { StringBuilder bldr = new StringBuilder ( ) ; while ( true ) { int b = read ( ) ; if ( b == - 1 || b == 10 ) { break ; } else if ( b != '\r' ) { bldr . append ( ( char ) ( ( byte ) b ) ) ; } } return bldr . toString ( ) ; } | Reads a line up until \ r \ n This will act similar to BufferedReader . readLine |
14,173 | 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 != '\r' ) { 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 . |
14,174 | 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 . |
14,175 | public String getValue ( String key ) { KeyValue kv = getKV ( key ) ; return kv == null ? null : kv . getValue ( ) ; } | Get the value for the key |
14,176 | 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! |
14,177 | 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 |
14,178 | 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 |
14,179 | 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 . |
14,180 | @ 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 . |
14,181 | 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 . |
14,182 | @ SuppressWarnings ( "rawtypes" ) public List < Interval > getIntervals ( ) { List < Interval > lstIntervals = new ArrayList < Interval > ( ) ; for ( AbstractEdge < T > e : this . edges ) { lstIntervals . addAll ( e . getIntervals ( ) ) ; } return lstIntervals ; } | Collect all intervals of all outgoing edges |
14,183 | public AbstractEdge < T > match ( T value ) throws UnmatchedException , MIDDException { for ( AbstractEdge < T > e : this . edges ) { if ( e . match ( value ) ) { return e ; } } throw new UnmatchedException ( "No matching edge found for value " + value ) ; } | Return an edge to match with input value |
14,184 | public AbstractNode createFromConjunctionClauses ( Map < String , AttributeInfo > intervals ) throws MIDDParsingException , MIDDException { if ( intervals == null || intervals . size ( ) == 0 ) { return ExternalNode . newInstance ( ) ; } Map < Integer , AbstractEdge < ? > > edges = new HashMap < Integer , AbstractEdge < ? > > ( ) ; for ( String attrId : intervals . keySet ( ) ) { int varId = attrMapper . getVariableId ( attrId ) ; Interval < ? > interval = intervals . get ( attrId ) . getInterval ( ) ; Class < ? > type = interval . getType ( ) ; AbstractEdge < ? > e = EdgeUtils . createEdge ( interval ) ; edges . put ( varId , e ) ; } List < Integer > lstVarIds = new ArrayList < Integer > ( edges . keySet ( ) ) ; Collections . sort ( lstVarIds ) ; InternalNode < ? > root = null ; InternalNode < ? > currentNode = null ; AbstractEdge < ? > currentEdge = null ; Iterator < Integer > lstIt = lstVarIds . iterator ( ) ; while ( lstIt . hasNext ( ) ) { Integer varId = lstIt . next ( ) ; AbstractEdge < ? > e = edges . get ( varId ) ; String attrId = attrMapper . getAttributeId ( varId ) ; boolean isAttrMustBePresent = intervals . get ( attrId ) . isMustBePresent ; InternalNodeState nodeState = new InternalNodeState ( isAttrMustBePresent ? DecisionType . Indeterminate : DecisionType . NotApplicable ) ; InternalNode < ? > node = NodeUtils . createInternalNode ( varId , nodeState , e . getType ( ) ) ; if ( root == null ) { root = node ; currentNode = node ; currentEdge = e ; } else { currentNode . addChild ( currentEdge , node ) ; currentNode = node ; currentEdge = e ; } } currentNode . addChild ( currentEdge , ExternalNode . newInstance ( ) ) ; return root ; } | Create a MIDD from conjunctions of intervals |
14,185 | private final static byte [ ] getAlphabet ( final int options ) { if ( ( options & Base64 . URL_SAFE ) == Base64 . URL_SAFE ) { return Base64 . _URL_SAFE_ALPHABET ; } else if ( ( options & Base64 . ORDERED ) == Base64 . ORDERED ) { return Base64 . _ORDERED_ALPHABET ; } else { return Base64 . _STANDARD_ALPHABET ; } } | Returns one of the _SOMETHING_ALPHABET byte arrays depending on the options specified . It s possible though silly to specify ORDERED and URLSAFE in which case one of them will be picked though there is no guarantee as to which one will be picked . |
14,186 | private final static void usage ( final String msg ) { System . err . println ( msg ) ; System . err . println ( "Usage: java Base64 -e|-d inputfile outputfile" ) ; } | Prints command line usage . |
14,187 | public String toHeader ( ) { StringBuilder header = new StringBuilder ( ) ; header . append ( name ) . append ( '=' ) . append ( value ) ; if ( domain != null ) { header . append ( "; " ) . append ( "Domain=" ) . append ( domain ) ; } if ( path != null ) { header . append ( "; " ) . append ( "Path=" ) . append ( path ) ; } if ( expireTime > - 1 ) { header . append ( "; " ) . append ( "Expires=" ) . append ( RFC_DATEFORMAT . format ( new Date ( expireTime ) ) ) ; } if ( secure ) { header . append ( "; " ) . append ( "Secure" ) ; } return header . toString ( ) ; } | Transforms this cookie into a Set - Cookie header field |
14,188 | public static String generateRandomString ( int nbytes ) { byte [ ] salt = new byte [ nbytes ] ; Random r = new SecureRandom ( ) ; r . nextBytes ( salt ) ; return bytesToHex ( salt ) ; } | Generate a random string with a certain entropy . |
14,189 | public static boolean fixedTimeEqual ( String lhs , String rhs ) { boolean equal = ( lhs . length ( ) == rhs . length ( ) ? true : false ) ; if ( ! equal ) { rhs = lhs ; } int len = lhs . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( lhs . charAt ( i ) == rhs . charAt ( i ) ) { equal = equal && true ; } else { equal = equal && false ; } } return equal ; } | Fixed time comparison of two strings . |
14,190 | private void initialize ( InputStream input ) { BufferedReader reader = null ; try { reader = new BufferedReader ( new InputStreamReader ( input ) ) ; String line ; Matcher m ; while ( ( line = reader . readLine ( ) ) != null ) { m = TYPE_PATTERN . matcher ( line ) ; if ( m . find ( ) ) { String type = m . group ( 1 ) ; String [ ] extensions = m . group ( 2 ) . split ( " " ) ; for ( String extension : extensions ) { contentTypes . put ( extension , type ) ; } } } } catch ( IOException e ) { } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } | Read and parse the type file . |
14,191 | private static final String getExtension ( String fileName ) { return fileName . indexOf ( '.' ) == - 1 ? null : fileName . substring ( fileName . lastIndexOf ( '.' ) + 1 ) ; } | Get the extension of a file . |
14,192 | public boolean containsInterval ( Interval < T > i ) { for ( Interval < T > item : intervals ) { if ( item . contains ( i ) ) { return true ; } } return false ; } | Return true if the argument interval is a subset of an interval of the partition |
14,193 | public void addHeader ( String key , Object value ) { List < Object > values = headers . get ( key ) ; if ( values == null ) { headers . put ( key , values = new ArrayList < Object > ( ) ) ; } values . add ( value ) ; } | Add a header to the response |
14,194 | public void setResponse ( String response ) { this . response = response ; try { this . responseLength = response . getBytes ( "UTF-8" ) . length ; } catch ( UnsupportedEncodingException e ) { this . responseLength = response . length ( ) ; } } | Set the response string |
14,195 | public void setResponse ( InputStream response ) { this . response = response ; try { this . responseLength = response . available ( ) ; } catch ( IOException e ) { } } | Set the response Input Stream |
14,196 | public void start ( ) { if ( socket == null ) { throw new RuntimeException ( "Cannot bind a server that has not been initialized!" ) ; } running = true ; Thread t = new Thread ( this ) ; t . setName ( "HttpServer" ) ; t . start ( ) ; } | Start the server in a new thread |
14,197 | public void run ( ) { while ( running ) { try { service . execute ( new HttpSession ( this , socket . accept ( ) ) ) ; } catch ( IOException e ) { } } } | Run and process requests . |
14,198 | public void dispatchRequest ( HttpRequest httpRequest ) throws IOException { for ( HttpRequestHandler handler : handlers ) { HttpResponse resp = handler . handleRequest ( httpRequest ) ; if ( resp != null ) { httpRequest . getSession ( ) . sendResponse ( resp ) ; return ; } } if ( ! hasCapability ( HttpCapability . THREADEDRESPONSE ) ) { httpRequest . getSession ( ) . sendResponse ( new HttpResponse ( HttpStatus . NOT_FOUND , HttpStatus . NOT_FOUND . toString ( ) ) ) ; } } | Dispatch a request to all handlers |
14,199 | public WwwAuthenticateHeader createWwwAuthenticateHeader ( ) throws HawkException { WwwAuthenticateBuilder headerBuilder = WwwAuthenticateHeader . wwwAuthenticate ( ) ; if ( hasTs ( ) ) { if ( ! hasTsm ( ) ) { String hmac = this . generateHmac ( ) ; headerBuilder . ts ( getTs ( ) ) . tsm ( hmac ) ; } else { headerBuilder . ts ( getTs ( ) ) . tsm ( getTsm ( ) ) ; } if ( hasError ( ) ) { throw new IllegalStateException ( "Context cannot contain error and ts at the same time." ) ; } } if ( hasError ( ) ) { headerBuilder . error ( this . error ) ; } return headerBuilder . build ( ) ; } | Create a WWW - Authenticate header from this HawkWwwAuthenticateContext . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.