idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
1,400
|
public static boolean isJavaIdentifier ( String str ) { if ( str . length ( ) == 0 || ! Character . isJavaIdentifierStart ( str . charAt ( 0 ) ) ) { return false ; } for ( int i = 1 ; i < str . length ( ) ; i ++ ) { if ( ! Character . isJavaIdentifierPart ( str . charAt ( i ) ) ) { return false ; } } return true ; }
|
Returns trus if str represents a valid Java identifier .
|
1,401
|
public static boolean isNull ( Object obj ) { if ( obj instanceof JSONObject ) { return ( ( JSONObject ) obj ) . isNullObject ( ) ; } return JSONNull . getInstance ( ) . equals ( obj ) ; }
|
Tests if the obj is a javaScript null .
|
1,402
|
public static boolean isObject ( Object obj ) { return ! isNumber ( obj ) && ! isString ( obj ) && ! isBoolean ( obj ) && ! isArray ( obj ) && ! isFunction ( obj ) || isNull ( obj ) ; }
|
Tests if obj is not a boolean number string or array .
|
1,403
|
public static boolean isString ( Class clazz ) { return clazz != null && ( String . class . isAssignableFrom ( clazz ) || ( Character . TYPE . isAssignableFrom ( clazz ) || Character . class . isAssignableFrom ( clazz ) ) ) ; }
|
Tests if Class represents a String or a char
|
1,404
|
public static boolean isString ( Object obj ) { if ( ( obj instanceof String ) || ( obj instanceof Character ) || ( obj != null && ( obj . getClass ( ) == Character . TYPE || String . class . isAssignableFrom ( obj . getClass ( ) ) ) ) ) { return true ; } return false ; }
|
Tests if obj is a String or a char
|
1,405
|
public static DynaBean newDynaBean ( JSONObject jsonObject , JsonConfig jsonConfig ) { Map props = getProperties ( jsonObject ) ; for ( Iterator entries = props . entrySet ( ) . iterator ( ) ; entries . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) entries . next ( ) ; String key = ( String ) entry . getKey ( ) ; if ( ! JSONUtils . isJavaIdentifier ( key ) ) { String parsedKey = JSONUtils . convertToJavaIdentifier ( key , jsonConfig ) ; if ( parsedKey . compareTo ( key ) != 0 ) { props . put ( parsedKey , props . remove ( key ) ) ; } } } MorphDynaClass dynaClass = new MorphDynaClass ( props ) ; MorphDynaBean dynaBean = null ; try { dynaBean = ( MorphDynaBean ) dynaClass . newInstance ( ) ; dynaBean . setDynaBeanClass ( dynaClass ) ; } catch ( Exception e ) { throw new JSONException ( e ) ; } return dynaBean ; }
|
Creates a new MorphDynaBean from a JSONObject . The MorphDynaBean will have all the properties of the original JSONObject with the most accurate type . Values of properties are not copied .
|
1,406
|
public static String quoteCanonical ( String s ) { if ( s == null || s . length ( ) == 0 ) { return "\"\"" ; } int len = s . length ( ) ; StringBuilder sb = new StringBuilder ( len + 4 ) ; sb . append ( '"' ) ; for ( int i = 0 ; i < len ; i += 1 ) { char c = s . charAt ( i ) ; switch ( c ) { case '\\' : case '"' : sb . append ( '\\' ) ; sb . append ( c ) ; break ; default : if ( c < ' ' ) { String t = "000" + Integer . toHexString ( c ) ; sb . append ( "\\u" ) . append ( t . substring ( t . length ( ) - 4 ) ) ; } else { sb . append ( c ) ; } } } sb . append ( '"' ) ; return sb . toString ( ) ; }
|
Minimal escape form .
|
1,407
|
public static String stripQuotes ( String input ) { if ( input . length ( ) < 2 ) { return input ; } else if ( input . startsWith ( SINGLE_QUOTE ) && input . endsWith ( SINGLE_QUOTE ) ) { return input . substring ( 1 , input . length ( ) - 1 ) ; } else if ( input . startsWith ( DOUBLE_QUOTE ) && input . endsWith ( DOUBLE_QUOTE ) ) { return input . substring ( 1 , input . length ( ) - 1 ) ; } else { return input ; } }
|
Strips any single - quotes or double - quotes from both sides of the string .
|
1,408
|
public static boolean hasQuotes ( String input ) { if ( input == null || input . length ( ) < 2 ) { return false ; } return input . startsWith ( SINGLE_QUOTE ) && input . endsWith ( SINGLE_QUOTE ) || input . startsWith ( DOUBLE_QUOTE ) && input . endsWith ( DOUBLE_QUOTE ) ; }
|
Returns true if the input has single - quotes or double - quotes at both sides .
|
1,409
|
private static boolean isDouble ( Number n ) { if ( n instanceof Double ) { return true ; } try { double d = Double . parseDouble ( String . valueOf ( n ) ) ; return ! Double . isInfinite ( d ) ; } catch ( NumberFormatException e ) { return false ; } }
|
Finds out if n represents a Double .
|
1,410
|
private static boolean isFloat ( Number n ) { if ( n instanceof Float ) { return true ; } try { float f = Float . parseFloat ( String . valueOf ( n ) ) ; return ! Float . isInfinite ( f ) ; } catch ( NumberFormatException e ) { return false ; } }
|
Finds out if n represents a Float .
|
1,411
|
private static boolean isInteger ( Number n ) { if ( n instanceof Integer ) { return true ; } try { Integer . parseInt ( String . valueOf ( n ) ) ; return true ; } catch ( NumberFormatException e ) { return false ; } }
|
Finds out if n represents an Integer .
|
1,412
|
private static boolean isLong ( Number n ) { if ( n instanceof Long ) { return true ; } try { Long . parseLong ( String . valueOf ( n ) ) ; return true ; } catch ( NumberFormatException e ) { return false ; } }
|
Finds out if n represents a Long .
|
1,413
|
public static JSONFunction parse ( String str ) { if ( ! JSONUtils . isFunction ( str ) ) { throw new JSONException ( "String is not a function. " + str ) ; } else { String params = JSONUtils . getFunctionParams ( str ) ; String text = JSONUtils . getFunctionBody ( str ) ; return new JSONFunction ( ( params != null ) ? StringUtils . split ( params , "," ) : null , text != null ? text : "" ) ; } }
|
Constructs a JSONFunction from a text representation
|
1,414
|
public static int [ ] getDimensions ( JSONArray jsonArray ) { if ( jsonArray == null || jsonArray . isEmpty ( ) ) { return new int [ ] { 0 } ; } List dims = new ArrayList ( ) ; processArrayDimensions ( jsonArray , dims , 0 ) ; int [ ] dimensions = new int [ dims . size ( ) ] ; int j = 0 ; for ( Iterator i = dims . iterator ( ) ; i . hasNext ( ) ; ) { dimensions [ j ++ ] = ( ( Integer ) i . next ( ) ) . intValue ( ) ; } return dimensions ; }
|
Returns the number of dimensions suited for a java array .
|
1,415
|
public static Object toArray ( JSONArray jsonArray , Class objectClass ) { JsonConfig jsonConfig = new JsonConfig ( ) ; jsonConfig . setRootClass ( objectClass ) ; return toArray ( jsonArray , jsonConfig ) ; }
|
Creates a java array from a JSONArray .
|
1,416
|
public static Collection toCollection ( JSONArray jsonArray , Class objectClass ) { JsonConfig jsonConfig = new JsonConfig ( ) ; jsonConfig . setRootClass ( objectClass ) ; return toCollection ( jsonArray , jsonConfig ) ; }
|
Creates a Collection from a JSONArray .
|
1,417
|
public static List toList ( JSONArray jsonArray , Class objectClass ) { JsonConfig jsonConfig = new JsonConfig ( ) ; jsonConfig . setRootClass ( objectClass ) ; return toList ( jsonArray , jsonConfig ) ; }
|
Creates a List from a JSONArray .
|
1,418
|
public JSONArray element ( Collection value , JsonConfig jsonConfig ) { if ( value instanceof JSONArray ) { elements . add ( value ) ; return this ; } else { return element ( _fromCollection ( value , jsonConfig ) ) ; } }
|
Append a value in the JSONArray where the value will be a JSONArray which is produced from a Collection .
|
1,419
|
private static JSONArray _fromArray ( Enum e , JsonConfig jsonConfig ) { if ( ! addInstance ( e ) ) { try { return jsonConfig . getCycleDetectionStrategy ( ) . handleRepeatedReferenceAsArray ( e ) ; } catch ( JSONException jsone ) { removeInstance ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } catch ( RuntimeException re ) { removeInstance ( e ) ; JSONException jsone = new JSONException ( re ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } } fireArrayStartEvent ( jsonConfig ) ; JSONArray jsonArray = new JSONArray ( ) ; if ( e != null ) { jsonArray . addValue ( e , jsonConfig ) ; fireElementAddedEvent ( 0 , jsonArray . get ( 0 ) , jsonConfig ) ; } else { JSONException jsone = new JSONException ( "enum value is null" ) ; removeInstance ( e ) ; fireErrorEvent ( jsone , jsonConfig ) ; throw jsone ; } removeInstance ( e ) ; fireArrayEndEvent ( jsonConfig ) ; return jsonArray ; }
|
Construct a JSONArray from an Enum value .
|
1,420
|
protected static void fireArrayEndEvent ( JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onArrayEnd ( ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } }
|
Fires an end of array event .
|
1,421
|
protected static void fireArrayStartEvent ( JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onArrayStart ( ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } }
|
Fires a start of array event .
|
1,422
|
protected static void fireElementAddedEvent ( int index , Object element , JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onElementAdded ( index , element ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } }
|
Fires an element added event .
|
1,423
|
protected static void fireErrorEvent ( JSONException jsone , JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onError ( jsone ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } }
|
Fires an error event .
|
1,424
|
protected static void fireObjectEndEvent ( JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onObjectEnd ( ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } }
|
Fires an end of object event .
|
1,425
|
protected static void fireObjectStartEvent ( JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onObjectStart ( ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } }
|
Fires a start of object event .
|
1,426
|
protected static void firePropertySetEvent ( String key , Object value , boolean accumulated , JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onPropertySet ( key , value , accumulated ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } }
|
Fires a property set event .
|
1,427
|
protected static void fireWarnEvent ( String warning , JsonConfig jsonConfig ) { if ( jsonConfig . isEventTriggeringEnabled ( ) ) { for ( Iterator listeners = jsonConfig . getJsonEventListeners ( ) . iterator ( ) ; listeners . hasNext ( ) ; ) { JsonEventListener listener = ( JsonEventListener ) listeners . next ( ) ; try { listener . onWarning ( warning ) ; } catch ( RuntimeException e ) { log . warn ( e ) ; } } } }
|
Fires a warning event .
|
1,428
|
protected static void removeInstance ( Object instance ) { Set set = getCycleSet ( ) ; set . remove ( instance ) ; if ( set . size ( ) == 0 ) { cycleSet . remove ( ) ; } }
|
Removes a reference for cycle detection check .
|
1,429
|
public static boolean isValidJsonValue ( Object value ) { if ( JSONNull . getInstance ( ) . equals ( value ) || value instanceof JSON || value instanceof Boolean || value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Double || value instanceof BigInteger || value instanceof BigDecimal || value instanceof JSONFunction || value instanceof JSONString || value instanceof String ) { return true ; } return false ; }
|
Verifies if value is a valid JSON value .
|
1,430
|
public void reset ( ) { excludes = EMPTY_EXCLUDES ; ignoreDefaultExcludes = false ; ignoreTransientFields = false ; ignorePublicFields = true ; javascriptCompliant = false ; javaIdentifierTransformer = DEFAULT_JAVA_IDENTIFIER_TRANSFORMER ; cycleDetectionStrategy = DEFAULT_CYCLE_DETECTION_STRATEGY ; skipJavaIdentifierTransformationInMapKeys = false ; triggerEvents = false ; handleJettisonEmptyElement = false ; handleJettisonSingleElementArray = false ; arrayMode = MODE_LIST ; rootClass = null ; classMap = null ; keyMap . clear ( ) ; typeMap . clear ( ) ; beanKeyMap . clear ( ) ; beanTypeMap . clear ( ) ; jsonPropertyFilter = null ; javaPropertyFilter = null ; jsonBeanProcessorMatcher = DEFAULT_JSON_BEAN_PROCESSOR_MATCHER ; newBeanInstanceStrategy = DEFAULT_NEW_BEAN_INSTANCE_STRATEGY ; defaultValueProcessorMatcher = DEFAULT_DEFAULT_VALUE_PROCESSOR_MATCHER ; defaultValueMap . clear ( ) ; propertySetStrategy = null ; collectionType = DEFAULT_COLLECTION_TYPE ; enclosedType = null ; jsonValueProcessorMatcher = DEFAULT_JSON_VALUE_PROCESSOR_MATCHER ; javaPropertyNameProcessorMap . clear ( ) ; javaPropertyNameProcessorMatcher = DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER ; jsonPropertyNameProcessorMap . clear ( ) ; jsonPropertyNameProcessorMatcher = DEFAULT_PROPERTY_NAME_PROCESSOR_MATCHER ; beanProcessorMap . clear ( ) ; propertyExclusionClassMatcher = DEFAULT_PROPERTY_EXCLUSION_CLASS_MATCHER ; exclusionMap . clear ( ) ; ignoreFieldAnnotations . clear ( ) ; allowNonStringKeys = false ; }
|
Resets all values to its default state .
|
1,431
|
public HttpResponse sendRequest ( PiwikRequest request ) throws IOException { HttpClient client = getHttpClient ( ) ; uriBuilder . replaceQuery ( request . getUrlEncodedQueryString ( ) ) ; HttpGet get = new HttpGet ( uriBuilder . build ( ) ) ; try { return client . execute ( get ) ; } finally { get . releaseConnection ( ) ; } }
|
Send a request .
|
1,432
|
public HttpResponse sendBulkRequest ( Iterable < PiwikRequest > requests , String authToken ) throws IOException { if ( authToken != null && authToken . length ( ) != PiwikRequest . AUTH_TOKEN_LENGTH ) { throw new IllegalArgumentException ( authToken + " is not " + PiwikRequest . AUTH_TOKEN_LENGTH + " characters long." ) ; } JsonObjectBuilder ob = Json . createObjectBuilder ( ) ; JsonArrayBuilder ab = Json . createArrayBuilder ( ) ; for ( PiwikRequest request : requests ) { ab . add ( "?" + request . getQueryString ( ) ) ; } ob . add ( REQUESTS , ab ) ; if ( authToken != null ) { ob . add ( AUTH_TOKEN , authToken ) ; } HttpClient client = getHttpClient ( ) ; HttpPost post = new HttpPost ( uriBuilder . build ( ) ) ; post . setEntity ( new StringEntity ( ob . build ( ) . toString ( ) , ContentType . APPLICATION_JSON ) ) ; try { return client . execute ( post ) ; } finally { post . releaseConnection ( ) ; } }
|
Send multiple requests in a single HTTP call . More efficient than sending several individual requests . Specify the AuthToken if parameters that require an auth token is used .
|
1,433
|
protected HttpClient getHttpClient ( ) { HttpClientBuilder builder = HttpClientBuilder . create ( ) ; if ( proxyHost != null && proxyPort != 0 ) { HttpHost proxy = new HttpHost ( proxyHost , proxyPort ) ; DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner ( proxy ) ; builder . setRoutePlanner ( routePlanner ) ; } RequestConfig . Builder config = RequestConfig . custom ( ) . setConnectTimeout ( timeout ) . setConnectionRequestTimeout ( timeout ) . setSocketTimeout ( timeout ) ; builder . setDefaultRequestConfig ( config . build ( ) ) ; return builder . build ( ) ; }
|
Get a HTTP client . With proxy if a proxy is provided in the constructor .
|
1,434
|
JsonArray toJsonArray ( ) { JsonArrayBuilder ab = Json . createArrayBuilder ( ) ; ab . add ( sku ) ; ab . add ( name ) ; ab . add ( category ) ; ab . add ( price ) ; ab . add ( quantity ) ; return ab . build ( ) ; }
|
Returns the value of this EcommerceItem as a JsonArray .
|
1,435
|
public List getCustomTrackingParameter ( String key ) { if ( key == null ) { throw new NullPointerException ( "Key cannot be null." ) ; } List l = customTrackingParameters . get ( key ) ; if ( l == null ) { return new ArrayList ( 0 ) ; } return new ArrayList ( l ) ; }
|
Gets the list of objects currently stored at the specified custom tracking parameter . An empty list will be returned if there are no objects set at that key .
|
1,436
|
public void addCustomTrackingParameter ( String key , Object value ) { if ( key == null ) { throw new NullPointerException ( "Key cannot be null." ) ; } if ( value == null ) { throw new NullPointerException ( "Cannot add a null custom tracking parameter." ) ; } else { List l = customTrackingParameters . get ( key ) ; if ( l == null ) { l = new ArrayList ( ) ; customTrackingParameters . put ( key , l ) ; } l . add ( value ) ; } }
|
Add a custom tracking parameter to the specified key . This allows users to have multiple parameters with the same name and different values commonly used during situations where list parameters are needed
|
1,437
|
public void setGoalRevenue ( Double goalRevenue ) { if ( goalRevenue != null && getGoalId ( ) == null ) { throw new IllegalStateException ( "GoalId must be set before GoalRevenue can be set." ) ; } setParameter ( GOAL_REVENUE , goalRevenue ) ; }
|
Set a monetary value that was generated as revenue by this goal conversion . Only used if idgoal is specified in the request .
|
1,438
|
public void setPageCustomVariable ( String key , String value ) { if ( value == null ) { removeCustomVariable ( PAGE_CUSTOM_VARIABLE , key ) ; } else { setCustomVariable ( PAGE_CUSTOM_VARIABLE , new CustomVariable ( key , value ) , null ) ; } }
|
Set a page custom variable with the specified key and value at the first available index . All page custom variables with this key will be overwritten or deleted
|
1,439
|
public void setSearchCategory ( String searchCategory ) { if ( searchCategory != null && getSearchQuery ( ) == null ) { throw new IllegalStateException ( "SearchQuery must be set before SearchCategory can be set." ) ; } setParameter ( SEARCH_CATEGORY , searchCategory ) ; }
|
Specify a search category with this parameter . SearchQuery must first be set .
|
1,440
|
public void setUserCustomVariable ( String key , String value ) { if ( value == null ) { removeCustomVariable ( VISIT_CUSTOM_VARIABLE , key ) ; } else { setCustomVariable ( VISIT_CUSTOM_VARIABLE , new CustomVariable ( key , value ) , null ) ; } }
|
Set a visit custom variable with the specified key and value at the first available index . All visit custom variables with this key will be overwritten or deleted
|
1,441
|
public String getQueryString ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( Entry < String , Object > parameter : parameters . entrySet ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "&" ) ; } sb . append ( parameter . getKey ( ) ) ; sb . append ( "=" ) ; sb . append ( parameter . getValue ( ) . toString ( ) ) ; } for ( Entry < String , List > customTrackingParameter : customTrackingParameters . entrySet ( ) ) { for ( Object o : customTrackingParameter . getValue ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "&" ) ; } sb . append ( customTrackingParameter . getKey ( ) ) ; sb . append ( "=" ) ; sb . append ( o . toString ( ) ) ; } } return sb . toString ( ) ; }
|
Get the query string represented by this object .
|
1,442
|
public String getUrlEncodedQueryString ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( Entry < String , Object > parameter : parameters . entrySet ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "&" ) ; } try { StringBuilder sb2 = new StringBuilder ( ) ; sb2 . append ( parameter . getKey ( ) ) ; sb2 . append ( "=" ) ; sb2 . append ( URLEncoder . encode ( parameter . getValue ( ) . toString ( ) , "UTF-8" ) ) ; sb . append ( sb2 ) ; } catch ( UnsupportedEncodingException e ) { System . err . println ( e . getMessage ( ) ) ; } } for ( Entry < String , List > customTrackingParameter : customTrackingParameters . entrySet ( ) ) { for ( Object o : customTrackingParameter . getValue ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "&" ) ; } try { StringBuilder sb2 = new StringBuilder ( ) ; sb2 . append ( URLEncoder . encode ( customTrackingParameter . getKey ( ) , "UTF-8" ) ) ; sb2 . append ( "=" ) ; sb2 . append ( URLEncoder . encode ( o . toString ( ) , "UTF-8" ) ) ; sb . append ( sb2 ) ; } catch ( UnsupportedEncodingException e ) { System . err . println ( e . getMessage ( ) ) ; } } } return sb . toString ( ) ; }
|
Get the url encoded query string represented by this object .
|
1,443
|
public static String getRandomHexString ( int length ) { byte [ ] bytes = new byte [ length / 2 ] ; new Random ( ) . nextBytes ( bytes ) ; return DatatypeConverter . printHexBinary ( bytes ) ; }
|
Get a random hexadecimal string of a specified length .
|
1,444
|
private void setParameter ( String key , Object value ) { if ( value == null ) { parameters . remove ( key ) ; } else { parameters . put ( key , value ) ; } }
|
Set a stored parameter .
|
1,445
|
private void setNonEmptyStringParameter ( String key , String value ) { if ( value == null ) { parameters . remove ( key ) ; } else if ( value . length ( ) == 0 ) { throw new IllegalArgumentException ( "Value cannot be empty." ) ; } else { parameters . put ( key , value ) ; } }
|
Set a stored parameter and verify it is a non - empty string .
|
1,446
|
private Boolean getBooleanParameter ( String key ) { Integer i = ( Integer ) parameters . get ( key ) ; if ( i == null ) { return null ; } return i . equals ( 1 ) ; }
|
Get a stored parameter that is a boolean .
|
1,447
|
private void setBooleanParameter ( String key , Boolean value ) { if ( value == null ) { parameters . remove ( key ) ; } else if ( value ) { parameters . put ( key , 1 ) ; } else { parameters . put ( key , 0 ) ; } }
|
Set a stored parameter that is a boolean . This value will be stored as 1 for true and 0 for false .
|
1,448
|
private CustomVariable getCustomVariable ( String parameter , int index ) { CustomVariableList cvl = ( CustomVariableList ) parameters . get ( parameter ) ; if ( cvl == null ) { return null ; } return cvl . get ( index ) ; }
|
Get a value that is stored in a json object at the specified parameter .
|
1,449
|
private void setCustomVariable ( String parameter , CustomVariable customVariable , Integer index ) { CustomVariableList cvl = ( CustomVariableList ) parameters . get ( parameter ) ; if ( cvl == null ) { cvl = new CustomVariableList ( ) ; parameters . put ( parameter , cvl ) ; } if ( customVariable == null ) { cvl . remove ( index ) ; if ( cvl . isEmpty ( ) ) { parameters . remove ( parameter ) ; } } else if ( index == null ) { cvl . add ( customVariable ) ; } else { cvl . add ( customVariable , index ) ; } }
|
Store a value in a json object at the specified parameter .
|
1,450
|
private JsonValue getFromJsonArray ( String key , int index ) { PiwikJsonArray a = ( PiwikJsonArray ) parameters . get ( key ) ; if ( a == null ) { return null ; } return a . get ( index ) ; }
|
Get the value at the specified index from the json array at the specified parameter .
|
1,451
|
private void addToJsonArray ( String key , JsonValue value ) { if ( value == null ) { throw new NullPointerException ( "Value cannot be null." ) ; } PiwikJsonArray a = ( PiwikJsonArray ) parameters . get ( key ) ; if ( a == null ) { a = new PiwikJsonArray ( ) ; parameters . put ( key , a ) ; } a . add ( value ) ; }
|
Add a value to the json array at the specified parameter
|
1,452
|
private Memory readChunkOffsets ( DataInput input ) { try { int chunkCount = input . readInt ( ) ; Memory offsets = Memory . allocate ( chunkCount * 8 ) ; for ( int i = 0 ; i < chunkCount ; i ++ ) { try { offsets . setLong ( i * 8 , input . readLong ( ) ) ; } catch ( EOFException e ) { String msg = String . format ( "Corrupted Index File %s: read %d but expected %d chunks." , indexFilePath , i , chunkCount ) ; throw new CorruptSSTableException ( new IOException ( msg , e ) , indexFilePath ) ; } } return offsets ; } catch ( IOException e ) { throw new FSReadError ( e , indexFilePath ) ; } }
|
Read offsets of the individual chunks from the given input .
|
1,453
|
public static SSTableIndexIndex readIndex ( final FileSystem fileSystem , final Path sstablePath ) throws IOException { final Closer closer = Closer . create ( ) ; final Path indexPath = sstablePath . suffix ( SSTABLE_INDEX_SUFFIX ) ; final FSDataInputStream inputStream = closer . register ( fileSystem . open ( indexPath ) ) ; final SSTableIndexIndex indexIndex = new SSTableIndexIndex ( ) ; try { while ( inputStream . available ( ) != 0 ) { indexIndex . add ( inputStream . readLong ( ) , inputStream . readLong ( ) ) ; } } finally { closer . close ( ) ; } return indexIndex ; }
|
Read an existing index . Reads and returns the index index which is a list of chunks defined by the Cassandra Index . db file along with the configured split size .
|
1,454
|
public OutputCommitter getOutputCommitter ( TaskAttemptContext taskAttemptContext ) throws IOException , InterruptedException { return new OutputCommitter ( ) { public void setupJob ( JobContext jobContext ) throws IOException { } public void cleanupJob ( JobContext jobContext ) throws IOException { } public void setupTask ( TaskAttemptContext taskAttemptContext ) throws IOException { } public void commitTask ( TaskAttemptContext taskAttemptContext ) throws IOException { } public void abortTask ( TaskAttemptContext taskAttemptContext ) throws IOException { } public boolean needsTaskCommit ( TaskAttemptContext taskAttemptContext ) throws IOException { return false ; } } ; }
|
and writes to that instead .
|
1,455
|
public static CFMetaData parseCreateStatement ( String cql ) throws RequestValidationException { final CreateColumnFamilyStatement statement = ( CreateColumnFamilyStatement ) QueryProcessor . parseStatement ( cql ) . prepare ( ) . statement ; final CFMetaData cfm = new CFMetaData ( "assess" , "kvs_strict" , ColumnFamilyType . Standard , statement . comparator , null ) ; statement . applyPropertiesTo ( cfm ) ; return cfm ; }
|
Parses a CQL CREATE statement into its CFMetaData object
|
1,456
|
public long next ( ) { try { ByteBufferUtil . readWithShortLength ( input ) ; final long offset = input . readLong ( ) ; skipPromotedIndex ( input ) ; return offset ; } catch ( IOException e ) { throw new IOError ( e ) ; } }
|
Get the next offset from the SSTable index .
|
1,457
|
private void skipPromotedIndex ( final DataInput in ) throws IOException { final int size = in . readInt ( ) ; if ( size <= 0 ) { return ; } FileUtils . skipBytesFully ( in , size ) ; }
|
Convenience method for skipping promoted index from SSTable index file .
|
1,458
|
private Collection < FileStatus > handleFile ( final FileStatus file , final JobContext job ) throws IOException { final List < FileStatus > results = Lists . newArrayList ( ) ; if ( file . isDir ( ) ) { final Path p = file . getPath ( ) ; LOG . debug ( "Expanding {}" , p ) ; final FileSystem fs = p . getFileSystem ( job . getConfiguration ( ) ) ; final FileStatus [ ] children = fs . listStatus ( p ) ; for ( FileStatus child : children ) { results . addAll ( handleFile ( child , job ) ) ; } } else { results . add ( file ) ; } return results ; }
|
If we have a directory recursively gather the files we care about for this job .
|
1,459
|
public final long hash ( byte [ ] data , int c , int d ) { return SipHasher . hash ( c , d , this . v0 , this . v1 , this . v2 , this . v3 , data ) ; }
|
Hashes input data using the preconfigured state .
|
1,460
|
public final SipHasherStream update ( byte b ) { this . len ++ ; this . m |= ( ( ( long ) b & 0xff ) << ( this . m_idx ++ * 8 ) ) ; if ( this . m_idx < 8 ) { return this ; } this . v3 ^= this . m ; for ( int i = 0 ; i < this . c ; i ++ ) { round ( ) ; } this . v0 ^= this . m ; this . m_idx = 0 ; this . m = 0 ; return this ; }
|
Updates the hash with a single byte .
|
1,461
|
public final long digest ( ) { byte msgLenMod256 = this . len ; while ( this . m_idx < 7 ) { update ( ( byte ) 0 ) ; } update ( msgLenMod256 ) ; this . v2 ^= 0xff ; for ( int i = 0 ; i < this . d ; i ++ ) { round ( ) ; } return this . v0 ^ this . v1 ^ this . v2 ^ this . v3 ; }
|
Finalizes the digest and returns the hash .
|
1,462
|
private void round ( ) { this . v0 += this . v1 ; this . v2 += this . v3 ; this . v1 = rotateLeft ( this . v1 , 13 ) ; this . v3 = rotateLeft ( this . v3 , 16 ) ; this . v1 ^= this . v0 ; this . v3 ^= this . v2 ; this . v0 = rotateLeft ( this . v0 , 32 ) ; this . v2 += this . v1 ; this . v0 += this . v3 ; this . v1 = rotateLeft ( this . v1 , 17 ) ; this . v3 = rotateLeft ( this . v3 , 21 ) ; this . v1 ^= this . v2 ; this . v3 ^= this . v0 ; this . v2 = rotateLeft ( this . v2 , 32 ) ; }
|
SipRound implementation for internal use .
|
1,463
|
public static long hash ( byte [ ] key , byte [ ] data , int c , int d ) { if ( key . length != 16 ) { throw new IllegalArgumentException ( "Key must be exactly 16 bytes!" ) ; } long k0 = bytesToLong ( key , 0 ) ; long k1 = bytesToLong ( key , 8 ) ; return hash ( c , d , INITIAL_V0 ^ k0 , INITIAL_V1 ^ k1 , INITIAL_V2 ^ k0 , INITIAL_V3 ^ k1 , data ) ; }
|
Hashes a data input for a given key using the provided rounds of compression .
|
1,464
|
public static String toHexString ( long hash ) { String hex = Long . toHexString ( hash ) ; if ( hex . length ( ) == 16 ) { return hex ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 , j = 16 - hex . length ( ) ; i < j ; i ++ ) { sb . append ( '0' ) ; } return sb . append ( hex ) . toString ( ) ; }
|
Converts a hash to a hexidecimal representation .
|
1,465
|
static long bytesToLong ( byte [ ] bytes , int offset ) { long m = 0 ; for ( int i = 0 ; i < 8 ; i ++ ) { m |= ( ( ( ( long ) bytes [ i + offset ] ) & 0xff ) << ( 8 * i ) ) ; } return m ; }
|
Converts a chunk of 8 bytes to a number in little endian .
|
1,466
|
static long hash ( int c , int d , long v0 , long v1 , long v2 , long v3 , byte [ ] data ) { long m ; int last = data . length / 8 * 8 ; int i = 0 ; int r ; while ( i < last ) { m = data [ i ++ ] & 0xffL ; for ( r = 1 ; r < 8 ; r ++ ) { m |= ( data [ i ++ ] & 0xffL ) << ( r * 8 ) ; } v3 ^= m ; for ( r = 0 ; r < c ; r ++ ) { v0 += v1 ; v2 += v3 ; v1 = rotateLeft ( v1 , 13 ) ; v3 = rotateLeft ( v3 , 16 ) ; v1 ^= v0 ; v3 ^= v2 ; v0 = rotateLeft ( v0 , 32 ) ; v2 += v1 ; v0 += v3 ; v1 = rotateLeft ( v1 , 17 ) ; v3 = rotateLeft ( v3 , 21 ) ; v1 ^= v2 ; v3 ^= v0 ; v2 = rotateLeft ( v2 , 32 ) ; } v0 ^= m ; } m = 0 ; for ( i = data . length - 1 ; i >= last ; -- i ) { m <<= 8 ; m |= ( data [ i ] & 0xffL ) ; } m |= ( long ) data . length << 56 ; v3 ^= m ; for ( r = 0 ; r < c ; r ++ ) { v0 += v1 ; v2 += v3 ; v1 = rotateLeft ( v1 , 13 ) ; v3 = rotateLeft ( v3 , 16 ) ; v1 ^= v0 ; v3 ^= v2 ; v0 = rotateLeft ( v0 , 32 ) ; v2 += v1 ; v0 += v3 ; v1 = rotateLeft ( v1 , 17 ) ; v3 = rotateLeft ( v3 , 21 ) ; v1 ^= v2 ; v3 ^= v0 ; v2 = rotateLeft ( v2 , 32 ) ; } v0 ^= m ; v2 ^= 0xff ; for ( r = 0 ; r < d ; r ++ ) { v0 += v1 ; v2 += v3 ; v1 = rotateLeft ( v1 , 13 ) ; v3 = rotateLeft ( v3 , 16 ) ; v1 ^= v0 ; v3 ^= v2 ; v0 = rotateLeft ( v0 , 32 ) ; v2 += v1 ; v0 += v3 ; v1 = rotateLeft ( v1 , 17 ) ; v3 = rotateLeft ( v3 , 21 ) ; v1 ^= v2 ; v3 ^= v0 ; v2 = rotateLeft ( v2 , 32 ) ; } return v0 ^ v1 ^ v2 ^ v3 ; }
|
Internal 0A hashing implementation .
|
1,467
|
public static < T extends Value > List < List < T > > split ( List < T > input , long targetSize ) { Collections . sort ( input , new Comparator < Value > ( ) { public int compare ( Value o1 , Value o2 ) { return new Long ( o1 . getValue ( ) ) . compareTo ( new Long ( o2 . getValue ( ) ) ) ; } } ) ; List < T > smaller = new ArrayList < T > ( ) ; List < T > bigger = new ArrayList < T > ( ) ; for ( T v : input ) { if ( v . getValue ( ) >= targetSize ) { bigger . add ( v ) ; } else { smaller . add ( v ) ; } } List < List < T > > ret = new ArrayList < List < T > > ( ) ; for ( T b : bigger ) { List < T > elem = new ArrayList < T > ( ) ; elem . add ( b ) ; ret . add ( elem ) ; } while ( smaller . size ( ) > 0 ) { ret . add ( removeBestSubset ( smaller , targetSize ) ) ; } return ret ; }
|
things that are too big get their own set
|
1,468
|
private boolean checkCombineValidity ( Pail p , CopyArgs args ) throws IOException { if ( args . force ) return true ; PailSpec mine = getSpec ( ) ; PailSpec other = p . getSpec ( ) ; PailStructure structure = mine . getStructure ( ) ; boolean typesSame = structure . getType ( ) . equals ( other . getStructure ( ) . getType ( ) ) ; if ( ! structure . getType ( ) . equals ( new byte [ 0 ] . getClass ( ) ) && ! typesSame ) throw new IllegalArgumentException ( "Cannot combine two pails of different types unless target pail is raw" ) ; for ( String name : p . getUserFileNames ( ) ) { checkValidStructure ( name ) ; } return mine . getName ( ) . equals ( other . getName ( ) ) && mine . getArgs ( ) . equals ( other . getArgs ( ) ) ; }
|
returns if formats are same
|
1,469
|
public void copyAppend ( Pail p , CopyArgs args ) throws IOException { args = new CopyArgs ( args ) ; if ( args . renameMode == null ) args . renameMode = RenameMode . ALWAYS_RENAME ; boolean formatsSame = checkCombineValidity ( p , args ) ; String sourceQual = getQualifiedRoot ( p ) ; String destQual = getQualifiedRoot ( this ) ; if ( formatsSame ) { BalancedDistcp . distcp ( sourceQual , destQual , args . renameMode , new PailPathLister ( args . copyMetadata ) , EXTENSION , args . configuration ) ; } else { Coercer . coerce ( sourceQual , destQual , args . renameMode , new PailPathLister ( args . copyMetadata ) , p . getFormat ( ) , getFormat ( ) , EXTENSION , args . configuration ) ; } }
|
Copy append will copy all the files from p into this pail . Appending maintains the structure that was present in p .
|
1,470
|
public static boolean isLong ( String input ) { try { Long . parseLong ( input ) ; return true ; } catch ( Exception e ) { return false ; } }
|
Return true or false if the input is a long
|
1,471
|
private void parseAnnotatableText ( String text , Element parent ) { AnnotationNode annotation = null ; Matcher matcher = AnnotationParser . WIDGET_ANNOTATION_REGEX . matcher ( text ) ; int previousEnd = 0 ; while ( matcher . find ( ) ) { int start = matcher . start ( ) ; if ( start > previousEnd ) { String segment = text . substring ( previousEnd , start ) ; if ( segment . trim ( ) . length ( ) > 0 ) { addTextNodeToParent ( segment , parent , annotation ) ; annotation = null ; } } String annotationText = matcher . group ( ) . trim ( ) ; if ( null != annotationText ) { annotation = new AnnotationNode ( annotationText ) ; lines ( annotation , annotationText ) ; } previousEnd = matcher . end ( ) ; } if ( previousEnd > 0 && previousEnd < text . length ( ) ) { String segment = text . substring ( previousEnd ) ; if ( segment . trim ( ) . length ( ) > 0 ) { addTextNodeToParent ( segment , parent , annotation ) ; annotation = null ; } } if ( annotation != null ) add ( annotation ) ; if ( previousEnd == 0 ) { Node dataNode ; if ( parent . tagName ( ) . equals ( titleTag ) || parent . tagName ( ) . equals ( textareaTag ) ) dataNode = TextNode . createFromEncoded ( text , baseUri ) ; else dataNode = new DataNode ( text , baseUri ) ; lines ( dataNode , text ) ; if ( pendingAnnotation != null ) pendingAnnotation . apply ( dataNode ) ; parent . appendChild ( dataNode ) ; } }
|
Pulls a text segment apart by annotations within it and creates multiple Text Nodes applying the annotation to each text segment as approriate .
|
1,472
|
private void addTextNodeToParent ( String text , Element parent , AnnotationNode annotation ) { String [ ] lines = new String [ ] { text } ; if ( annotation != null ) lines = splitInTwo ( text ) ; for ( int i = 0 ; i < lines . length ; i ++ ) { TextNode textNode = TextNode . createFromEncoded ( lines [ i ] , baseUri ) ; lines ( textNode , lines [ i ] ) ; if ( annotation != null && i == 0 ) annotation . apply ( textNode ) ; parent . appendChild ( textNode ) ; } }
|
Break the text up by the first line delimiter . We only want annotations applied to the first line of a block of text and not to a whole segment .
|
1,473
|
private String [ ] splitInTwo ( String text ) { Matcher matcher = LINE_SEPARATOR . matcher ( text ) ; while ( matcher . find ( ) ) { int start = matcher . start ( ) ; if ( start > 0 && start < text . length ( ) ) { String segment = text . substring ( 0 , start ) ; if ( segment . trim ( ) . length ( ) > 0 ) return new String [ ] { text . substring ( 0 , start ) , text . substring ( start ) } ; } } return new String [ ] { text } ; }
|
Break a text segment apart into two at the first line delimiter which has non - whitespace characters before it .
|
1,474
|
boolean canContain ( Tag parent , Tag child ) { Validate . notNull ( child ) ; if ( child . isBlock ( ) && ! parent . canContainBlock ( ) ) return false ; if ( ! child . isBlock ( ) && parent . isData ( ) ) return false ; if ( closingOptional . contains ( parent . getName ( ) ) && parent . getName ( ) . equals ( child . getName ( ) ) ) return false ; if ( parent . isEmpty ( ) || parent . isData ( ) ) return false ; if ( parent . getName ( ) . equals ( "head" ) ) { if ( headTags . contains ( child . getName ( ) ) ) return true ; else return false ; } if ( parent . getName ( ) . equals ( "dt" ) && child . getName ( ) . equals ( "dd" ) ) return false ; if ( parent . getName ( ) . equals ( "dd" ) && child . getName ( ) . equals ( "dt" ) ) return false ; return true ; }
|
Test if this tag the prospective parent can accept the proposed child .
|
1,475
|
static String readAnnotationValue ( Annotation annotation ) { try { Method m = annotation . getClass ( ) . getMethod ( "value" ) ; return ( String ) m . invoke ( annotation ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( "Encountered a configured annotation that " + "has no value parameter. This should never happen. " + annotation , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( "Encountered a configured annotation that " + "could not be read." + annotation , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( "Encountered a configured annotation that " + "could not be read." + annotation , e ) ; } }
|
A simple utility method that reads the String value attribute of any annotation instance .
|
1,476
|
private ParserContext singleBackingTypeParserContext ( ) throws ExpressionCompileException { ParserContext context = new ParserContext ( ) ; context . setStrongTyping ( true ) ; context . addInput ( "this" , backingType ) ; PropertyDescriptor [ ] propertyDescriptors ; try { propertyDescriptors = Introspector . getBeanInfo ( backingType ) . getPropertyDescriptors ( ) ; } catch ( IntrospectionException e ) { throw new ExpressionCompileException ( "Could not read class " + backingType ) ; } for ( Field field : backingType . getDeclaredFields ( ) ) { if ( field . isAnnotationPresent ( Visible . class ) ) { context . addInput ( field . getName ( ) , field . getType ( ) ) ; if ( ! field . getAnnotation ( Visible . class ) . readOnly ( ) ) { writeableProperties . add ( field . getName ( ) ) ; } } } for ( PropertyDescriptor propertyDescriptor : propertyDescriptors ) { if ( CLASS . equals ( propertyDescriptor . getName ( ) ) ) continue ; if ( null != propertyDescriptor . getWriteMethod ( ) ) { writeableProperties . add ( propertyDescriptor . getName ( ) ) ; } if ( Collection . class . isAssignableFrom ( propertyDescriptor . getPropertyType ( ) ) ) { Type propertyType ; if ( propertyDescriptor . getReadMethod ( ) != null ) { propertyType = propertyDescriptor . getReadMethod ( ) . getGenericReturnType ( ) ; } else { propertyType = propertyDescriptor . getWriteMethod ( ) . getGenericParameterTypes ( ) [ 0 ] ; } ParameterizedType collectionType = ( ParameterizedType ) Generics . getExactSuperType ( propertyType , Collection . class ) ; Class < ? > [ ] parameterClasses = new Class [ 1 ] ; Type parameterType = collectionType . getActualTypeArguments ( ) [ 0 ] ; parameterClasses [ 0 ] = Generics . erase ( parameterType ) ; context . addInput ( propertyDescriptor . getName ( ) , propertyDescriptor . getPropertyType ( ) , parameterClasses ) ; } else { context . addInput ( propertyDescriptor . getName ( ) , propertyDescriptor . getPropertyType ( ) ) ; } } return context ; }
|
generates a parsing context with type information from the backing type s javabean properties
|
1,477
|
private static List < PathMatcher > toMatchChain ( String path ) { String [ ] pieces = path . split ( PATH_SEPARATOR ) ; List < PathMatcher > matchers = new ArrayList < PathMatcher > ( ) ; for ( String piece : pieces ) { matchers . add ( ( piece . startsWith ( ":" ) ) ? new GreedyPathMatcher ( piece ) : new SimplePathMatcher ( piece ) ) ; } return Collections . unmodifiableList ( matchers ) ; }
|
converts a string path to a tree of heterogenous matchers
|
1,478
|
public synchronized boolean connect ( final DisconnectListener listener ) { reset ( ) ; ChannelFuture future = bootstrap . connect ( new InetSocketAddress ( config . getHost ( ) , config . getPort ( ) ) ) ; Channel channel = future . awaitUninterruptibly ( ) . getChannel ( ) ; if ( ! future . isSuccess ( ) ) { throw new RuntimeException ( "Could not connect channel" , future . getCause ( ) ) ; } this . channel = channel ; this . disconnectListener = listener ; if ( null != listener ) { channel . getCloseFuture ( ) . addListener ( new ChannelFutureListener ( ) { public void operationComplete ( ChannelFuture future ) throws Exception { mailClientHandler . idleAcknowledged . set ( false ) ; mailClientHandler . disconnected ( ) ; listener . disconnected ( ) ; } } ) ; } return login ( ) ; }
|
Connects to the IMAP server logs in with the given credentials .
|
1,479
|
public synchronized void disconnect ( ) { try { if ( ! mailClientHandler . isHalted ( ) ) { if ( mailClientHandler . idleRequested . get ( ) ) { log . warn ( "Disconnect called while IDLE, leaving idle and logging out." ) ; done ( ) ; } channel . write ( ". logout\n" ) ; } currentFolder = null ; } catch ( Exception e ) { } finally { try { channel . close ( ) . awaitUninterruptibly ( config . getTimeout ( ) , TimeUnit . MILLISECONDS ) ; } catch ( Exception e ) { } finally { mailClientHandler . idleAcknowledged . set ( false ) ; mailClientHandler . disconnected ( ) ; if ( disconnectListener != null ) disconnectListener . disconnected ( ) ; } } }
|
Logs out of the current IMAP session and releases all resources including executor services .
|
1,480
|
public static List < Token > tokenize ( String warpRawText , EvaluatorCompiler compiler ) throws ExpressionCompileException { ArrayList < Token > tokens = new ArrayList < Token > ( ) ; char [ ] characters = warpRawText . toCharArray ( ) ; StringBuilder token = new StringBuilder ( ) ; TokenizerState state = TokenizerState . READING_TEXT ; for ( int i = 0 ; i < characters . length ; i ++ ) { if ( TokenizerState . READING_TEXT . equals ( state ) ) { if ( '$' == characters [ i ] ) { if ( '{' == characters [ i + 1 ] ) { if ( token . length ( ) > 0 ) { tokens . add ( CompiledToken . text ( token . toString ( ) ) ) ; token = new StringBuilder ( ) ; } state = TokenizerState . READING_EXPRESSION ; } } } if ( TokenizerState . READING_EXPRESSION . equals ( state ) ) { if ( '}' == characters [ i ] ) { token . append ( characters [ i ] ) ; tokens . add ( CompiledToken . expression ( token . toString ( ) , compiler ) ) ; token = new StringBuilder ( ) ; state = TokenizerState . READING_TEXT ; continue ; } } token . append ( characters [ i ] ) ; } if ( TokenizerState . READING_EXPRESSION . equals ( state ) ) throw new IllegalStateException ( "Error. Expression was not terminated properly: " + token . toString ( ) ) ; if ( token . length ( ) > 0 ) tokens . add ( CompiledToken . text ( token . toString ( ) ) ) ; tokens . trimToSize ( ) ; return tokens ; }
|
tokenizes text into raw text chunks interspersed with expression chunks
|
1,481
|
private void collectBindings ( List < SitebricksModule . LinkingBinder > bindings , Set < PageBook . Page > pagesToCompile ) { Map < Class < ? extends Annotation > , String > methodSet = null ; for ( SitebricksModule . LinkingBinder binding : bindings ) { if ( EMBEDDED == binding . bindingKind ) { if ( null == binding . embedAs ) { throw new IllegalStateException ( "embed() missing .as() clause: " + binding . pageClass ) ; } registry . addEmbed ( binding . embedAs ) ; pagesToCompile . add ( pageBook . embedAs ( binding . pageClass , binding . embedAs ) ) ; } else if ( PAGE == binding . bindingKind ) { pagesToCompile . add ( pageBook . at ( binding . uri , binding . pageClass ) ) ; } else if ( STATIC_RESOURCE == binding . bindingKind ) { resourcesService . add ( SitebricksModule . class , binding . getResource ( ) ) ; } else if ( SERVICE == binding . bindingKind ) { pagesToCompile . add ( pageBook . serviceAt ( binding . uri , binding . pageClass ) ) ; } else if ( ACTION == binding . bindingKind ) { if ( null == methodSet ) { methodSet = HashBiMap . create ( methodMap ) . inverse ( ) ; } pageBook . at ( binding . uri , binding . actionDescriptors , methodSet ) ; } } }
|
processes all explicit bindings including static resources .
|
1,482
|
private Set < PageBook . Page > scanPagesToCompile ( Set < Class < ? > > set ) { Set < Templates . Descriptor > templates = Sets . newHashSet ( ) ; Set < PageBook . Page > pagesToCompile = Sets . newHashSet ( ) ; for ( Class < ? > pageClass : set ) { EmbedAs embedAs = pageClass . getAnnotation ( EmbedAs . class ) ; if ( null != embedAs ) { final String embedName = embedAs . value ( ) ; if ( Renderable . class . isAssignableFrom ( pageClass ) ) { @ SuppressWarnings ( "unchecked" ) Class < ? extends Renderable > renderable = ( Class < ? extends Renderable > ) pageClass ; registry . add ( embedName , renderable ) ; } else { pagesToCompile . add ( embed ( embedName , pageClass ) ) ; } } At at = pageClass . getAnnotation ( At . class ) ; if ( null != at ) { if ( pageClass . isAnnotationPresent ( Service . class ) ) { pagesToCompile . add ( pageBook . serviceAt ( at . value ( ) , pageClass ) ) ; } else if ( pageClass . isAnnotationPresent ( Export . class ) ) { resourcesService . add ( SitebricksModule . class , pageClass . getAnnotation ( Export . class ) ) ; } else { pagesToCompile . add ( pageBook . at ( at . value ( ) , pageClass ) ) ; } } if ( pageClass . isAnnotationPresent ( Show . class ) ) { templates . add ( new Templates . Descriptor ( pageClass , pageClass . getAnnotation ( Show . class ) . value ( ) ) ) ; } } if ( Stage . DEVELOPMENT != currentStage ) { this . templates . loadAll ( templates ) ; } return pagesToCompile ; }
|
goes through the set of scanned classes and builds pages out of them .
|
1,483
|
private Class < ? > nextDecoratedClassInHierarchy ( Class < ? > previousTemplateClass , Class < ? > candidate ) { if ( candidate == previousTemplateClass ) { return null ; } else if ( candidate == Object . class ) { throw new IllegalStateException ( "Did not find previous extension" ) ; } else { boolean isDecorated = candidate . isAnnotationPresent ( Decorated . class ) ; if ( isDecorated ) return candidate ; else return nextDecoratedClassInHierarchy ( previousTemplateClass , candidate . getSuperclass ( ) ) ; } }
|
recursively find the next superclass with an
|
1,484
|
public void setBody ( String body ) { assert bodyParts . isEmpty ( ) : "Unexpected set body call to a multipart email" ; bodyParts . add ( new BodyPart ( body ) ) ; }
|
Short hand .
|
1,485
|
public Set < String > extract ( List < String > messages ) throws ExtractionException { boolean gotFetch = false ; Set < String > result = null ; String fetchStr = null ; for ( int i = 0 , messagesSize = messages . size ( ) ; i < messagesSize ; i ++ ) { String message = messages . get ( i ) ; if ( null == message || message . isEmpty ( ) ) continue ; fetchStr = matchAndGetGroup1 ( FETCH_LABEL_PATT , message ) ; if ( fetchStr != null ) { if ( gotFetch ) { throw new ExtractionException ( "STORE_LABELS RESPONSE: Got more than one FETCH " + "response " + message ) ; } gotFetch = true ; result = Sets . < String > newHashSet ( ) ; result . addAll ( Parsing . tokenize ( fetchStr ) ) ; result . remove ( "(" ) ; result . remove ( ")" ) ; } else { if ( matchAndGetGroup1 ( OK_PATT , message ) != null ) { if ( ! gotFetch ) { throw new ExtractionException ( "STORE_LABELS RESPONSE: no LABELS received." + message ) ; } } else if ( matchAndGetGroup1 ( BAD_PATT , message ) != null || matchAndGetGroup1 ( NO_PATT , message ) != null ) { throw new ExtractionException ( "STORE_LABELS RESPONSE: " + message ) ; } } } return result ; }
|
Parse the response which includes label settings and command status . We expect only one FETCH response as we only set labels on one msg .
|
1,486
|
public void enqueue ( CommandCompletion completion ) { completions . add ( completion ) ; commandTrace . add ( new Date ( ) . toString ( ) + " " + completion . toString ( ) ) ; }
|
DO NOT synchronize!
|
1,487
|
private synchronized void complete ( String message ) { if ( MESSAGE_COULDNT_BE_FETCHED_REGEX . matcher ( message ) . matches ( ) ) { log . warn ( "Some messages in the batch could not be fetched for {}\n" + "---cmd---\n{}\n---wire---\n{}\n---end---\n" , new Object [ ] { config . getUsername ( ) , getCommandTrace ( ) , getWireTrace ( ) } ) ; errorStack . push ( new Error ( completions . peek ( ) , message , wireTrace . list ( ) ) ) ; final CommandCompletion completion = completions . peek ( ) ; String errorMsg = "Some messages in the batch could not be fetched for user " + config . getUsername ( ) ; RuntimeException ex = new RuntimeException ( errorMsg ) ; if ( completion != null ) { completion . error ( errorMsg , new MailHandlingException ( getWireTrace ( ) , errorMsg , ex ) ) ; completions . poll ( ) ; } else { throw ex ; } } CommandCompletion completion = completions . peek ( ) ; if ( completion == null ) { if ( "+ idling" . equalsIgnoreCase ( message ) ) { synchronized ( idleMutex ) { idler . idleStart ( ) ; log . trace ( "IDLE entered." ) ; idleAcknowledged . set ( true ) ; } } else { log . error ( "Could not find the completion for message {} (Was it ever issued?)" , message ) ; errorStack . push ( new Error ( null , "No completion found!" , wireTrace . list ( ) ) ) ; } return ; } if ( completion . complete ( message ) ) { completions . poll ( ) ; } }
|
This is synchronized to ensure that we process the queue serially .
|
1,488
|
void observe ( FolderObserver observer ) { synchronized ( idleMutex ) { this . observer = observer ; pushedData = new PushedData ( ) ; idleAcknowledged . set ( false ) ; } }
|
Registers a FolderObserver to receive events happening with a particular folder . Typically an IMAP IDLE feature . If called multiple times will overwrite the currently set observer .
|
1,489
|
public static Localization defaultLocalizationFor ( Class < ? > iface ) { Map < String , String > defaultMessages = Maps . newHashMap ( ) ; for ( Method method : iface . getMethods ( ) ) { Message msg = method . getAnnotation ( Message . class ) ; if ( null != msg ) { defaultMessages . put ( method . getName ( ) , msg . message ( ) ) ; } } return new Localization ( iface , Locale . getDefault ( ) , defaultMessages ) ; }
|
Returns a localization value object describing the defaults specified in the
|
1,490
|
public String build ( Protocol protocol , String oauthToken , String oauthTokenSecret ) throws IOException , OAuthException , URISyntaxException { OAuthAccessor accessor = new OAuthAccessor ( consumer ) ; accessor . tokenSecret = oauthTokenSecret ; Map < String , String > parameters = new HashMap < String , String > ( ) ; parameters . put ( OAuth . OAUTH_SIGNATURE_METHOD , "HMAC-SHA1" ) ; parameters . put ( OAuth . OAUTH_TOKEN , oauthToken ) ; String url = String . format ( "https://mail.google.com/mail/b/%s/%s/" , email , ( Protocol . IMAP == protocol ) ? "imap" : "smtp" ) ; OAuthMessage message = new OAuthMessage ( "GET" , url , parameters . entrySet ( ) ) ; message . addRequiredParameters ( accessor ) ; StringBuilder authString = new StringBuilder ( ) ; authString . append ( "GET " ) ; authString . append ( url ) ; authString . append ( " " ) ; int i = 0 ; for ( Map . Entry < String , String > entry : message . getParameters ( ) ) { if ( i ++ > 0 ) { authString . append ( "," ) ; } authString . append ( OAuth . percentEncode ( entry . getKey ( ) ) ) ; authString . append ( "=\"" ) ; authString . append ( OAuth . percentEncode ( entry . getValue ( ) ) ) ; authString . append ( "\"" ) ; } return Base64 . encode ( authString . toString ( ) . getBytes ( ) ) ; }
|
Builds an XOAUTH SASL client response .
|
1,491
|
public static Class < ? > erase ( Type type ) { if ( type instanceof Class < ? > ) { return ( Class < ? > ) type ; } else if ( type instanceof ParameterizedType ) { return ( Class < ? > ) ( ( ParameterizedType ) type ) . getRawType ( ) ; } else if ( type instanceof TypeVariable < ? > ) { TypeVariable < ? > tv = ( TypeVariable < ? > ) type ; if ( tv . getBounds ( ) . length == 0 ) return Object . class ; else return erase ( tv . getBounds ( ) [ 0 ] ) ; } else if ( type instanceof GenericArrayType ) { GenericArrayType aType = ( GenericArrayType ) type ; return GenericArrayTypeImpl . createArrayType ( erase ( aType . getGenericComponentType ( ) ) ) ; } else { throw new RuntimeException ( "not supported: " + type . getClass ( ) ) ; } }
|
Returns the erasure of the given type .
|
1,492
|
private static Type mapTypeParameters ( Type toMapType , Type typeAndParams ) { if ( isMissingTypeParameters ( typeAndParams ) ) { return erase ( toMapType ) ; } else { VarMap varMap = new VarMap ( ) ; Type handlingTypeAndParams = typeAndParams ; while ( handlingTypeAndParams instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) handlingTypeAndParams ; Class < ? > clazz = ( Class < ? > ) pType . getRawType ( ) ; varMap . addAll ( clazz . getTypeParameters ( ) , pType . getActualTypeArguments ( ) ) ; handlingTypeAndParams = pType . getOwnerType ( ) ; } return varMap . map ( toMapType ) ; } }
|
Maps type parameters in a type to their values .
|
1,493
|
private < N extends Node > WidgetChain walk ( PageCompilingContext pc , N node ) { WidgetChain widgetChain = Chains . proceeding ( ) ; for ( Node n : node . childNodes ( ) ) { if ( n instanceof Element ) { final Element child = ( Element ) n ; if ( child . tagName ( ) . equals ( "form" ) ) pc . form = ( Element ) n ; final boolean shouldPopScope = lexicalClimb ( pc , child ) ; WidgetChain childsChildren ; try { childsChildren = walk ( pc , child ) ; widgetChain . addWidget ( widgetize ( pc , child , childsChildren ) ) ; } finally { lexicalDescend ( pc , child , shouldPopScope ) ; } } else if ( n instanceof TextNode ) { TextNode child = ( TextNode ) n ; Renderable textWidget ; final boolean shouldPopScope = lexicalClimb ( pc , child ) ; try { textWidget = registry . textWidget ( cleanHtml ( n ) , pc . lexicalScopes . peek ( ) ) ; if ( ! child . hasAttr ( ANNOTATION_KEY ) ) { widgetChain . addWidget ( textWidget ) ; } else { WidgetChain childsChildren = Chains . proceeding ( ) . addWidget ( textWidget ) ; String widgetName = child . attr ( ANNOTATION_KEY ) . toLowerCase ( ) ; Renderable annotationWidget = registry . newWidget ( widgetName , child . attr ( ANNOTATION_CONTENT ) , childsChildren , pc . lexicalScopes . peek ( ) ) ; widgetChain . addWidget ( annotationWidget ) ; } } catch ( ExpressionCompileException e ) { pc . errors . add ( CompileError . in ( node . outerHtml ( ) ) . near ( line ( n ) ) . causedBy ( e ) ) ; } if ( shouldPopScope ) pc . lexicalScopes . pop ( ) ; } else if ( ( n instanceof Comment ) || ( n instanceof DataNode ) ) { try { widgetChain . addWidget ( registry . textWidget ( cleanHtml ( n ) , pc . lexicalScopes . peek ( ) ) ) ; } catch ( ExpressionCompileException e ) { pc . errors . add ( CompileError . in ( node . outerHtml ( ) ) . near ( line ( node ) ) . causedBy ( e ) ) ; } } else if ( n instanceof XmlDeclaration ) { try { widgetChain . addWidget ( registry . xmlDirectiveWidget ( ( ( XmlDeclaration ) n ) . getWholeDeclaration ( ) , pc . lexicalScopes . peek ( ) ) ) ; } catch ( ExpressionCompileException e ) { pc . errors . add ( CompileError . in ( node . outerHtml ( ) ) . near ( line ( node ) ) . causedBy ( e ) ) ; } } } return widgetChain ; }
|
Walks the DOM recursively and converts elements into corresponding sitebricks widgets .
|
1,494
|
private boolean lexicalClimb ( PageCompilingContext pc , Node node ) { if ( node . attr ( ANNOTATION ) . length ( ) > 1 ) { if ( REPEAT_WIDGET . equalsIgnoreCase ( node . attr ( ANNOTATION_KEY ) ) || CHOOSE_WIDGET . equalsIgnoreCase ( node . attr ( ANNOTATION_KEY ) ) ) { String [ ] keyAndContent = { node . attr ( ANNOTATION_KEY ) , node . attr ( ANNOTATION_CONTENT ) } ; pc . lexicalScopes . push ( new MvelEvaluatorCompiler ( parseRepeatScope ( pc , keyAndContent , node ) ) ) ; return true ; } final PageBook . Page embed = pageBook . forName ( node . attr ( ANNOTATION_KEY ) ) ; if ( null != embed ) { final Class < ? > embedClass = embed . pageClass ( ) ; MvelEvaluatorCompiler compiler = new MvelEvaluatorCompiler ( embedClass ) ; checkEmbedAgainst ( pc , compiler , Parsing . toBindMap ( node . attr ( ANNOTATION_CONTENT ) ) , embedClass , node ) ; pc . lexicalScopes . push ( compiler ) ; return true ; } } return false ; }
|
Called to push a new lexical scope onto the stack .
|
1,495
|
private void checkEmbedAgainst ( PageCompilingContext pc , EvaluatorCompiler compiler , Map < String , String > properties , Class < ? > embedClass , Node node ) { for ( String property : properties . keySet ( ) ) { try { if ( ! compiler . isWritable ( property ) ) { pc . errors . add ( CompileError . in ( node . outerHtml ( ) ) . near ( node . siblingIndex ( ) - 1 ) . causedBy ( CompileErrors . PROPERTY_NOT_WRITEABLE , String . format ( "Property %s#%s was not writable. Did you forget to create " + "a setter or @Visible annotation?" , embedClass . getSimpleName ( ) , property ) ) ) ; } } catch ( ExpressionCompileException ece ) { pc . errors . add ( CompileError . in ( node . outerHtml ( ) ) . near ( node . siblingIndex ( ) ) . causedBy ( CompileErrors . ERROR_COMPILING_PROPERTY ) ) ; } } }
|
Ensures that embed bound properties are writable
|
1,496
|
public List < Node > findSiblings ( Node node ) { Preconditions . checkNotNull ( node ) ; Node parent = node . parent ( ) ; if ( null == parent ) return null ; return parent . childNodes ( ) ; }
|
TESTING jsoup . nodes . Node
|
1,497
|
private static String cleanHtml ( final Node node ) { if ( node instanceof Element ) { Element element = ( ( Element ) node ) ; StringBuilder accum = new StringBuilder ( ) ; accum . append ( "<" ) . append ( element . tagName ( ) ) ; for ( Attribute attribute : element . attributes ( ) ) { if ( ! ( attribute . getKey ( ) . startsWith ( "_" ) ) ) { accum . append ( " " ) ; accum . append ( attribute . getKey ( ) ) ; accum . append ( "=\"" ) ; accum . append ( attribute . getValue ( ) ) ; accum . append ( '"' ) ; } } if ( element . childNodes ( ) . isEmpty ( ) && element . tag ( ) . isEmpty ( ) ) { accum . append ( " />" ) ; } else { accum . append ( ">" ) ; for ( Node child : element . childNodes ( ) ) accum . append ( cleanHtml ( child ) ) ; accum . append ( "</" ) . append ( element . tagName ( ) ) . append ( ">" ) ; } return accum . toString ( ) ; } else if ( node instanceof TextNode ) { return ( ( TextNode ) node ) . getWholeText ( ) ; } else if ( node instanceof XmlDeclaration ) { if ( node . childNodes ( ) . isEmpty ( ) ) { return "" ; } return node . outerHtml ( ) ; } else if ( node instanceof Comment ) { return "" ; } else if ( node instanceof DataNode && node . childNodes ( ) . isEmpty ( ) ) { String content = node . attr ( "data" ) ; if ( Strings . empty ( content ) ) { return "" ; } return content ; } else { return node . outerHtml ( ) ; } }
|
outerHtml from jsoup . Node Element with suppressed _attribs
|
1,498
|
private Object search ( Collection < ? > collection , String hashKey ) { int hash = Integer . valueOf ( hashKey ) ; for ( Object o : collection ) { if ( o . hashCode ( ) == hash ) return o ; } return null ; }
|
Linear collection search by hashcode
|
1,499
|
public AnnotationNode annotation ( String annotation ) { this . attr ( ANNOTATION , annotation ) ; String [ ] kc = AnnotationParser . extractKeyAndContent ( annotation ) ; this . attr ( ANNOTATION_KEY , kc [ 0 ] ) ; this . attr ( ANNOTATION_CONTENT , kc [ 1 ] ) ; return this ; }
|
Set the annotation of this node .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.