idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
137,800
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...
Remove field from session after maxTime is elapsed .
137,801
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...
Returns an immutable collection of all the instructions in this InstructionList .
137,802
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 .
137,803
public Resolution intercept ( ExecutionContext context ) throws Exception { HttpServletRequest request = context . getActionBeanContext ( ) . getRequest ( ) ; if ( resourceBundleFactory != null ) { ResourceBundle bundle = resourceBundleFactory . getDefaultBundle ( request . getLocale ( ) ) ; setMessageResourceBundle ( ...
Invoked when intercepting the flow of execution .
137,804
public Resolution intercept ( ExecutionContext executionContext ) throws Exception { Resolution resolution ; if ( securityManager != null ) { executionContext . getActionBeanContext ( ) . getRequest ( ) . setAttribute ( SecurityInterceptor . SECURITY_MANAGER , securityManager ) ; switch ( executionContext . getLifecycl...
Intercept execution .
137,805
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." ) ; resol...
Intercept execution for event handling . Checks if the security manager allows access before allowing the event .
137,806
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 ++ ) ) == '[' ) { di...
Acquire a TypeDesc from a type descriptor .
137,807
public void valueUnbound ( HttpSessionBindingEvent event ) { for ( SessionFieldMapper fieldMapper : this . values ( ) ) { if ( fieldMapper . runnable != null ) fieldMapper . runnable . cancel ( ) ; } }
Cancel all threads from field mappers .
137,808
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 .
137,809
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 ...
Scans the contents of this map removing all entries that have a cleared soft value .
137,810
protected void setMessageResourceBundle ( HttpServletRequest request , ResourceBundle bundle ) { request . setAttribute ( REQ_ATTR_MESSAGE_RESOURCE_BUNDLE , bundle ) ; }
Puts the resource bundle as a request - scope attribute .
137,811
public List < ProblemInput > getProblemInputs ( ) { return ( inputs == null ? Collections . emptyList ( ) : Arrays . asList ( inputs ) ) ; }
Getter for the problem inputs .
137,812
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 .
137,813
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 .
137,814
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 CAST...
Returns true if the given opcode can throw an exception at runtime .
137,815
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...
Returns a Map of all the available properties on a given class including write - only and indexed properties .
137,816
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 ( na...
Returns null if prefix pattern doesn t match
137,817
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...
Saves all fields in session .
137,818
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 ( ) ) ...
Restore all fields from value stored in session except if they .
137,819
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 . ...
Returns all property that stripes will replace for request .
137,820
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 . getNam...
Returns session key under which field should be saved or read .
137,821
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 ( )...
Returns all fields with Session annotation for a class .
137,822
public static Object getAttribute ( HttpSession session , String key ) { return session . getAttribute ( key ) ; }
Returns an object in session .
137,823
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...
Saves an object in session for latter use .
137,824
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 resour...
Sets the message resource bundle in the request using the JSTL s mechanism .
137,825
protected void setOtherResourceBundles ( HttpServletRequest request ) { Locale locale = request . getLocale ( ) ; if ( errorBundleName != null ) { ResourceBundle errorBundle = getLocalizationBundleFactory ( ) . getErrorMessageBundle ( locale ) ; Config . set ( request , errorBundleName , new LocalizationContext ( error...
Sets the Stripes error and field resource bundles in the request if their names have been configured .
137,826
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...
Evaluate the given EL expression using the current action bean to resolve variables .
137,827
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 ( ( ...
Acquire a MethodDesc from a type descriptor .
137,828
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 ) { fina...
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 ins...
137,829
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...
Returns a Constructor that accepts an AtomicReference to the wrapped object .
137,830
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
137,831
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 .
137,832
public void invokeVirtual ( String methodName , TypeDesc ret , TypeDesc [ ] params ) { invokeVirtual ( mClassFile . getClassName ( ) , methodName , ret , params ) ; }
invocation style instructions
137,833
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 ( ...
Returns wait context based on context id found in request .
137,834
private Resolution createContextAndRedirect ( ExecutionContext executionContext , WaitPage annotation ) throws IOException { Context context = this . createContext ( executionContext ) ; context . actionBean = executionContext . getActionBean ( ) ; context . eventHandler = executionContext . getHandler ( ) ; context . ...
Create a wait context to execute event in background .
137,835
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 ( conte...
Return wait page resolution or event s resolution depending on completion status .
137,836
protected void copyErrors ( ActionBeanContext source , ActionBeanContext destination ) { destination . getValidationErrors ( ) . putAll ( source . getValidationErrors ( ) ) ; }
Copy errors from a context to another context .
137,837
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 . complete...
Remove all contexts that are expired .
137,838
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 ) )...
Read context timeout if any .
137,839
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 .
137,840
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 .
137,841
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...
Specify what target virtual machine version classfile should generate for . Calling this method changes the major and minor version of the classfile format .
137,842
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 = min...
Sets the version to use when writing the generated classfile overriding the target .
137,843
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 ; } Stri...
Disassembles a class file sending the results to standard out .
137,844
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 , ha...
Decide if the annotated element allows access to the current user .
137,845
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...
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 .
137,846
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 { whil...
Invoke event in a background request .
137,847
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 = ne...
Finishes the class definition .
137,848
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 .
137,849
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 mat...
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 .
137,850
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 ( ) ) { Bean...
Returns two arrays of BeanProperties . Array 0 contains read BeanProperties array 1 contains the write BeanProperties .
137,851
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 ByteArrayOu...
Open a stream to define the new class into .
137,852
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 .
137,853
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 Fil...
Returns the newly defined class .
137,854
int available ( Context context ) { return context . buffer != null ? context . pos - context . readPos : 0 ; }
Returns the amount of buffered data available for reading .
137,855
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 )...
Parse POST data or GET data from the request URI
137,856
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 ) {...
Fixes capitalization on headers
137,857
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 External...
Combine two external nodes following the algorithm in this . algo
137,858
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 . i...
Return OE in the list that are fulfilled the indicated decision .
137,859
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 .
137,860
@ 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 < ...
Set indicated external - xacml3 node to be the leaves of the MIDD
137,861
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 .
137,862
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
137,863
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' ) { bld...
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 .
137,864
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 ...
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 .
137,865
public String getValue ( String key ) { KeyValue kv = getKV ( key ) ; return kv == null ? null : kv . getValue ( ) ; }
Get the value for the key
137,866
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!
137,867
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
137,868
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
137,869
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 .
137,870
@ 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" ) ; } edg...
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 .
137,871
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 .
137,872
@ 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
137,873
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
137,874
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 ...
Create a MIDD from conjunctions of intervals
137,875
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 .
137,876
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 .
137,877
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 )...
Transforms this cookie into a Set - Cookie header field
137,878
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 .
137,879
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 {...
Fixed time comparison of two strings .
137,880
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 ) ...
Read and parse the type file .
137,881
private static final String getExtension ( String fileName ) { return fileName . indexOf ( '.' ) == - 1 ? null : fileName . substring ( fileName . lastIndexOf ( '.' ) + 1 ) ; }
Get the extension of a file .
137,882
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
137,883
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
137,884
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
137,885
public void setResponse ( InputStream response ) { this . response = response ; try { this . responseLength = response . available ( ) ; } catch ( IOException e ) { } }
Set the response Input Stream
137,886
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
137,887
public void run ( ) { while ( running ) { try { service . execute ( new HttpSession ( this , socket . accept ( ) ) ) ; } catch ( IOException e ) { } } }
Run and process requests .
137,888
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 . THR...
Dispatch a request to all handlers
137,889
public WwwAuthenticateHeader createWwwAuthenticateHeader ( ) throws HawkException { WwwAuthenticateBuilder headerBuilder = WwwAuthenticateHeader . wwwAuthenticate ( ) ; if ( hasTs ( ) ) { if ( ! hasTsm ( ) ) { String hmac = this . generateHmac ( ) ; headerBuilder . ts ( getTs ( ) ) . tsm ( hmac ) ; } else { headerBuild...
Create a WWW - Authenticate header from this HawkWwwAuthenticateContext .
137,890
public boolean isValidTimestampMac ( String hmac ) throws HawkException { String this_hmac = this . generateHmac ( ) ; return Util . fixedTimeEqual ( this_hmac , hmac ) ; }
Check whether a given HMAC value matches the HMAC for the timestamp in this HawkWwwAuthenticateContext .
137,891
private String getBaseString ( ) { if ( ! hasTs ( ) ) { throw new IllegalStateException ( "This HawkWwwAuthenticateContext has no timestamp" ) ; } return new StringBuilder ( HAWK_TS_PREFIX ) . append ( SLF ) . append ( getTs ( ) ) . append ( SLF ) . toString ( ) ; }
Generate base string for timestamp HMAC generation .
137,892
private String generateHmac ( ) throws HawkException { String baseString = getBaseString ( ) ; Mac mac ; try { mac = Mac . getInstance ( getAlgorithm ( ) . getMacName ( ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new HawkException ( "Unknown algorithm " + getAlgorithm ( ) . getMacName ( ) , e ) ; } SecretKeySp...
Generate an HMAC from the context ts parameter .
137,893
public static HawkWwwAuthenticateContextBuilder_A tsAndTsm ( long l , String tsm ) { return new HawkWwwAuthenticateContextBuilder ( ) . ts ( l ) . tsm ( tsm ) ; }
Create a new HawkWwwAuthenticateContextBuilder_A initialized with timestamp and timestamp hmac .
137,894
public int addAttribute ( String attrId ) { if ( attributeMapper . containsKey ( attrId ) ) { return attributeMapper . get ( attrId ) ; } attributeMapper . put ( attrId , varIdCounter ) ; varIdCounter ++ ; return attributeMapper . get ( attrId ) ; }
Add a new attribute - id to the map return the variable id . If the attribute existed throws exception
137,895
public String getAttributeId ( int variableId ) throws MIDDParsingException { if ( ! attributeMapper . containsValue ( variableId ) ) { throw new MIDDParsingException ( "Variable identifier '" + variableId + "' not found" ) ; } for ( String attrId : attributeMapper . keySet ( ) ) { if ( attributeMapper . get ( attrId )...
Return the attribute identifier from the variable - id
137,896
public void write ( MessageBodyWriterContext context ) throws IOException , WebApplicationException { Object encoding = context . getHeaders ( ) . getFirst ( HttpHeaders . CONTENT_ENCODING ) ; if ( encoding != null && encoding . toString ( ) . equalsIgnoreCase ( "lzf" ) ) { OutputStream old = context . getOutputStream ...
Grab the outgoing message if encoding is set to LZF then wrap the OutputStream in an LZF OutputStream before sending it on its merry way compressing all the time .
137,897
public AuthorizationHeader createAuthorizationHeader ( ) throws HawkException { String hmac = this . generateHmac ( ) ; AuthorizationBuilder headerBuilder = AuthorizationHeader . authorization ( ) . ts ( ts ) . nonce ( nonce ) . id ( getId ( ) ) . mac ( hmac ) ; if ( hasExt ( ) ) { headerBuilder . ext ( getExt ( ) ) ; ...
Create an Authorization header from this HawkContext .
137,898
public boolean verifyServerAuthorizationMatches ( AuthorizationHeader header ) { if ( ! Util . fixedTimeEqual ( header . getId ( ) , this . getId ( ) ) ) { return false ; } if ( header . getTs ( ) != this . getTs ( ) ) { return false ; } if ( ! Util . fixedTimeEqual ( header . getNonce ( ) , this . getNonce ( ) ) ) { r...
Verify that a given header matches a HawkContext .
137,899
public boolean isValidMac ( String hmac ) throws HawkException { String this_hmac = this . generateHmac ( ) ; return Util . fixedTimeEqual ( this_hmac , hmac ) ; }
Check whether a given HMAC value matches the HMAC for this HawkContext .