idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
22,600
@ SuppressWarnings ( "rawtypes" ) public int compare ( ITuple w1 , ITuple w2 ) { int schemaId1 = tupleMRConf . getSchemaIdByName ( w1 . getSchema ( ) . getName ( ) ) ; int schemaId2 = tupleMRConf . getSchemaIdByName ( w2 . getSchema ( ) . getName ( ) ) ; int [ ] indexes1 = serInfo . getGroupSchemaIndexTranslation ( schemaId1 ) ; int [ ] indexes2 = serInfo . getGroupSchemaIndexTranslation ( schemaId2 ) ; Serializer [ ] serializers = serInfo . getGroupSchemaSerializers ( ) ; return compare ( w1 . getSchema ( ) , groupCriteria , w1 , indexes1 , w2 , indexes2 , serializers ) ; }
Never called in MapRed jobs . Just for completion and test purposes
22,601
public void encodeNBitUnsignedInteger ( int b , int n ) throws IOException { if ( b < 0 || n < 0 ) { throw new IllegalArgumentException ( "Encode negative value as unsigned integer is invalid!" ) ; } assert ( b >= 0 ) ; assert ( n >= 0 ) ; ostream . writeBits ( b , n ) ; }
Encode n - bit unsigned integer . The n least significant bits of parameter b starting with the most significant i . e . from left to right .
22,602
public static Schema subSetOf ( Schema schema , String ... subSetFields ) { return subSetOf ( "subSetSchema" + ( COUNTER ++ ) , schema , subSetFields ) ; }
Creates a subset of the input Schema exactly with the fields whose names are specified . The name of the schema is auto - generated with a static counter .
22,603
public static Schema subSetOf ( String newName , Schema schema , String ... subSetFields ) { List < Field > newSchema = new ArrayList < Field > ( ) ; for ( String subSetField : subSetFields ) { newSchema . add ( schema . getField ( subSetField ) ) ; } return new Schema ( newName , newSchema ) ; }
Creates a subset of the input Schema exactly with the fields whose names are specified . The name of the schema is also specified as a parameter .
22,604
public static Schema superSetOf ( Schema schema , Field ... newFields ) { return superSetOf ( "superSetSchema" + ( COUNTER ++ ) , schema , newFields ) ; }
Creates a superset of the input Schema taking all the Fields in the input schema and adding some new ones . The new fields are fully specified in a Field class . The name of the schema is auto - generated with a static counter .
22,605
public static Schema superSetOf ( String newName , Schema schema , Field ... newFields ) { List < Field > newSchema = new ArrayList < Field > ( ) ; newSchema . addAll ( schema . getFields ( ) ) ; for ( Field newField : newFields ) { newSchema . add ( newField ) ; } return new Schema ( newName , newSchema ) ; }
Creates a superset of the input Schema taking all the Fields in the input schema and adding some new ones . The new fields are fully specified in a Field class . The name of the schema is also specified as a parameter .
22,606
public void setupScheduler ( ) { for ( SchedulerTask task : tasks ) { if ( task . getDelay ( ) > 0 && task . getInterval ( ) > 0 ) { executor . scheduleWithFixedDelay ( task . getTask ( ) , task . getDelay ( ) , task . getInterval ( ) , task . getTimeUnit ( ) ) ; } else if ( task . isImmediate ( ) && task . getInterval ( ) > 0 ) { executor . scheduleWithFixedDelay ( task . getTask ( ) , 0l , task . getInterval ( ) , task . getTimeUnit ( ) ) ; } else if ( task . getDelay ( ) > 0 ) { executor . schedule ( task . getTask ( ) , task . getDelay ( ) , task . getTimeUnit ( ) ) ; } else { executor . execute ( task . getTask ( ) ) ; } } }
Schedules all tasks injected in by guice .
22,607
public File getAlternateContentDirectory ( String userAgent ) { Configuration config = liveConfig ; for ( AlternateContent configuration : config . configs ) { try { if ( configuration . compiledPattern . matcher ( userAgent ) . matches ( ) ) { return new File ( config . metaDir , configuration . getContentDirectory ( ) ) ; } } catch ( Exception e ) { logger . warn ( "Failed to process config: " + configuration . getPattern ( ) + "->" + configuration . getContentDirectory ( ) , e ) ; } } return null ; }
Iterates through AlternateContent objects trying to match against their pre compiled pattern .
22,608
public void addIntermediateSchema ( Schema schema ) throws TupleMRException { if ( schemaAlreadyExists ( schema . getName ( ) ) ) { throw new TupleMRException ( "There's a schema with that name '" + schema . getName ( ) + "'" ) ; } schemas . add ( schema ) ; }
Adds a Map - output schema . Tuples emitted by TupleMapper will use one of the schemas added by this method . Schemas added in consecutive calls to this method must be named differently .
22,609
public void setOrderBy ( OrderBy ordering ) throws TupleMRException { failIfNull ( ordering , "OrderBy can't be null" ) ; failIfEmpty ( ordering . getElements ( ) , "OrderBy can't be empty" ) ; failIfEmpty ( schemas , "Need to specify source schemas" ) ; failIfEmpty ( groupByFields , "Need to specify group by fields" ) ; if ( schemas . size ( ) == 1 ) { if ( ordering . getSchemaOrderIndex ( ) != null ) { throw new TupleMRException ( "Not able to use source order when just one source specified" ) ; } } Schema firstSchema = schemas . get ( 0 ) ; for ( SortElement sortElement : ordering . getElements ( ) ) { if ( ! fieldPresentInAllSchemas ( sortElement . getName ( ) ) ) { throw new TupleMRException ( "Can't sort by field '" + sortElement . getName ( ) + "' . Not present in all sources" ) ; } if ( ! fieldSameTypeInAllSources ( sortElement . getName ( ) ) ) { throw new TupleMRException ( "Can't sort by field '" + sortElement . getName ( ) + "' since its type differs among sources" ) ; } if ( sortElement . getCustomComparator ( ) != null ) { Field field = firstSchema . getField ( sortElement . getName ( ) ) ; if ( field . getType ( ) != Type . OBJECT ) { throw new TupleMRException ( "Not allowed to specify custom comparator for type=" + field . getType ( ) ) ; } } } for ( String groupField : groupByFields ) { if ( ! ordering . containsBeforeSchemaOrder ( groupField ) ) { throw new TupleMRException ( "Group by field '" + groupField + "' is not present in common order by before source order" ) ; } } this . commonOrderBy = ordering ; }
Sets the criteria to sort the tuples by . In a multi - schema scenario all the fields defined in the specified ordering must be present in every intermediate schema defined .
22,610
public void setSpecificOrderBy ( String schemaName , OrderBy ordering ) throws TupleMRException { failIfNull ( schemaName , "Not able to set specific orderBy for null source" ) ; if ( ! schemaAlreadyExists ( schemaName ) ) { throw new TupleMRException ( "Unknown source '" + schemaName + "' in specific OrderBy" ) ; } failIfNull ( ordering , "Not able to set null criteria for source '" + schemaName + "'" ) ; failIfEmpty ( ordering . getElements ( ) , "Can't set empty ordering" ) ; failIfNull ( commonOrderBy , "Not able to set specific order with no previous common OrderBy" ) ; if ( commonOrderBy . getSchemaOrderIndex ( ) == null ) { throw new TupleMRException ( "Need to specify source order in common OrderBy when using specific OrderBy" ) ; } if ( ordering . getSchemaOrderIndex ( ) != null ) { throw new TupleMRException ( "Not allowed to set source order in specific order" ) ; } Schema schema = getSchemaByName ( schemaName ) ; Map < String , String > aliases = fieldAliases . get ( schema . getName ( ) ) ; for ( SortElement e : ordering . getElements ( ) ) { if ( ! Schema . containsFieldUsingAlias ( schema , e . getName ( ) , aliases ) ) { throw new TupleMRException ( "Source '" + schemaName + "' doesn't contain field '" + e . getName ( ) ) ; } if ( e . getCustomComparator ( ) != null ) { Field field = schema . getField ( e . getName ( ) ) ; if ( field == null ) { field = schema . getField ( aliases . get ( e . getName ( ) ) ) ; } if ( field . getType ( ) != Type . OBJECT ) { throw new TupleMRException ( "Not allowed to set custom comparator for type=" + field . getType ( ) ) ; } } } for ( SortElement e : ordering . getElements ( ) ) { if ( commonOrderBy . containsFieldName ( e . getName ( ) ) ) { throw new TupleMRException ( "Common sort by already contains sorting for field '" + e . getName ( ) ) ; } } this . specificsOrderBy . put ( schemaName , ordering ) ; }
Sets how tuples from the specific schemaName will be sorted after being sorted by commonOrderBy and schemaOrder
22,611
private void initComparators ( ) { TupleMRConfigBuilder . initializeComparators ( context . getHadoopContext ( ) . getConfiguration ( ) , tupleMRConfig ) ; customComparators = new RawComparator < ? > [ maxDepth + 1 ] ; for ( int i = minDepth ; i <= maxDepth ; i ++ ) { SortElement element = tupleMRConfig . getCommonCriteria ( ) . getElements ( ) . get ( i ) ; if ( element . getCustomComparator ( ) != null ) { customComparators [ i ] = element . getCustomComparator ( ) ; } } }
Initialize the custom comparators . Creates a quick access array for the custom comparators .
22,612
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public Record toRecord ( ITuple tuple , Record reuse ) throws IOException { Record record = reuse ; if ( record == null ) { record = new Record ( avroSchema ) ; } if ( schemaValidation && ! tuple . getSchema ( ) . equals ( pangoolSchema ) ) { throw new IOException ( "Tuple '" + tuple + "' " + "contains schema not expected." + "Expected schema '" + pangoolSchema + " and actual: " + tuple . getSchema ( ) ) ; } for ( int i = 0 ; i < pangoolSchema . getFields ( ) . size ( ) ; i ++ ) { Object obj = tuple . get ( i ) ; Field field = pangoolSchema . getField ( i ) ; if ( obj == null ) { throw new IOException ( "Field '" + field . getName ( ) + "' can't be null in tuple:" + tuple ) ; } switch ( field . getType ( ) ) { case INT : case LONG : case FLOAT : case BOOLEAN : case DOUBLE : case BYTES : record . put ( i , obj ) ; break ; case OBJECT : Serializer customSer = customSerializers [ i ] ; DataOutputBuffer buffer = buffers [ i ] ; buffer . reset ( ) ; if ( customSer != null ) { customSer . open ( buffer ) ; customSer . serialize ( obj ) ; customSer . close ( ) ; } else { hadoopSer . ser ( obj , buffer ) ; } ByteBuffer byteBuffer = ByteBuffer . wrap ( buffer . getData ( ) , 0 , buffer . getLength ( ) ) ; record . put ( i , byteBuffer ) ; break ; case ENUM : record . put ( i , obj . toString ( ) ) ; break ; case STRING : record . put ( i , new Utf8 ( obj . toString ( ) ) ) ; break ; default : throw new IOException ( "Not correspondence to Avro type from Pangool type " + field . getType ( ) ) ; } } return record ; }
Moves data between a Tuple and an Avro Record
22,613
public Properties appendToDefaultProperties ( File configFile ) { if ( defaultProperties != null && configFile . canRead ( ) ) { defaultProperties = appendProperties ( defaultProperties , configFile ) ; } return defaultProperties ; }
Adds properties from file to the default properties if the file exists .
22,614
public Properties appendProperties ( Properties properties , File configFile ) { if ( ! configFile . exists ( ) ) { return properties ; } return reader . appendProperties ( properties , configFile , log ) ; }
Add new properties to an existing Properties object
22,615
public Properties getSystemProperties ( ) { Properties properties = new Properties ( ) ; properties . putAll ( System . getenv ( ) ) ; properties . putAll ( System . getProperties ( ) ) ; return properties ; }
Read in The system properties
22,616
public Properties getPropertiesByContext ( ServletContext context , String path ) { return reader . getProperties ( context , path , log ) ; }
Read in properties based on a ServletContext and a path to a config file
22,617
public synchronized void persistProperties ( Properties properties , File propsFile , String message ) { Properties toWrite = new Properties ( ) ; for ( String key : properties . stringPropertyNames ( ) ) { if ( System . getProperties ( ) . containsKey ( key ) && ! properties . getProperty ( key ) . equals ( System . getProperty ( key ) ) ) { toWrite . setProperty ( key , properties . getProperty ( key ) ) ; } else if ( System . getenv ( ) . containsKey ( key ) && ! properties . getProperty ( key ) . equals ( System . getenv ( key ) ) ) { toWrite . setProperty ( key , properties . getProperty ( key ) ) ; } else if ( ! System . getProperties ( ) . containsKey ( key ) && ! System . getenv ( ) . containsKey ( key ) ) { toWrite . setProperty ( key , properties . getProperty ( key ) ) ; } } writer . persistProperties ( toWrite , propsFile , message , log ) ; }
Persist properties that are not system env or other system properties in a thread synchronized manner
22,618
public void makeConfigParserLive ( ) { if ( stagedConfigParser != null ) { notifyListeners ( listeners , stagedConfigParser , log ) ; liveConfigParser = stagedConfigParser ; latch . countDown ( ) ; } }
This notifies all registered listeners then make a staged configuration live .
22,619
private static Class < ? > [ ] getListenerGenericTypes ( Class < ? > listenerClass , Logger log ) { List < Class < ? > > configClasses = new ArrayList < Class < ? > > ( ) ; Type [ ] typeVars = listenerClass . getGenericInterfaces ( ) ; if ( typeVars != null ) { for ( Type interfaceClass : typeVars ) { if ( interfaceClass instanceof ParameterizedType ) { if ( ( ( ParameterizedType ) interfaceClass ) . getRawType ( ) instanceof Class ) { if ( ConfigurationListener . class . isAssignableFrom ( ( Class < ? > ) ( ( ParameterizedType ) interfaceClass ) . getRawType ( ) ) ) { ParameterizedType pType = ( ParameterizedType ) interfaceClass ; Type [ ] typeArgs = pType . getActualTypeArguments ( ) ; if ( typeArgs != null && typeArgs . length == 1 && typeArgs [ 0 ] instanceof Class ) { Class < ? > type = ( Class < ? > ) typeArgs [ 0 ] ; if ( type . isAnnotationPresent ( CadmiumConfig . class ) ) { log . debug ( "Adding " + type + " to the configuration types interesting to " + listenerClass ) ; configClasses . add ( type ) ; } } } } } } } return configClasses . toArray ( new Class < ? > [ ] { } ) ; }
Gets a list of classes that the listenerClass is interesting in listening to .
22,620
protected void doSanityCheck ( ) throws EXIException { if ( fidelityOptions . isFidelityEnabled ( FidelityOptions . FEATURE_SC ) && ( codingMode == CodingMode . COMPRESSION || codingMode == CodingMode . PRE_COMPRESSION ) ) { throw new EXIException ( "(Pre-)Compression and selfContained elements cannot work together" ) ; } if ( ! this . grammar . isSchemaInformed ( ) ) { this . maximumNumberOfBuiltInElementGrammars = - 1 ; this . maximumNumberOfBuiltInProductions = - 1 ; this . grammarLearningDisabled = false ; } if ( this . getEncodingOptions ( ) . isOptionEnabled ( EncodingOptions . CANONICAL_EXI ) ) { updateFactoryAccordingCanonicalEXI ( ) ; } }
some consistency and sanity checks
22,621
static public int zipDirectory ( final Configuration conf , final ZipOutputStream zos , final String baseName , final String root , final Path itemToZip ) throws IOException { LOG . info ( String . format ( "zipDirectory: %s %s %s" , baseName , root , itemToZip ) ) ; LocalFileSystem localFs = FileSystem . getLocal ( conf ) ; int count = 0 ; final FileStatus itemStatus = localFs . getFileStatus ( itemToZip ) ; if ( itemStatus . isDir ( ) ) { final FileStatus [ ] statai = localFs . listStatus ( itemToZip ) ; final String zipDirName = relativePathForZipEntry ( itemToZip . toUri ( ) . getPath ( ) , baseName , root ) ; final ZipEntry dirZipEntry = new ZipEntry ( zipDirName + Path . SEPARATOR_CHAR ) ; LOG . info ( String . format ( "Adding directory %s to zip" , zipDirName ) ) ; zos . putNextEntry ( dirZipEntry ) ; zos . closeEntry ( ) ; count ++ ; if ( statai == null || statai . length == 0 ) { LOG . info ( String . format ( "Skipping empty directory %s" , itemToZip ) ) ; return count ; } for ( FileStatus status : statai ) { count += zipDirectory ( conf , zos , baseName , root , status . getPath ( ) ) ; } LOG . info ( String . format ( "Wrote %d entries for directory %s" , count , itemToZip ) ) ; return count ; } final String inZipPath = relativePathForZipEntry ( itemToZip . toUri ( ) . getPath ( ) , baseName , root ) ; if ( inZipPath . length ( ) == 0 ) { LOG . warn ( String . format ( "Skipping empty zip file path for %s (%s %s)" , itemToZip , root , baseName ) ) ; return 0 ; } FSDataInputStream in = null ; try { in = localFs . open ( itemToZip ) ; final ZipEntry ze = new ZipEntry ( inZipPath ) ; ze . setTime ( itemStatus . getModificationTime ( ) ) ; zos . putNextEntry ( ze ) ; IOUtils . copyBytes ( in , zos , conf , false ) ; zos . closeEntry ( ) ; LOG . info ( String . format ( "Wrote %d entries for file %s" , count , itemToZip ) ) ; return 1 ; } finally { in . close ( ) ; } }
Write a file to a zip output stream removing leading path name components from the actual file name when creating the zip file entry .
22,622
public static void addListener ( Document doc , Element root ) { Element listener = doc . createElement ( "listener" ) ; Element listenerClass = doc . createElement ( "listener-class" ) ; listener . appendChild ( listenerClass ) ; listenerClass . appendChild ( doc . createTextNode ( "org.apache.shiro.web.env.EnvironmentLoaderListener" ) ) ; addRelativeTo ( root , listener , "listener" , true ) ; }
Adds a shiro environment listener to load the shiro config file .
22,623
public static void addContextParam ( Document doc , Element root ) { Element ctxParam = doc . createElement ( "context-param" ) ; Element paramName = doc . createElement ( "param-name" ) ; paramName . appendChild ( doc . createTextNode ( "shiroConfigLocations" ) ) ; ctxParam . appendChild ( paramName ) ; Element paramValue = doc . createElement ( "param-value" ) ; paramValue . appendChild ( doc . createTextNode ( "file:" + new File ( System . getProperty ( "com.meltmedia.cadmium.contentRoot" ) , "shiro.ini" ) . getAbsoluteFile ( ) . getAbsolutePath ( ) ) ) ; ctxParam . appendChild ( paramValue ) ; addRelativeTo ( root , ctxParam , "listener" , false ) ; }
Adds a context parameter to a web . xml file to override where the shiro config location is to be loaded from . The location loaded from will be represented by the com . meltmedia . cadmium . contentRoot system property .
22,624
public static void addEnvContextParam ( Document doc , Element root ) { Element ctxParam = doc . createElement ( "context-param" ) ; Element paramName = doc . createElement ( "param-name" ) ; paramName . appendChild ( doc . createTextNode ( "shiroEnvironmentClass" ) ) ; ctxParam . appendChild ( paramName ) ; Element paramValue = doc . createElement ( "param-value" ) ; paramValue . appendChild ( doc . createTextNode ( "com.meltmedia.cadmium.servlets.shiro.WebEnvironment" ) ) ; ctxParam . appendChild ( paramValue ) ; addRelativeTo ( root , ctxParam , "listener" , false ) ; }
Adds a context parameter to a web . xml file to override where the shiro environment class .
22,625
public static void addFilter ( Document doc , Element root ) { Element filter = doc . createElement ( "filter" ) ; Element filterName = doc . createElement ( "filter-name" ) ; filterName . appendChild ( doc . createTextNode ( "ShiroFilter" ) ) ; filter . appendChild ( filterName ) ; Element filterClass = doc . createElement ( "filter-class" ) ; filterClass . appendChild ( doc . createTextNode ( "org.apache.shiro.web.servlet.ShiroFilter" ) ) ; filter . appendChild ( filterClass ) ; addRelativeTo ( root , filter , "filter" , true ) ; }
Adds the shiro filter to a web . xml file .
22,626
public static void addFilterMapping ( Document doc , Element root ) { Element filterMapping = doc . createElement ( "filter-mapping" ) ; Element filterName = doc . createElement ( "filter-name" ) ; filterName . appendChild ( doc . createTextNode ( "ShiroFilter" ) ) ; filterMapping . appendChild ( filterName ) ; Element urlPattern = doc . createElement ( "url-pattern" ) ; urlPattern . appendChild ( doc . createTextNode ( "/*" ) ) ; filterMapping . appendChild ( urlPattern ) ; addDispatchers ( doc , filterMapping , "REQUEST" , "FORWARD" , "INCLUDE" , "ERROR" ) ; addRelativeTo ( root , filterMapping , "filter-mapping" , true ) ; }
Adds the filter mapping for the shiro filter to a web . xml file .
22,627
public static void addDispatchers ( Document doc , Element filterMapping , String ... names ) { if ( names != null ) { for ( String name : names ) { Element dispatcher = doc . createElement ( "dispatcher" ) ; dispatcher . appendChild ( doc . createTextNode ( name ) ) ; filterMapping . appendChild ( dispatcher ) ; } } }
Adds dispatchers for each item in the vargs parameter names to a filter mapping element of a web . xml file .
22,628
public static void storeXmlDocument ( ZipOutputStream outZip , ZipEntry jbossWeb , Document doc ) throws IOException , TransformerFactoryConfigurationError , TransformerConfigurationException , TransformerException { jbossWeb = new ZipEntry ( jbossWeb . getName ( ) ) ; outZip . putNextEntry ( jbossWeb ) ; TransformerFactory tFactory = TransformerFactory . newInstance ( ) ; Transformer transformer = tFactory . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , "2" ) ; DOMSource source = new DOMSource ( doc ) ; StreamResult result = new StreamResult ( outZip ) ; transformer . transform ( source , result ) ; outZip . closeEntry ( ) ; }
Writes a xml document to a zip file with an entry specified by the jbossWeb parameter .
22,629
public static void removeNodesByTagName ( Element doc , String tagname ) { NodeList nodes = doc . getElementsByTagName ( tagname ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { Node n = nodes . item ( i ) ; doc . removeChild ( n ) ; } }
Removes elements by a specified tag name from the xml Element passed in .
22,630
public static void storeProperties ( ZipOutputStream outZip , ZipEntry cadmiumPropertiesEntry , Properties cadmiumProps , List < String > newWarNames ) throws IOException { ZipEntry newCadmiumEntry = new ZipEntry ( cadmiumPropertiesEntry . getName ( ) ) ; outZip . putNextEntry ( newCadmiumEntry ) ; cadmiumProps . store ( outZip , "Initial git properties for " + newWarNames . get ( 0 ) ) ; outZip . closeEntry ( ) ; }
Adds a properties file to a war .
22,631
public static String getWarName ( ServletContext context ) { String [ ] pathSegments = context . getRealPath ( "/WEB-INF/web.xml" ) . split ( "/" ) ; String warName = pathSegments [ pathSegments . length - 3 ] ; if ( ! warName . endsWith ( ".war" ) ) { URL webXml = WarUtils . class . getClassLoader ( ) . getResource ( "/cadmium-version.properties" ) ; if ( webXml != null ) { String urlString = webXml . toString ( ) . substring ( 0 , webXml . toString ( ) . length ( ) - "/WEB-INF/classes/cadmium-version.properties" . length ( ) ) ; File warFile = null ; if ( webXml . getProtocol ( ) . equalsIgnoreCase ( "file" ) ) { warFile = new File ( urlString . substring ( 5 ) ) ; } else if ( webXml . getProtocol ( ) . equalsIgnoreCase ( "vfszip" ) ) { warFile = new File ( urlString . substring ( 7 ) ) ; } else if ( webXml . getProtocol ( ) . equalsIgnoreCase ( "vfsfile" ) ) { warFile = new File ( urlString . substring ( 8 ) ) ; } else if ( webXml . getProtocol ( ) . equalsIgnoreCase ( "vfs" ) && System . getProperty ( JBOSS_7_DEPLOY_DIR ) != null ) { String path = urlString . substring ( "vfs:/" . length ( ) ) ; String deployDir = System . getProperty ( JBOSS_7_DEPLOY_DIR ) ; warFile = new File ( deployDir , path ) ; } if ( warFile != null ) { warName = warFile . getName ( ) ; } } } return warName ; }
Gets the currently deployed war file name from the ServletContext .
22,632
public final int decodeUnsignedInteger ( ) throws IOException { int result = decode ( ) ; if ( result >= 128 ) { result = ( result & 127 ) ; int mShift = 7 ; int b ; do { b = decode ( ) ; result += ( b & 127 ) << mShift ; mShift += 7 ; } while ( b >= 128 ) ; } return result ; }
Decode an arbitrary precision non negative integer using a sequence of octets . The most significant bit of the last octet is set to zero to indicate sequence termination . Only seven bits per octet are used to store the integer s value .
22,633
public DateTimeValue decodeDateTimeValue ( DateTimeType type ) throws IOException { int year = 0 , monthDay = 0 , time = 0 , fractionalSecs = 0 ; switch ( type ) { case gYear : year = decodeInteger ( ) + DateTimeValue . YEAR_OFFSET ; break ; case gYearMonth : case date : year = decodeInteger ( ) + DateTimeValue . YEAR_OFFSET ; monthDay = decodeNBitUnsignedInteger ( DateTimeValue . NUMBER_BITS_MONTHDAY ) ; break ; case dateTime : year = decodeInteger ( ) + DateTimeValue . YEAR_OFFSET ; monthDay = decodeNBitUnsignedInteger ( DateTimeValue . NUMBER_BITS_MONTHDAY ) ; case time : time = decodeNBitUnsignedInteger ( DateTimeValue . NUMBER_BITS_TIME ) ; boolean presenceFractionalSecs = decodeBoolean ( ) ; fractionalSecs = presenceFractionalSecs ? decodeUnsignedInteger ( ) : 0 ; break ; case gMonth : case gMonthDay : case gDay : monthDay = decodeNBitUnsignedInteger ( DateTimeValue . NUMBER_BITS_MONTHDAY ) ; break ; default : throw new UnsupportedOperationException ( ) ; } boolean presenceTimezone = decodeBoolean ( ) ; int timeZone = presenceTimezone ? decodeNBitUnsignedInteger ( DateTimeValue . NUMBER_BITS_TIMEZONE ) - DateTimeValue . TIMEZONE_OFFSET_IN_MINUTES : 0 ; return new DateTimeValue ( type , year , monthDay , time , fractionalSecs , presenceTimezone , timeZone ) ; }
Decode Date - Time as sequence of values representing the individual components of the Date - Time .
22,634
public Set < String > configureJob ( Job job ) throws FileNotFoundException , IOException { Set < String > instanceFiles = new HashSet < String > ( ) ; for ( Map . Entry < Path , List < Input > > entry : multiInputs . entrySet ( ) ) { for ( int inputId = 0 ; inputId < entry . getValue ( ) . size ( ) ; inputId ++ ) { Input input = entry . getValue ( ) . get ( inputId ) ; instanceFiles . addAll ( PangoolMultipleInputs . addInputPath ( job , input . path , input . inputFormat , input . inputProcessor , input . specificContext , inputId ) ) ; } } return instanceFiles ; }
Use this method for configuring a Job instance according to the multiple input specs that has been specified . Returns the instance files created .
22,635
public static void waitForToken ( String siteUri , String token , Long since , Long timeout ) throws Exception { if ( ! siteUri . endsWith ( "/system/history" ) ) { siteUri += "/system/history" ; } siteUri += "/" + token ; if ( since != null ) { siteUri += "/" + since ; } HttpClient httpClient = httpClient ( ) ; HttpGet get = new HttpGet ( siteUri ) ; Long currentTime = System . currentTimeMillis ( ) ; Long timeoutTime = currentTime + timeout ; do { currentTime = System . currentTimeMillis ( ) ; HttpResponse resp = httpClient . execute ( get ) ; if ( resp . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { String response = EntityUtils . toString ( resp . getEntity ( ) ) ; if ( response != null && response . trim ( ) . equalsIgnoreCase ( "true" ) ) { return ; } else { Thread . sleep ( 1000l ) ; } } else { String errorResponse = EntityUtils . toString ( resp . getEntity ( ) ) ; if ( errorResponse != null ) { throw new Exception ( errorResponse . trim ( ) ) ; } else { throw new Exception ( "Command failed!" ) ; } } } while ( currentTime < timeoutTime ) ; if ( currentTime >= timeoutTime ) { throw new Exception ( "Timed out waiting for command to complete!" ) ; } }
Waits until a timeout is reached or a token shows up in the history of a site as finished or failed .
22,636
public static List < HistoryEntry > getHistory ( String siteUri , int limit , boolean filter , String token ) throws URISyntaxException , IOException , ClientProtocolException , Exception { if ( ! siteUri . endsWith ( "/system/history" ) ) { siteUri += "/system/history" ; } List < HistoryEntry > history = null ; HttpClient httpClient = httpClient ( ) ; HttpGet get = null ; try { URIBuilder uriBuilder = new URIBuilder ( siteUri ) ; if ( limit > 0 ) { uriBuilder . addParameter ( "limit" , limit + "" ) ; } if ( filter ) { uriBuilder . addParameter ( "filter" , filter + "" ) ; } URI uri = uriBuilder . build ( ) ; get = new HttpGet ( uri ) ; addAuthHeader ( token , get ) ; HttpResponse resp = httpClient . execute ( get ) ; if ( resp . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { HttpEntity entity = resp . getEntity ( ) ; if ( entity . getContentType ( ) . getValue ( ) . equals ( "application/json" ) ) { String responseContent = EntityUtils . toString ( entity ) ; Gson gson = new GsonBuilder ( ) . registerTypeAdapter ( Date . class , new JsonDeserializer < Date > ( ) { public Date deserialize ( JsonElement json , Type typeOfT , JsonDeserializationContext ctx ) throws JsonParseException { return new Date ( json . getAsLong ( ) ) ; } } ) . create ( ) ; history = gson . fromJson ( responseContent , new TypeToken < List < HistoryEntry > > ( ) { } . getType ( ) ) ; } else { System . err . println ( "Invalid response content type [" + entity . getContentType ( ) . getValue ( ) + "]" ) ; System . exit ( 1 ) ; } } else { System . err . println ( "Request failed due to a [" + resp . getStatusLine ( ) . getStatusCode ( ) + ":" + resp . getStatusLine ( ) . getReasonPhrase ( ) + "] response from the remote server." ) ; System . exit ( 1 ) ; } } finally { if ( get != null ) { get . releaseConnection ( ) ; } } return history ; }
Retrieves the history of a Cadmium site .
22,637
private static void printComments ( String comment ) { int index = 0 ; int nextIndex = 154 ; while ( index < comment . length ( ) ) { nextIndex = nextIndex <= comment . length ( ) ? nextIndex : comment . length ( ) ; String commentSegment = comment . substring ( index , nextIndex ) ; int lastSpace = commentSegment . lastIndexOf ( ' ' ) ; int lastNewLine = commentSegment . indexOf ( '\n' ) ; char lastChar = ' ' ; if ( nextIndex < comment . length ( ) ) { lastChar = comment . charAt ( nextIndex ) ; } if ( lastNewLine > 0 ) { nextIndex = index + lastNewLine ; commentSegment = comment . substring ( index , nextIndex ) ; } else if ( Character . isWhitespace ( lastChar ) ) { } else if ( lastSpace > 0 ) { nextIndex = index + lastSpace ; commentSegment = comment . substring ( index , nextIndex ) ; } System . out . println ( " " + commentSegment ) ; index = nextIndex ; if ( lastNewLine > 0 || lastSpace > 0 ) { index ++ ; } nextIndex = index + 154 ; } }
Helper method to format comments to standard out .
22,638
private static String formatTimeLive ( long timeLive ) { String timeString = "ms" ; timeString = ( timeLive % 1000 ) + timeString ; timeLive = timeLive / 1000 ; if ( timeLive > 0 ) { timeString = ( timeLive % 60 ) + "s" + timeString ; timeLive = timeLive / 60 ; if ( timeLive > 0 ) { timeString = ( timeLive % 60 ) + "m" + timeString ; timeLive = timeLive / 60 ; if ( timeLive > 0 ) { timeString = ( timeLive % 24 ) + "h" + timeString ; timeLive = timeLive / 24 ; if ( timeLive > 0 ) { timeString = ( timeLive ) + "d" + timeString ; } } } } return timeString ; }
Helper method to format a timestamp .
22,639
public boolean isSecure ( HttpServletRequest request ) { String proto = request . getHeader ( X_FORWARED_PROTO ) ; if ( proto != null ) return proto . equalsIgnoreCase ( HTTPS_PROTOCOL ) ; return super . isSecure ( request ) ; }
When the X - Forwarded - Proto header is present this method returns true if the header equals https false otherwise . When the header is not present it delegates this call to the super class .
22,640
public String getProtocol ( HttpServletRequest request ) { String proto = request . getHeader ( X_FORWARED_PROTO ) ; if ( proto != null ) return proto ; return super . getProtocol ( request ) ; }
When the X - Forwarded - Proto header is present this method returns the value of that header . When the header is not present it delegates this call to the super class .
22,641
public int getPort ( HttpServletRequest request ) { String portValue = request . getHeader ( X_FORWARED_PORT ) ; if ( portValue != null ) return Integer . parseInt ( portValue ) ; return super . getPort ( request ) ; }
When the X - Forwarded - Port header is present this method returns the value of that header . When the header is not present it delegates this call to the super class .
22,642
public String contentTypeOf ( String path ) throws IOException { File file = findFile ( path ) ; return lookupMimeType ( file . getName ( ) ) ; }
Returns the content type for the specified path .
22,643
public File findFile ( String path ) throws IOException { File base = new File ( getBasePath ( ) ) ; File pathFile = new File ( base , "." + path ) ; if ( ! pathFile . exists ( ) ) throw new FileNotFoundException ( "No file or directory at " + pathFile . getCanonicalPath ( ) ) ; if ( pathFile . isFile ( ) ) return pathFile ; pathFile = new File ( pathFile , "index.html" ) ; if ( ! pathFile . exists ( ) ) throw new FileNotFoundException ( "No welcome file at " + pathFile . getCanonicalPath ( ) ) ; return pathFile ; }
Returns the file object for the given path including welcome file lookup . If the file cannot be found a FileNotFoundException is returned .
22,644
public void setGitService ( GitService git ) { if ( git != null ) { logger . debug ( "Setting git service" ) ; this . git = git ; latch . countDown ( ) ; } }
Sets the common reference an releases any threads waiting for the reference to be set .
22,645
public void close ( ) throws IOException { if ( git != null ) { IOUtils . closeQuietly ( git ) ; git = null ; } latch . countDown ( ) ; try { latch . notifyAll ( ) ; } catch ( Exception e ) { logger . trace ( "Failed to notifyAll" ) ; } try { locker . notifyAll ( ) ; } catch ( Exception e ) { logger . trace ( "Failed to notifyAll" ) ; } }
Releases any used resources and waiting threads .
22,646
public int read ( byte [ ] b , int off , int len ) throws IOException { ensureOpen ( ) ; if ( ( off | len | ( off + len ) | ( b . length - ( off + len ) ) ) < 0 ) { throw new IndexOutOfBoundsException ( ) ; } else if ( len == 0 ) { return 0 ; } try { int n ; while ( ( n = inf . inflate ( b , off , len ) ) == 0 ) { if ( inf . finished ( ) || inf . needsDictionary ( ) ) { reachEOF = true ; return - 1 ; } if ( inf . needsInput ( ) ) { fill ( ) ; } } return n ; } catch ( DataFormatException e ) { String s = e . getMessage ( ) ; throw new ZipException ( s != null ? s : "Invalid ZLIB data format" ) ; } }
Reads uncompressed data into an array of bytes . This method will block until some input can be decompressed .
22,647
public static void writeTXT ( String string , File file ) throws IOException { BufferedWriter out = new BufferedWriter ( new FileWriter ( file ) ) ; out . write ( string ) ; out . close ( ) ; }
Writes the string into the file .
22,648
public void setOption ( String key ) throws UnsupportedOption { if ( key . equals ( IGNORE_SCHEMA_ID ) ) { options . add ( key ) ; } else { throw new UnsupportedOption ( "DecodingOption '" + key + "' is unknown!" ) ; } }
Enables given option .
22,649
public void encodeNBitUnsignedInteger ( int b , int n ) throws IOException { if ( b < 0 || n < 0 ) { throw new IllegalArgumentException ( "Negative value as unsigned integer!" ) ; } assert ( b >= 0 ) ; assert ( n >= 0 ) ; if ( n == 0 ) { } else if ( n < 9 ) { encode ( b & 0xff ) ; } else if ( n < 17 ) { encode ( b & 0x00ff ) ; encode ( ( b & 0xff00 ) >> 8 ) ; } else if ( n < 25 ) { encode ( b & 0x0000ff ) ; encode ( ( b & 0x00ff00 ) >> 8 ) ; encode ( ( b & 0xff0000 ) >> 16 ) ; } else if ( n < 33 ) { encode ( b & 0x000000ff ) ; encode ( ( b & 0x0000ff00 ) >> 8 ) ; encode ( ( b & 0x00ff0000 ) >> 16 ) ; encode ( ( b & 0xff000000 ) >> 24 ) ; } else { throw new RuntimeException ( "Currently not more than 4 Bytes allowed for NBitUnsignedInteger!" ) ; } }
Encode n - bit unsigned integer using the minimum number of bytes required to store n bits . The n least significant bits of parameter b starting with the most significant i . e . from left to right .
22,650
@ SuppressWarnings ( "rawtypes" ) public void addClass ( String name , Class mainClass , String description ) throws Throwable { programs . put ( name , new ProgramDescription ( mainClass , description ) ) ; }
This is the method that adds the classed to the repository
22,651
public void driver ( String [ ] args ) throws Throwable { if ( args . length == 0 ) { System . out . println ( "An example program must be given as the" + " first argument." ) ; printUsage ( programs ) ; throw new IllegalArgumentException ( "An example program must be given " + "as the first argument." ) ; } ProgramDescription pgm = programs . get ( args [ 0 ] ) ; if ( pgm == null ) { System . out . println ( "Unknown program '" + args [ 0 ] + "' chosen." ) ; printUsage ( programs ) ; throw new IllegalArgumentException ( "Unknown program '" + args [ 0 ] + "' chosen." ) ; } String [ ] new_args = new String [ args . length - 1 ] ; for ( int i = 1 ; i < args . length ; ++ i ) { new_args [ i - 1 ] = args [ i ] ; } pgm . invoke ( new_args ) ; }
This is a driver for the example programs . It looks at the first command line argument and tries to find an example program with that name . If it is found it calls the main method in that class with the rest of the command line arguments .
22,652
public void ser ( Object datum , OutputStream output ) throws IOException { Map < Class , Serializer > serializers = cachedSerializers . get ( ) ; Serializer ser = serializers . get ( datum . getClass ( ) ) ; if ( ser == null ) { ser = serialization . getSerializer ( datum . getClass ( ) ) ; if ( ser == null ) { throw new IOException ( "Serializer for class " + datum . getClass ( ) + " not found" ) ; } serializers . put ( datum . getClass ( ) , ser ) ; } ser . open ( output ) ; ser . serialize ( datum ) ; ser . close ( ) ; }
Serializes the given object using the Hadoop serialization system .
22,653
public < T > T deser ( Object obj , InputStream in ) throws IOException { Map < Class , Deserializer > deserializers = cachedDeserializers . get ( ) ; Deserializer deSer = deserializers . get ( obj . getClass ( ) ) ; if ( deSer == null ) { deSer = serialization . getDeserializer ( obj . getClass ( ) ) ; deserializers . put ( obj . getClass ( ) , deSer ) ; } deSer . open ( in ) ; obj = deSer . deserialize ( obj ) ; deSer . close ( ) ; return ( T ) obj ; }
Deseerializes into the given object using the Hadoop serialization system . Object cannot be null .
22,654
public < T > T deser ( Object obj , byte [ ] array , int offset , int length ) throws IOException { Map < Class , Deserializer > deserializers = cachedDeserializers . get ( ) ; Deserializer deSer = deserializers . get ( obj . getClass ( ) ) ; if ( deSer == null ) { deSer = serialization . getDeserializer ( obj . getClass ( ) ) ; deserializers . put ( obj . getClass ( ) , deSer ) ; } DataInputBuffer baIs = cachedInputStream . get ( ) ; baIs . reset ( array , offset , length ) ; deSer . open ( baIs ) ; obj = deSer . deserialize ( obj ) ; deSer . close ( ) ; baIs . close ( ) ; return ( T ) obj ; }
Deserialize an object using Hadoop serialization from a byte array . The object cannot be null .
22,655
public static void copyPartialContent ( InputStream in , OutputStream out , Range r ) throws IOException { IOUtils . copyLarge ( in , out , r . start , r . length ) ; }
Copies the given range of bytes from the input stream to the output stream .
22,656
public static Long calculateRangeLength ( FileRequestContext context , Range range ) { if ( range . start == - 1 ) range . start = 0 ; if ( range . end == - 1 ) range . end = context . file . length ( ) - 1 ; range . length = range . end - range . start + 1 ; return range . length ; }
Calculates the length of a given range .
22,657
protected boolean checkAccepts ( FileRequestContext context ) throws IOException { if ( ! canAccept ( context . request . getHeader ( ACCEPT_HEADER ) , false , context . contentType ) ) { notAcceptable ( context ) ; return true ; } if ( ! ( canAccept ( context . request . getHeader ( ACCEPT_ENCODING_HEADER ) , false , "identity" ) || canAccept ( context . request . getHeader ( ACCEPT_ENCODING_HEADER ) , false , "gzip" ) ) ) { notAcceptable ( context ) ; return true ; } if ( context . request . getHeader ( ACCEPT_ENCODING_HEADER ) != null && canAccept ( context . request . getHeader ( ACCEPT_ENCODING_HEADER ) , true , "gzip" ) && shouldGzip ( context . contentType ) ) { context . compress = true ; } return false ; }
Checks the accepts headers and makes sure that we can fulfill the request .
22,658
public boolean locateFileToServe ( FileRequestContext context ) throws IOException { context . file = new File ( contentDir , context . path ) ; if ( ! context . file . exists ( ) ) { context . response . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return true ; } if ( handleWelcomeRedirect ( context ) ) return true ; if ( context . file . isDirectory ( ) ) { context . file = new File ( context . file , "index.html" ) ; } if ( ! context . file . exists ( ) ) { context . response . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return true ; } return false ; }
Locates the file to serve . Returns true if locating the file caused the request to be handled .
22,659
public static void invalidRanges ( FileRequestContext context ) throws IOException { context . response . setHeader ( CONTENT_RANGE_HEADER , "*/" + context . file . length ( ) ) ; context . response . sendError ( HttpServletResponse . SC_REQUESTED_RANGE_NOT_SATISFIABLE ) ; }
Sets the appropriate response headers and error status for bad ranges
22,660
public static boolean canAccept ( String headerValue , boolean strict , String type ) { if ( headerValue != null && type != null ) { String availableTypes [ ] = headerValue . split ( "," ) ; for ( String availableType : availableTypes ) { String typeParams [ ] = availableType . split ( ";" ) ; double qValue = 1.0d ; if ( typeParams . length > 0 ) { for ( int i = 1 ; i < typeParams . length ; i ++ ) { if ( typeParams [ i ] . trim ( ) . startsWith ( "q=" ) ) { String qString = typeParams [ i ] . substring ( 2 ) . trim ( ) ; if ( qString . matches ( "\\A\\d+(\\.\\d*){0,1}\\Z" ) ) { qValue = Double . parseDouble ( qString ) ; break ; } } } } boolean matches = false ; if ( typeParams [ 0 ] . equals ( "*" ) || typeParams [ 0 ] . equals ( "*/*" ) ) { matches = true ; } else { matches = hasMatch ( typeParams , type ) ; } if ( qValue == 0 && matches ) { return false ; } else if ( matches ) { return true ; } } } return ! strict ; }
Parses an Accept header value and checks to see if the type is acceptable .
22,661
private static boolean hasMatch ( String [ ] typeParams , String ... type ) { boolean matches = false ; for ( String t : type ) { for ( String typeParam : typeParams ) { if ( typeParam . contains ( "/" ) ) { String typePart = typeParam . replace ( "*" , "" ) ; if ( t . startsWith ( typePart ) || t . endsWith ( typePart ) ) { matches = true ; break ; } } else if ( t . equals ( typeParam ) ) { matches = true ; break ; } } if ( matches ) { break ; } } return matches ; }
Check to see if a Accept header accept part matches any of the given types .
22,662
public boolean handleWelcomeRedirect ( FileRequestContext context ) throws IOException { if ( context . file . isFile ( ) && context . file . getName ( ) . equals ( "index.html" ) ) { resolveContentType ( context ) ; String location = context . path . replaceFirst ( "/index.html\\Z" , "" ) ; if ( location . isEmpty ( ) ) location = "/" ; if ( context . request . getQueryString ( ) != null ) location = location + "?" + context . request . getQueryString ( ) ; sendPermanentRedirect ( context , location ) ; return true ; } return false ; }
Forces requests for index files to not use the file name .
22,663
public void resolveContentType ( FileRequestContext context ) { String contentType = lookupMimeType ( context . file . getName ( ) ) ; if ( contentType != null ) { context . contentType = contentType ; if ( contentType . equals ( "text/html" ) ) { context . contentType += ";charset=UTF-8" ; } } }
Looks up the mime type based on file extension and if found sets it on the FileRequestContext .
22,664
protected void flushBuffer ( ) throws IOException { if ( capacity == 0 ) { ostream . write ( buffer ) ; capacity = BITS_IN_BYTE ; buffer = 0 ; len ++ ; } }
If buffer is full write it out and reset internal state .
22,665
public void align ( ) throws IOException { if ( capacity < BITS_IN_BYTE ) { ostream . write ( buffer << capacity ) ; capacity = BITS_IN_BYTE ; buffer = 0 ; len ++ ; } }
If there are some unwritten bits pad them if necessary and write them out .
22,666
public void writeBits ( int b , int n ) throws IOException { if ( n <= capacity ) { buffer = ( buffer << n ) | ( b & ( 0xff >> ( BITS_IN_BYTE - n ) ) ) ; capacity -= n ; if ( capacity == 0 ) { ostream . write ( buffer ) ; capacity = BITS_IN_BYTE ; len ++ ; } } else { buffer = ( buffer << capacity ) | ( ( b >>> ( n - capacity ) ) & ( 0xff >> ( BITS_IN_BYTE - capacity ) ) ) ; n -= capacity ; ostream . write ( buffer ) ; len ++ ; while ( n >= 8 ) { n -= 8 ; ostream . write ( b >>> n ) ; len ++ ; } buffer = b ; capacity = BITS_IN_BYTE - n ; } }
Write the n least significant bits of parameter b starting with the most significant i . e . from left to right .
22,667
protected void writeDirectBytes ( byte [ ] b , int off , int len ) throws IOException { ostream . write ( b , off , len ) ; len += len ; }
Ignore current buffer and write a sequence of bytes directly to the underlying stream .
22,668
private static String adaptNumber ( String number ) { String n = number . trim ( ) ; if ( n . startsWith ( "+" ) ) { return n . substring ( 1 ) ; } else { return n ; } }
Adapt a number for being able to be parsed by Integer and Long
22,669
private void persistRealmChanges ( ) { configManager . persistProperties ( realm . getProperties ( ) , new File ( applicationContentDir , PersistablePropertiesRealm . REALM_FILE_NAME ) , null ) ; }
Persists the user accounts to a properties file that is only available to this site only .
22,670
public static void stringToFile ( FileSystem fs , Path path , String string ) throws IOException { OutputStream os = fs . create ( path , true ) ; PrintWriter pw = new PrintWriter ( os ) ; pw . append ( string ) ; pw . close ( ) ; }
Creates a file with the given string overwritting if needed .
22,671
public static String fileToString ( FileSystem fs , Path path ) throws IOException { if ( ! fs . exists ( path ) ) { return null ; } InputStream is = fs . open ( path ) ; InputStreamReader isr = new InputStreamReader ( is ) ; BufferedReader br = new BufferedReader ( isr ) ; char [ ] buff = new char [ 256 ] ; StringBuilder sb = new StringBuilder ( ) ; int read ; while ( ( read = br . read ( buff ) ) != - 1 ) { sb . append ( buff , 0 , read ) ; } br . close ( ) ; return sb . toString ( ) ; }
Reads the content of a file into a String . Return null if the file does not exist .
22,672
public static HashMap < Integer , Integer > readIntIntMap ( Path path , FileSystem fs ) throws IOException { SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , fs . getConf ( ) ) ; IntWritable topic = new IntWritable ( ) ; IntWritable value = new IntWritable ( ) ; HashMap < Integer , Integer > ret = new HashMap < Integer , Integer > ( ) ; while ( reader . next ( topic ) ) { reader . getCurrentValue ( value ) ; ret . put ( topic . get ( ) , value . get ( ) ) ; } reader . close ( ) ; return ret ; }
Reads maps of integer - > integer
22,673
static Scenario scenario ( String text ) { reset ( ) ; final Scenario scenario = new Scenario ( text ) ; sRoot = scenario ; return scenario ; }
Describes the scenario of the use case .
22,674
static Given given ( String text ) { reset ( ) ; final Given given = new Given ( text ) ; sRoot = given ; return given ; }
Describes the entry point of the use case .
22,675
public static void insertMessage ( Throwable onObject , String msg ) { try { Field field = Throwable . class . getDeclaredField ( "detailMessage" ) ; field . setAccessible ( true ) ; if ( onObject . getMessage ( ) != null ) { field . set ( onObject , "\n[\n" + msg + "\n]\n[\nMessage: " + onObject . getMessage ( ) + "\n]" ) ; } else { field . set ( onObject , "\n[\n" + msg + "]\n" ) ; } } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { } }
Addes a message at the beginning of the stacktrace .
22,676
public Stylesheet parse ( ) throws ParseException { while ( tokenizer . more ( ) ) { if ( tokenizer . current ( ) . isKeyword ( KEYWORD_IMPORT ) ) { parseImport ( ) ; } else if ( tokenizer . current ( ) . isKeyword ( KEYWORD_MIXIN ) ) { Mixin mixin = parseMixin ( ) ; if ( mixin . getName ( ) != null ) { result . addMixin ( mixin ) ; } } else if ( tokenizer . current ( ) . isKeyword ( KEYWORD_MEDIA ) ) { result . addSection ( parseSection ( true ) ) ; } else if ( tokenizer . current ( ) . isSpecialIdentifier ( "$" ) && tokenizer . next ( ) . isSymbol ( ":" ) ) { parseVariableDeclaration ( ) ; } else { result . addSection ( parseSection ( false ) ) ; } } if ( ! tokenizer . getProblemCollector ( ) . isEmpty ( ) ) { throw ParseException . create ( tokenizer . getProblemCollector ( ) ) ; } return result ; }
Parses the given input returning the parsed stylesheet .
22,677
private Section parseSection ( boolean mediaQuery ) { Section section = new Section ( ) ; parseSectionSelector ( mediaQuery , section ) ; tokenizer . consumeExpectedSymbol ( "{" ) ; while ( tokenizer . more ( ) ) { if ( tokenizer . current ( ) . isSymbol ( "}" ) ) { tokenizer . consumeExpectedSymbol ( "}" ) ; return section ; } if ( isAtAttribute ( ) ) { Attribute attr = parseAttribute ( ) ; section . addAttribute ( attr ) ; } else if ( tokenizer . current ( ) . isKeyword ( KEYWORD_MEDIA ) ) { section . addSubSection ( parseSection ( true ) ) ; } else if ( tokenizer . current ( ) . isKeyword ( KEYWORD_INCLUDE ) ) { parseInclude ( section ) ; } else if ( tokenizer . current ( ) . isKeyword ( KEYWORD_EXTEND ) ) { parseExtend ( section ) ; } else { section . addSubSection ( parseSection ( false ) ) ; } } tokenizer . consumeExpectedSymbol ( "}" ) ; return section ; }
Parses a section which is either a media query or a css selector along with a set of attributes .
22,678
private Object [ ] getValues ( Map < String , Object > annotationAtts ) { if ( null == annotationAtts ) { throw new DuraCloudRuntimeException ( "Arg annotationAtts is null." ) ; } List < Object > values = new ArrayList < Object > ( ) ; for ( String key : annotationAtts . keySet ( ) ) { Object [ ] objects = ( Object [ ] ) annotationAtts . get ( key ) ; for ( Object obj : objects ) { values . add ( obj ) ; } } return values . toArray ( ) ; }
This method extracts the annotation argument info from the annotation metadata . Since the implementation of access for annotation arguments varies this method may need to be overwritten by additional AnnotationParsers .
22,679
private Set < Role > getOtherRolesArg ( Object [ ] arguments ) { if ( arguments . length <= NEW_ROLES_INDEX ) { log . error ( "Illegal number of args: " + arguments . length ) ; } Set < Role > roles = new HashSet < Role > ( ) ; Object [ ] rolesArray = ( Object [ ] ) arguments [ NEW_ROLES_INDEX ] ; if ( null != rolesArray && rolesArray . length > 0 ) { for ( Object role : rolesArray ) { roles . add ( ( Role ) role ) ; } } return roles ; }
This method returns roles argument of in the target method invocation .
22,680
private Long getOtherUserIdArg ( Object [ ] arguments ) { if ( arguments . length <= OTHER_USER_ID_INDEX ) { log . error ( "Illegal number of args: " + arguments . length ) ; } return ( Long ) arguments [ OTHER_USER_ID_INDEX ] ; }
This method returns peer userId argument of the target method invocation .
22,681
private Long getUserIdArg ( Object [ ] arguments ) { if ( arguments . length <= USER_ID_INDEX ) { log . error ( "Illegal number of args: " + arguments . length ) ; } return ( Long ) arguments [ USER_ID_INDEX ] ; }
This method returns userId argument of the target method invocation .
22,682
private Long getAccountIdArg ( Object [ ] arguments ) { if ( arguments . length <= ACCT_ID_INDEX ) { log . error ( "Illegal number of args: " + arguments . length ) ; } return ( Long ) arguments [ ACCT_ID_INDEX ] ; }
This method returns acctId argument of the target method invocation .
22,683
public static Expression rgb ( Generator generator , FunctionCall input ) { return new Color ( input . getExpectedIntParam ( 0 ) , input . getExpectedIntParam ( 1 ) , input . getExpectedIntParam ( 2 ) ) ; }
Creates a color from given RGB values .
22,684
public static Expression rgba ( Generator generator , FunctionCall input ) { if ( input . getParameters ( ) . size ( ) == 4 ) { return new Color ( input . getExpectedIntParam ( 0 ) , input . getExpectedIntParam ( 1 ) , input . getExpectedIntParam ( 2 ) , input . getExpectedFloatParam ( 3 ) ) ; } if ( input . getParameters ( ) . size ( ) == 2 ) { Color color = input . getExpectedColorParam ( 0 ) ; float newA = input . getExpectedFloatParam ( 1 ) ; return new Color ( color . getR ( ) , color . getG ( ) , color . getB ( ) , newA ) ; } throw new IllegalArgumentException ( "rgba must be called with either 2 or 4 parameters. Function call: " + input ) ; }
Creates a color from given RGB and alpha values .
22,685
public static Expression adjusthue ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; int changeInDegrees = input . getExpectedIntParam ( 1 ) ; Color . HSL hsl = color . getHSL ( ) ; hsl . setH ( hsl . getH ( ) + changeInDegrees ) ; return hsl . getColor ( ) ; }
Adjusts the hue of the given color by the given number of degrees .
22,686
public static Expression lighten ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; int increase = input . getExpectedIntParam ( 1 ) ; return changeLighteness ( color , increase ) ; }
Increases the lightness of the given color by N percent .
22,687
public static Expression alpha ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; return new Number ( color . getA ( ) , String . valueOf ( color . getA ( ) ) , "" ) ; }
Returns the alpha value of the given color
22,688
public static Expression darken ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; int decrease = input . getExpectedIntParam ( 1 ) ; return changeLighteness ( color , - decrease ) ; }
Decreases the lightness of the given color by N percent .
22,689
public static Expression saturate ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; int increase = input . getExpectedIntParam ( 1 ) ; return changeSaturation ( color , increase ) ; }
Increases the saturation of the given color by N percent .
22,690
public static Expression desaturate ( Generator generator , FunctionCall input ) { Color color = input . getExpectedColorParam ( 0 ) ; int decrease = input . getExpectedIntParam ( 1 ) ; return changeSaturation ( color , - decrease ) ; }
Decreases the saturation of the given color by N percent .
22,691
@ SuppressWarnings ( "squid:S00100" ) public static Expression fade_out ( Generator generator , FunctionCall input ) { return opacify ( generator , input ) ; }
Decreases the opacity of the given color by the given amount .
22,692
public static Expression mix ( Generator generator , FunctionCall input ) { Color color1 = input . getExpectedColorParam ( 0 ) ; Color color2 = input . getExpectedColorParam ( 1 ) ; float weight = input . getParameters ( ) . size ( ) > 2 ? input . getExpectedFloatParam ( 2 ) : 0.5f ; return new Color ( ( int ) Math . round ( color1 . getR ( ) * weight + color2 . getR ( ) * ( 1.0 - weight ) ) , ( int ) Math . round ( color1 . getG ( ) * weight + color2 . getG ( ) * ( 1.0 - weight ) ) , ( int ) Math . round ( color1 . getB ( ) * weight + color2 . getB ( ) * ( 1.0 - weight ) ) , ( float ) ( color1 . getA ( ) * weight + color2 . getA ( ) * ( 1.0 - weight ) ) ) ; }
Calculates the weighted arithmetic mean of two colors .
22,693
public Output lineBreak ( ) throws IOException { writer . write ( "\n" ) ; if ( ! skipOptionalOutput ) { for ( int i = 0 ; i < indentLevel ; i ++ ) { writer . write ( indentDepth ) ; } } return this ; }
Outputs an indented line break in any case .
22,694
@ SuppressWarnings ( "squid:S1244" ) public HSL getHSL ( ) { double red = r / 255.0 ; double green = g / 255.0 ; double blue = b / 255.0 ; double min = Math . min ( red , Math . min ( green , blue ) ) ; double max = Math . max ( red , Math . max ( green , blue ) ) ; double delta = max - min ; double l = ( min + max ) / 2 ; double s = 0 ; if ( Math . abs ( delta ) > EPSILON ) { if ( l < 0.5 ) { s = delta / ( max + min ) ; } else { s = delta / ( 2.0 - max - min ) ; } } double h = 0 ; if ( delta > 0 ) { if ( red == max ) { h = ( green - blue ) / delta ; } else if ( green == max ) { h = ( ( blue - red ) / delta ) + 2.0 ; } else { h = ( ( red - green ) / delta ) + 4.0 ; } } h = h * 60 ; return new HSL ( ( int ) Math . round ( h ) , s , l ) ; }
Computes the HSL value form the stored RGB values .
22,695
public String getMediaQuery ( Scope scope , Generator gen ) { StringBuilder sb = new StringBuilder ( ) ; for ( Expression expr : mediaQueries ) { if ( sb . length ( ) > 0 ) { sb . append ( " and " ) ; } sb . append ( expr . eval ( scope , gen ) ) ; } return sb . toString ( ) ; }
Compiles the effective media query of this section into a string
22,696
public String getSelectorString ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( List < String > selector : selectors ) { if ( sb . length ( ) > 0 ) { sb . append ( "," ) ; } for ( String s : selector ) { if ( sb . length ( ) > 0 ) { sb . append ( " " ) ; } sb . append ( s ) ; } } return sb . toString ( ) ; }
Compiles the effective selector string .
22,697
public void importStylesheet ( Stylesheet sheet ) { if ( sheet == null ) { return ; } if ( importedSheets . contains ( sheet . getName ( ) ) ) { return ; } importedSheets . add ( sheet . getName ( ) ) ; for ( String imp : sheet . getImports ( ) ) { importStylesheet ( imp ) ; } for ( Mixin mix : sheet . getMixins ( ) ) { mixins . put ( mix . getName ( ) , mix ) ; } for ( Variable var : sheet . getVariables ( ) ) { if ( ! scope . has ( var . getName ( ) ) || ! var . isDefaultValue ( ) ) { scope . set ( var . getName ( ) , var . getValue ( ) ) ; } else { debug ( "Skipping redundant variable definition: '" + var + "'" ) ; } } for ( Section section : sheet . getSections ( ) ) { List < Section > stack = new ArrayList < > ( ) ; expand ( null , section , stack ) ; } }
Imports an already parsed stylesheet .
22,698
protected final boolean isGroupNameValid ( String name ) { if ( name == null ) { return false ; } if ( ! name . startsWith ( DuracloudGroup . PREFIX ) ) { return false ; } if ( DuracloudGroup . PUBLIC_GROUP_NAME . equalsIgnoreCase ( name ) ) { return false ; } return name . substring ( DuracloudGroup . PREFIX . length ( ) ) . matches ( "\\A(?![_.@\\-])[a-z0-9_.@\\-]+(?<![_.@\\-])\\Z" ) ; }
This method is protected for testing purposes only .
22,699
public List < DuplicationInfo > getDupIssues ( ) { List < DuplicationInfo > dupIssues = new LinkedList < > ( ) ; for ( DuplicationInfo dupInfo : dupInfos . values ( ) ) { if ( dupInfo . hasIssues ( ) ) { dupIssues . add ( dupInfo ) ; } } return dupIssues ; }
This method gets all issues discovered for all checked accounts