idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
22,500
@ Path ( "teams" ) public Response authorizedTeams ( @ HeaderParam ( "Authorization" ) @ DefaultValue ( "no token" ) String auth ) throws Exception { if ( ! this . isAuth ( auth ) ) { return Response . status ( Status . FORBIDDEN ) . build ( ) ; } Integer teams [ ] = getAuthorizedTeams ( ) ; return Response . ok ( new Gson ( ) . toJson ( teams ) , MediaType . APPLICATION_JSON ) . build ( ) ; }
Get the list of github team ids that are allowed to access this instance .
22,501
private void sendRequest ( HttpUriRequest request , int expectedStatus ) throws Exception { addAuthHeader ( request ) ; HttpClient client = httpClient ( ) ; HttpResponse response = client . execute ( request ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_NOT_FOUND ) { EntityUtils . consume ( response . getEntity ( ) ) ; System . err . println ( "Authentication has been disabled for " + args . get ( 1 ) + "." ) ; } else if ( response . getStatusLine ( ) . getStatusCode ( ) == expectedStatus ) { if ( expectedStatus == HttpStatus . SC_OK ) { String responseStr = EntityUtils . toString ( response . getEntity ( ) ) ; List < String > usernames = new Gson ( ) . fromJson ( responseStr , new TypeToken < List < String > > ( ) { } . getType ( ) ) ; if ( usernames == null || usernames . isEmpty ( ) ) { System . out . println ( "There have been no site specific users created." ) ; } else { System . out . println ( usernames . size ( ) + " Users:" ) ; for ( String user : usernames ) { System . out . println ( user ) ; } } } } else { System . err . println ( EntityUtils . toString ( response . getEntity ( ) ) ) ; System . err . println ( "Unexpected status code returned. " + response . getStatusLine ( ) . getStatusCode ( ) ) ; } }
Sends a request to the rest endpoint .
22,502
private String hashPasswordForShiro ( ) { HashFormatFactory HASH_FORMAT_FACTORY = new DefaultHashFormatFactory ( ) ; SecureRandomNumberGenerator generator = new SecureRandomNumberGenerator ( ) ; int byteSize = 128 / 8 ; ByteSource salt = generator . nextBytes ( byteSize ) ; SimpleHash hash = new SimpleHash ( "SHA-256" , password , salt , 10 ) ; HashFormat format = HASH_FORMAT_FACTORY . getInstance ( "shiro1" ) ; return format . format ( hash ) ; }
Hashes a password the shiro way .
22,503
public static Field createTupleField ( String name , Schema schema ) { return Field . createTupleField ( name , schema ) ; }
Creates a field containing a Pangool Tuple .
22,504
protected void configure ( ) { try { InternalLoggerFactory . setDefaultFactory ( new Slf4JLoggerFactory ( ) ) ; File appRoot = new File ( System . getProperty ( CadmiumListener . BASE_PATH_ENV ) , "maven" ) ; FileUtils . forceMkdir ( appRoot ) ; String remoteMavenRepo = System . getProperty ( MAVEN_REPOSITORY ) ; ArtifactResolver resolver = new ArtifactResolver ( remoteMavenRepo , appRoot . getAbsolutePath ( ) ) ; bind ( ArtifactResolver . class ) . toInstance ( resolver ) ; bind ( JBossAdminApi . class ) ; Multibinder < ConfigurationListener > listenerBinder = Multibinder . newSetBinder ( binder ( ) , ConfigurationListener . class ) ; listenerBinder . addBinding ( ) . to ( JBossAdminApi . class ) ; bind ( IJBossUtil . class ) . to ( JBossDelegator . class ) ; } catch ( Exception e ) { logger . error ( "Failed to initialize maven artifact resolver." , e ) ; } }
Called to do all bindings for this module .
22,505
public static Response internalError ( Throwable throwable , UriInfo uriInfo ) { GenericError error = new GenericError ( ExceptionUtils . getRootCauseMessage ( throwable ) , ErrorCode . INTERNAL . getCode ( ) , uriInfo . getAbsolutePath ( ) . toString ( ) ) ; if ( ! isProduction ( ) ) { error . setStack ( ExceptionUtils . getStackTrace ( throwable ) ) ; } return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . type ( MediaType . APPLICATION_JSON_TYPE ) . entity ( error ) . build ( ) ; }
Creates Jersey response corresponding to internal error
22,506
public static GitService initializeConfigDirectory ( String uri , String branch , String root , String warName , HistoryManager historyManager , ConfigManager configManager ) throws Exception { initializeBaseDirectoryStructure ( root , warName ) ; String warDir = FileSystemManager . getChildDirectoryIfExists ( root , warName ) ; Properties configProperties = configManager . getDefaultProperties ( ) ; GitLocation gitLocation = new GitLocation ( uri , branch , configProperties . getProperty ( "config.git.ref.sha" ) ) ; GitService cloned = initializeRepo ( gitLocation , warDir , "git-config-checkout" ) ; try { String renderedContentDir = initializeSnapshotDirectory ( warDir , configProperties , "com.meltmedia.cadmium.config.lastUpdated" , "git-config-checkout" , "config" ) ; boolean hasExisting = configProperties . containsKey ( "com.meltmedia.cadmium.config.lastUpdated" ) && renderedContentDir != null && renderedContentDir . equals ( configProperties . getProperty ( "com.meltmedia.cadmium.config.lastUpdated" ) ) ; if ( renderedContentDir != null ) { configProperties . setProperty ( "com.meltmedia.cadmium.config.lastUpdated" , renderedContentDir ) ; } configProperties . setProperty ( "config.branch" , cloned . getBranchName ( ) ) ; configProperties . setProperty ( "config.git.ref.sha" , cloned . getCurrentRevision ( ) ) ; configProperties . setProperty ( "config.repo" , cloned . getRemoteRepository ( ) ) ; configManager . persistDefaultProperties ( ) ; ExecutorService pool = null ; if ( historyManager == null ) { pool = Executors . newSingleThreadExecutor ( ) ; historyManager = new HistoryManager ( warDir , pool ) ; } try { if ( historyManager != null && ! hasExisting ) { historyManager . logEvent ( EntryType . CONFIG , new GitLocation ( cloned . getRemoteRepository ( ) , cloned . getBranchName ( ) , cloned . getCurrentRevision ( ) ) , "AUTO" , renderedContentDir , "" , "Initial config pull." , true , true ) ; } } finally { if ( pool != null ) { pool . shutdownNow ( ) ; } } return cloned ; } catch ( Throwable e ) { cloned . close ( ) ; throw new Exception ( e ) ; } }
Initializes war configuration directory for a Cadmium war .
22,507
public String checkinNewContent ( String sourceDirectory , String message ) throws Exception { RmCommand remove = git . rm ( ) ; boolean hasFiles = false ; for ( String filename : new File ( getBaseDirectory ( ) ) . list ( ) ) { if ( ! filename . equals ( ".git" ) ) { remove . addFilepattern ( filename ) ; hasFiles = true ; } } if ( hasFiles ) { log . info ( "Removing old content." ) ; remove . call ( ) ; } log . info ( "Copying in new content." ) ; FileSystemManager . copyAllContent ( sourceDirectory , getBaseDirectory ( ) , true ) ; log . info ( "Adding new content." ) ; AddCommand add = git . add ( ) ; for ( String filename : new File ( getBaseDirectory ( ) ) . list ( ) ) { if ( ! filename . equals ( ".git" ) ) { add . addFilepattern ( filename ) ; } } add . call ( ) ; log . info ( "Committing new content." ) ; git . commit ( ) . setMessage ( message ) . call ( ) ; return getCurrentRevision ( ) ; }
Checks in content from a source directory into the current git repository .
22,508
public ObjectNode convertToObjectNode ( ILoggingEvent event ) { final ObjectNode logLine = mapper . valueToTree ( event instanceof OtlType ? event : new ApplicationLogEvent ( event ) ) ; final Marker marker = event . getMarker ( ) ; if ( marker instanceof LogMetadata ) { ObjectNode metadataNode = mapper . valueToTree ( ( ( LogMetadata ) marker ) . getMetadata ( ) ) ; logLine . setAll ( metadataNode ) ; for ( Object o : ( ( LogMetadata ) marker ) . getInlines ( ) ) { metadataNode = mapper . valueToTree ( o ) ; logLine . setAll ( metadataNode ) ; } } if ( marker instanceof OtlMarker ) { ObjectNode metadataNode = mapper . valueToTree ( ( ( OtlMarker ) marker ) . getOtl ( ) ) ; logLine . setAll ( metadataNode ) ; } for ( Entry < String , String > e : event . getMDCPropertyMap ( ) . entrySet ( ) ) { if ( ! logLine . has ( e . getKey ( ) ) ) { logLine . put ( e . getKey ( ) , e . getValue ( ) ) ; } } logLine . put ( "sequencenumber" , LOG_SEQUENCE_NUMBER . incrementAndGet ( ) ) ; return logLine ; }
Prepare a log event but don t append it return it as an ObjectNode instead .
22,509
protected byte [ ] getLogMessage ( final ObjectNode event ) { try ( ByteArrayBuilder buf = new ByteArrayBuilder ( ) ) { mapper . writeValue ( buf , event ) ; buf . append ( '\n' ) ; return buf . toByteArray ( ) ; } catch ( IOException e ) { addError ( "while serializing log event" , e ) ; return NADA ; } }
Convert the JSON object to a byte array to log
22,510
public void execute ( ) throws Exception { String content = null ; String siteUrl = null ; if ( params . size ( ) == 2 ) { content = params . get ( 0 ) ; siteUrl = getSecureBaseUrl ( params . get ( 1 ) ) ; } else if ( params . size ( ) == 0 ) { System . err . println ( "The content directory and site must be specifed." ) ; System . exit ( 1 ) ; } else { System . err . println ( "Too many parameters were specified." ) ; System . exit ( 1 ) ; } GitService git = null ; try { System . out . println ( "Getting status of [" + siteUrl + "]" ) ; Status status = StatusCommand . getSiteStatus ( siteUrl , token ) ; if ( repo != null ) { status . setRepo ( repo ) ; } status . setRevision ( null ) ; System . out . println ( "Cloning repository that [" + siteUrl + "] is serving" ) ; git = CloneCommand . cloneSiteRepo ( status ) ; String revision = status . getRevision ( ) ; String branch = status . getBranch ( ) ; if ( ! UpdateCommand . isValidBranchName ( branch , UpdateRequest . CONTENT_BRANCH_PREFIX ) ) { throw new Exception ( "Cannot commit to a branch without the prefix of " + UpdateRequest . CONTENT_BRANCH_PREFIX + "." ) ; } if ( git . isTag ( branch ) ) { throw new Exception ( "Cannot commit to a tag!" ) ; } System . out . println ( "Cloning content from [" + content + "] to [" + siteUrl + ":" + branch + "]" ) ; revision = CloneCommand . cloneContent ( content , git , comment ) ; System . out . println ( "Switching content on [" + siteUrl + "]" ) ; if ( ! UpdateCommand . sendUpdateMessage ( siteUrl , null , branch , revision , comment , token ) ) { System . err . println ( "Failed to update [" + siteUrl + "]" ) ; System . exit ( 1 ) ; } } catch ( Exception e ) { System . err . println ( "Failed to commit changes to [" + siteUrl + "]: " + e . getMessage ( ) ) ; System . exit ( 1 ) ; } finally { if ( git != null ) { String dir = git . getBaseDirectory ( ) ; git . close ( ) ; FileUtils . forceDelete ( new File ( dir ) ) ; } } }
Does the work for this command .
22,511
public static void enableSerialization ( Configuration conf ) { String serClass = TupleSerialization . class . getName ( ) ; Collection < String > currentSers = conf . getStringCollection ( "io.serializations" ) ; if ( currentSers . size ( ) == 0 ) { conf . set ( "io.serializations" , serClass ) ; return ; } if ( ! currentSers . contains ( serClass ) ) { currentSers . add ( serClass ) ; conf . setStrings ( "io.serializations" , currentSers . toArray ( new String [ ] { } ) ) ; } }
Use this method to enable this serialization in Hadoop
22,512
public static void disableSerialization ( Configuration conf ) { String ser = conf . get ( "io.serializations" ) . trim ( ) ; String stToSearch = Pattern . quote ( "," + TupleSerialization . class . getName ( ) ) ; ser = ser . replaceAll ( stToSearch , "" ) ; conf . set ( "io.serializations" , ser ) ; }
Use this method to disable this serialization in Hadoop
22,513
public static int compare ( String ns1 , String ln1 , String ns2 , String ln2 ) { if ( ns1 == null ) { ns1 = Constants . XML_NULL_NS_URI ; } if ( ns2 == null ) { ns2 = Constants . XML_NULL_NS_URI ; } int cLocalPart = ln1 . compareTo ( ln2 ) ; return ( cLocalPart == 0 ? ns1 . compareTo ( ns2 ) : cLocalPart ) ; }
Sort lexicographically by qname local - name then by qname uri
22,514
public static void postConstructQuietly ( Object obj , Logger log ) { try { postConstruct ( obj , log ) ; } catch ( Throwable t ) { log . warn ( "Could not @PostConstruct object" , t ) ; } }
Calls postConstruct with the same arguments logging any exceptions that are thrown at the level warn .
22,515
public static void preDestroyQuietly ( Object obj , Logger log ) { try { preDestroy ( obj , log ) ; } catch ( Throwable t ) { log . warn ( "Could not @PreDestroy object" , t ) ; } }
Calls preDestroy with the same arguments logging any exceptions that are thrown at the level warn .
22,516
private static List < Method > getAnnotatedMethodsFromChildToParent ( Class < ? > clazz , Class < ? extends Annotation > annotation , Logger log ) { List < Method > methodsToRun = new ArrayList < Method > ( ) ; while ( clazz != null ) { List < Method > newMethods = getMethodsWithAnnotation ( clazz , annotation , log ) ; for ( Method newMethod : newMethods ) { if ( containsMethod ( newMethod , methodsToRun ) ) { removeMethodByName ( newMethod , methodsToRun ) ; } else { methodsToRun . add ( newMethod ) ; } } clazz = clazz . getSuperclass ( ) ; if ( clazz != null && clazz . equals ( Object . class ) ) { clazz = null ; } } return methodsToRun ; }
Locates all annotated methods on the type passed in sorted as declared from the type to its super class .
22,517
private static boolean containsMethod ( Method method , List < Method > methods ) { if ( methods != null ) { for ( Method aMethod : methods ) { if ( method . getName ( ) . equals ( aMethod . getName ( ) ) ) { return true ; } } } return false ; }
Checks if the passed in method already exists in the list of methods . Checks for equality by the name of the method .
22,518
private static void removeMethodByName ( Method method , List < Method > methods ) { if ( methods != null ) { Iterator < Method > itr = methods . iterator ( ) ; Method aMethod = null ; while ( itr . hasNext ( ) ) { aMethod = itr . next ( ) ; if ( aMethod . getName ( ) . equals ( method . getName ( ) ) ) { itr . remove ( ) ; break ; } } if ( aMethod != null ) { methods . add ( aMethod ) ; } } }
Removes a method from the given list and adds it to the end of the list .
22,519
private static List < Method > getMethodsWithAnnotation ( Class < ? > clazz , Class < ? extends Annotation > annotation , Logger log ) { List < Method > annotatedMethods = new ArrayList < Method > ( ) ; Method classMethods [ ] = clazz . getDeclaredMethods ( ) ; for ( Method classMethod : classMethods ) { if ( classMethod . isAnnotationPresent ( annotation ) && classMethod . getParameterTypes ( ) . length == 0 ) { if ( ! containsMethod ( classMethod , annotatedMethods ) ) { annotatedMethods . add ( classMethod ) ; } } } Collections . sort ( annotatedMethods , new Comparator < Method > ( ) { public int compare ( Method method1 , Method method2 ) { return method1 . getName ( ) . compareTo ( method2 . getName ( ) ) ; } } ) ; return annotatedMethods ; }
Locates all methods annotated with a given annotation that are declared directly in the class passed in alphabetical order .
22,520
public static Jsr250Executor createJsr250Executor ( Injector injector , final Logger log , Scope ... scopes ) { final Set < Object > instances = findInstancesInScopes ( injector , scopes ) ; final List < Object > reverseInstances = new ArrayList < Object > ( instances ) ; Collections . reverse ( reverseInstances ) ; return new Jsr250Executor ( ) { public Set < Object > getInstances ( ) { return instances ; } public void postConstruct ( ) { for ( Object instance : instances ) { postConstructQuietly ( instance , log ) ; } } public void preDestroy ( ) { for ( Object instance : reverseInstances ) { preDestroyQuietly ( instance , log ) ; } } } ; }
Creates a Jsr250Executor for the specified scopes .
22,521
public static Set < Object > findInstancesInScopes ( Injector injector , Class < ? extends Annotation > ... scopeAnnotations ) { Set < Object > objects = new TreeSet < Object > ( new Comparator < Object > ( ) { public int compare ( Object o0 , Object o1 ) { return o0 . getClass ( ) . getName ( ) . compareTo ( o1 . getClass ( ) . getName ( ) ) ; } } ) ; for ( Map . Entry < Key < ? > , Binding < ? > > entry : findBindingsInScope ( injector , scopeAnnotations ) . entrySet ( ) ) { Object object = injector . getInstance ( entry . getKey ( ) ) ; objects . add ( object ) ; } return objects ; }
Finds all of the instances in the specified scopes .
22,522
public static Map < Key < ? > , Binding < ? > > findBindingsInScope ( Injector injector , Class < ? extends Annotation > ... scopeAnnotations ) { Map < Key < ? > , Binding < ? > > bindings = new LinkedHashMap < Key < ? > , Binding < ? > > ( ) ; ALL_BINDINGS : for ( Map . Entry < Key < ? > , Binding < ? > > entry : injector . getAllBindings ( ) . entrySet ( ) ) { for ( Class < ? extends Annotation > scopeAnnotation : scopeAnnotations ) { if ( inScope ( injector , entry . getValue ( ) , scopeAnnotation ) ) { bindings . put ( entry . getKey ( ) , entry . getValue ( ) ) ; continue ALL_BINDINGS ; } } } return bindings ; }
Finds all of the unique providers in the injector in the specified scopes .
22,523
public static Map < Key < ? > , Binding < ? > > findBindingsInScope ( Injector injector , Scope ... scopes ) { Map < Key < ? > , Binding < ? > > bindings = new LinkedHashMap < Key < ? > , Binding < ? > > ( ) ; ALL_BINDINGS : for ( Map . Entry < Key < ? > , Binding < ? > > entry : injector . getAllBindings ( ) . entrySet ( ) ) { for ( Scope scope : scopes ) { if ( inScope ( injector , entry . getValue ( ) , scope ) ) { bindings . put ( entry . getKey ( ) , entry . getValue ( ) ) ; continue ALL_BINDINGS ; } } } return bindings ; }
Returns the bindings in the specified scope .
22,524
public static boolean inScope ( final Injector injector , final Binding < ? > binding , final Class < ? extends Annotation > scope ) { return binding . acceptScopingVisitor ( new BindingScopingVisitor < Boolean > ( ) { public Boolean visitEagerSingleton ( ) { return scope == Singleton . class || scope == javax . inject . Singleton . class ; } public Boolean visitNoScoping ( ) { return false ; } public Boolean visitScope ( Scope guiceScope ) { return injector . getScopeBindings ( ) . get ( scope ) == guiceScope ; } public Boolean visitScopeAnnotation ( Class < ? extends Annotation > scopeAnnotation ) { return scopeAnnotation == scope ; } } ) ; }
Returns true if the binding is in the specified scope false otherwise .
22,525
private void init ( Class < ? > type ) { if ( method . isAnnotationPresent ( CoordinatorOnly . class ) || type . isAnnotationPresent ( CoordinatorOnly . class ) ) { coordinatorOnly = true ; } if ( method . isAnnotationPresent ( Scheduled . class ) ) { annotation = method . getAnnotation ( Scheduled . class ) ; } else if ( type . isAnnotationPresent ( Scheduled . class ) ) { annotation = type . getAnnotation ( Scheduled . class ) ; } }
Sets all values needed for the scheduling of this Runnable .
22,526
private void checkRunnable ( Class < ? > type ) { if ( Runnable . class . isAssignableFrom ( type ) ) { try { this . method = type . getMethod ( "run" ) ; } catch ( Exception e ) { throw new RuntimeException ( "Cannot get run method of runnable class." , e ) ; } } }
Checks if the type is a Runnable and gets the run method .
22,527
public static String [ ] sendRequest ( String token , String site , OPERATION op , String path ) throws Exception { HttpClient client = httpClient ( ) ; HttpUriRequest message = null ; if ( op == OPERATION . DISABLE ) { message = new HttpPut ( site + ENDPOINT + path ) ; } else if ( op == OPERATION . ENABLE ) { message = new HttpDelete ( site + ENDPOINT + path ) ; } else { message = new HttpGet ( site + ENDPOINT ) ; } addAuthHeader ( token , message ) ; HttpResponse resp = client . execute ( message ) ; if ( resp . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { String results = EntityUtils . toString ( resp . getEntity ( ) ) ; return new Gson ( ) . fromJson ( results , String [ ] . class ) ; } return null ; }
Sends acl request to cadmium .
22,528
public void shallowCopy ( ITuple tupleDest ) { for ( Field field : this . getSchema ( ) . getFields ( ) ) { tupleDest . set ( field . getName ( ) , this . get ( field . getName ( ) ) ) ; } }
Simple shallow copy of this Tuple to another Tuple .
22,529
public static final String getQualifiedName ( String localName , String pfx ) { pfx = pfx == null ? "" : pfx ; return pfx . length ( ) == 0 ? localName : ( pfx + Constants . COLON + localName ) ; }
Returns qualified name as String
22,530
public void setOption ( String key , Object value ) throws UnsupportedOption { if ( key . equals ( INCLUDE_COOKIE ) ) { options . put ( key , null ) ; } else if ( key . equals ( INCLUDE_OPTIONS ) ) { options . put ( key , null ) ; } else if ( key . equals ( INCLUDE_SCHEMA_ID ) ) { options . put ( key , null ) ; } else if ( key . equals ( RETAIN_ENTITY_REFERENCE ) ) { options . put ( key , null ) ; } else if ( key . equals ( INCLUDE_XSI_SCHEMALOCATION ) ) { options . put ( key , null ) ; } else if ( key . equals ( INCLUDE_INSIGNIFICANT_XSI_NIL ) ) { options . put ( key , null ) ; } else if ( key . equals ( INCLUDE_PROFILE_VALUES ) ) { options . put ( key , null ) ; } else if ( key . equals ( CANONICAL_EXI ) ) { options . put ( key , null ) ; this . setOption ( INCLUDE_OPTIONS ) ; } else if ( key . equals ( UTC_TIME ) ) { options . put ( key , null ) ; } else if ( key . equals ( DEFLATE_COMPRESSION_VALUE ) ) { if ( value != null && value instanceof Integer ) { options . put ( key , value ) ; } else { throw new UnsupportedOption ( "EncodingOption '" + key + "' requires value of type Integer" ) ; } } else { throw new UnsupportedOption ( "EncodingOption '" + key + "' is unknown!" ) ; } }
Enables given option with value .
22,531
public boolean unsetOption ( String key ) { boolean b = options . containsKey ( key ) ; options . remove ( key ) ; return b ; }
Disables given option .
22,532
private static void checkNamedOutputName ( JobContext job , String namedOutput , boolean alreadyDefined ) { validateOutputName ( namedOutput ) ; List < String > definedChannels = getNamedOutputsList ( job ) ; if ( alreadyDefined && definedChannels . contains ( namedOutput ) ) { throw new IllegalArgumentException ( "Named output '" + namedOutput + "' already alreadyDefined" ) ; } else if ( ! alreadyDefined && ! definedChannels . contains ( namedOutput ) ) { throw new IllegalArgumentException ( "Named output '" + namedOutput + "' not defined" ) ; } }
Checks if a named output name is valid .
22,533
private static String getDefaultNamedOutputFormatInstanceFile ( JobContext job ) { return job . getConfiguration ( ) . get ( DEFAULT_MO_PREFIX + FORMAT_INSTANCE_FILE , null ) ; }
Returns the DEFAULT named output OutputFormat .
22,534
private static Class < ? > getDefaultNamedOutputKeyClass ( JobContext job ) { return job . getConfiguration ( ) . getClass ( DEFAULT_MO_PREFIX + KEY , null , Object . class ) ; }
Returns the DEFAULT key class for a named output .
22,535
private static Class < ? > getDefaultNamedOutputValueClass ( JobContext job ) { return job . getConfiguration ( ) . getClass ( DEFAULT_MO_PREFIX + VALUE , null , Object . class ) ; }
Returns the DEFAULT value class for a named output .
22,536
public static String addNamedOutput ( Job job , String namedOutput , OutputFormat outputFormat , Class < ? > keyClass , Class < ? > valueClass ) throws FileNotFoundException , IOException , URISyntaxException { checkNamedOutputName ( job , namedOutput , true ) ; Configuration conf = job . getConfiguration ( ) ; String uniqueName = UUID . randomUUID ( ) . toString ( ) + '.' + "out-format.dat" ; InstancesDistributor . distribute ( outputFormat , uniqueName , conf ) ; conf . set ( MULTIPLE_OUTPUTS , conf . get ( MULTIPLE_OUTPUTS , "" ) + " " + namedOutput ) ; conf . set ( MO_PREFIX + namedOutput + FORMAT_INSTANCE_FILE , uniqueName ) ; conf . setClass ( MO_PREFIX + namedOutput + KEY , keyClass , Object . class ) ; conf . setClass ( MO_PREFIX + namedOutput + VALUE , valueClass , Object . class ) ; return uniqueName ; }
Adds a named output for the job . Returns the instance file that has been created .
22,537
@ SuppressWarnings ( "unchecked" ) public < K , V > void write ( String namedOutput , K key , V value , String baseOutputPath ) throws IOException , InterruptedException { checkNamedOutputName ( context , namedOutput , false ) ; checkBaseOutputPath ( baseOutputPath ) ; if ( ! namedOutputs . contains ( namedOutput ) ) { throw new IllegalArgumentException ( "Undefined named output '" + namedOutput + "'" ) ; } getRecordWriter ( baseOutputPath ) . write ( key , value ) ; }
Write key and value to baseOutputPath using the namedOutput .
22,538
public void close ( ) throws IOException , InterruptedException { for ( OutputContext outputContext : this . outputContexts . values ( ) ) { outputContext . recordWriter . close ( outputContext . taskAttemptContext ) ; outputContext . outputCommitter . commitTask ( outputContext . taskAttemptContext ) ; JobContext jContext ; try { jContext = JobContextFactory . get ( outputContext . taskAttemptContext . getConfiguration ( ) , new JobID ( ) ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } try { Class cl = Class . forName ( OutputCommitter . class . getName ( ) ) ; Method method = cl . getMethod ( "commitJob" , Class . forName ( JobContext . class . getName ( ) ) ) ; if ( method != null ) { method . invoke ( outputContext . outputCommitter , jContext ) ; } } catch ( Exception e ) { } outputContext . outputCommitter . cleanupJob ( outputContext . jobContext ) ; } }
Closes all the opened outputs .
22,539
private WhiteSpace getDatatypeWhiteSpace ( ) { Grammar currGr = this . getCurrentGrammar ( ) ; if ( currGr . isSchemaInformed ( ) && currGr . getNumberOfEvents ( ) > 0 ) { Production prod = currGr . getProduction ( 0 ) ; if ( prod . getEvent ( ) . getEventType ( ) == EventType . CHARACTERS ) { Characters ch = ( Characters ) prod . getEvent ( ) ; return ch . getDatatype ( ) . getWhiteSpace ( ) ; } } return null ; }
returns null if no CH datatype is available or schema - less
22,540
public void skip ( long n ) throws IOException { if ( capacity == 0 ) { while ( n != 0 ) { n -= istream . skip ( n ) ; } } else { for ( int i = 0 ; i < n ; n ++ ) { readBits ( 8 ) ; } } }
Skip n bytes
22,541
public int readBits ( int n ) throws IOException { assert ( n > 0 ) ; int result ; if ( n <= capacity ) { result = ( buffer >> ( capacity -= n ) ) & ( 0xff >> ( BUFFER_CAPACITY - n ) ) ; } else if ( capacity == 0 && n == BUFFER_CAPACITY ) { result = readDirectByte ( ) ; } else { result = buffer & ( 0xff >> ( BUFFER_CAPACITY - capacity ) ) ; n -= capacity ; capacity = 0 ; while ( n > 7 ) { if ( capacity == 0 ) { readBuffer ( ) ; } result = ( result << BUFFER_CAPACITY ) | buffer ; n -= BUFFER_CAPACITY ; capacity = 0 ; } if ( n > 0 ) { if ( capacity == 0 ) { readBuffer ( ) ; } result = ( result << n ) | ( buffer >> ( capacity = ( BUFFER_CAPACITY - n ) ) ) ; } } return result ; }
Read the next n bits and return the result as an integer .
22,542
public void readFields ( ITuple tuple , Deserializer [ ] customDeserializers ) throws IOException { readFields ( tuple , readSchema , customDeserializers ) ; }
Read fields using the specified readSchema in the constructor .
22,543
public final void mutate ( Context context ) throws MutagenException { performMutation ( context ) ; int version = getResultingState ( ) . getID ( ) ; String change = getChangeSummary ( ) ; if ( change == null ) { change = "" ; } String changeHash = md5String ( change ) ; try { MutationBatch batch = getKeyspace ( ) . prepareMutationBatch ( ) ; batch . withRow ( CassandraSubject . VERSION_CF , CassandraSubject . ROW_KEY ) . putColumn ( CassandraSubject . VERSION_COLUMN , version ) ; batch . withRow ( CassandraSubject . VERSION_CF , String . format ( "%08d" , version ) ) . putColumn ( "change" , change ) . putColumn ( "hash" , changeHash ) ; batch . execute ( ) ; } catch ( ConnectionException e ) { throw new MutagenException ( "Could not update \"schema_version\" " + "column family to state " + version + "; schema is now out of sync with recorded version" , e ) ; } }
Performs the actual mutation and then updates the recorded schema version
22,544
public static String toHex ( byte [ ] bytes ) { StringBuilder hexString = new StringBuilder ( ) ; for ( int i = 0 ; i < bytes . length ; i ++ ) { String hex = Integer . toHexString ( 0xFF & bytes [ i ] ) ; if ( hex . length ( ) == 1 ) { hexString . append ( '0' ) ; } hexString . append ( hex ) ; } return hexString . toString ( ) ; }
Encode a byte array as a hexadecimal string
22,545
public static List < String > getDeployed ( String url , String token ) throws Exception { List < String > deployed = new ArrayList < String > ( ) ; HttpClient client = httpClient ( ) ; HttpGet get = new HttpGet ( url + "/system/deployment/list" ) ; addAuthHeader ( token , get ) ; HttpResponse resp = client . execute ( get ) ; if ( resp . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { List < String > respList = new Gson ( ) . fromJson ( EntityUtils . toString ( resp . getEntity ( ) ) , new TypeToken < List < String > > ( ) { } . getType ( ) ) ; if ( respList != null ) { deployed . addAll ( respList ) ; } } return deployed ; }
Retrieves a list of Cadmium wars that are deployed .
22,546
public static void undeploy ( String url , String warName , String token ) throws Exception { HttpClient client = httpClient ( ) ; HttpPost del = new HttpPost ( url + "/system/undeploy" ) ; addAuthHeader ( token , del ) ; del . addHeader ( "Content-Type" , MediaType . APPLICATION_JSON ) ; UndeployRequest req = new UndeployRequest ( ) ; req . setWarName ( warName ) ; del . setEntity ( new StringEntity ( new Gson ( ) . toJson ( req ) , "UTF-8" ) ) ; HttpResponse resp = client . execute ( del ) ; if ( resp . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { String respStr = EntityUtils . toString ( resp . getEntity ( ) ) ; if ( ! respStr . equals ( "ok" ) ) { throw new Exception ( "Failed to undeploy " + warName ) ; } else { System . out . println ( "Undeployment of " + warName + " successful" ) ; } } else { System . err . println ( "Failed to undeploy " + warName ) ; System . err . println ( resp . getStatusLine ( ) . getStatusCode ( ) + ": " + EntityUtils . toString ( resp . getEntity ( ) ) ) ; } }
Sends the undeploy command to a Cadmium - Deployer war .
22,547
public void set ( int bit , boolean value ) { int bite = byteForBit ( bit ) ; ensureSpace ( bite + 1 ) ; int bitOnByte = bitOnByte ( bit , bite ) ; if ( value ) { bits [ bite ] = byteBitSet ( bitOnByte , bits [ bite ] ) ; } else { bits [ bite ] = byteBitUnset ( bitOnByte , bits [ bite ] ) ; } }
Sets or unsets a bit . The smaller allowed bit is 0
22,548
public boolean isSet ( int bit ) { int bite = byteForBit ( bit ) ; if ( bite >= bits . length || bits . length == 0 ) { return false ; } int bitOnByte = bitOnByte ( bit , bite ) ; return ( ( 1 << bitOnByte ) & bits [ bite ] ) != 0 ; }
Returns the value of a given bit . False is returned for unexisting bits .
22,549
public void ser ( DataOutput out ) throws IOException { if ( bits . length == 0 ) { out . writeByte ( 0 ) ; return ; } int bytesToWrite ; for ( bytesToWrite = bits . length ; bytesToWrite > 1 && bits [ bytesToWrite - 1 ] == 0 ; bytesToWrite -- ) ; for ( int i = 0 ; i < ( bytesToWrite - 1 ) ; i ++ ) { out . writeByte ( ( bits [ i ] | 1 ) ) ; } out . writeByte ( ( bits [ bytesToWrite - 1 ] & ~ 1 ) ) ; }
Serializes the bit field to the data output . It uses one byte per each 7 bits . If the rightmost bit of the read byte is set that means that there are more bytes to consume . The latest byte has the rightmost bit unset .
22,550
public int deser ( byte [ ] bytes , int start ) throws IOException { int idx = 0 ; byte current ; do { current = bytes [ start + idx ] ; ensureSpace ( idx + 1 ) ; bits [ idx ] = ( byte ) ( current & ~ 1 ) ; idx ++ ; } while ( ( current & 1 ) != 0 ) ; for ( int i = idx ; i < bits . length ; i ++ ) { bits [ i ] = 0 ; } return idx ; }
Deserialize a BitField serialized from a byte array . Return the number of bytes consumed .
22,551
protected void ensureSpace ( int bytes ) { if ( bits . length < bytes ) { bits = Arrays . copyOf ( bits , bytes ) ; } }
Ensures a minimum size for the backing byte array
22,552
public TypeDescription addTypeDescription ( TypeDescription definition ) { if ( definition != null && definition . getTag ( ) != null ) { tagsDefined . add ( definition . getTag ( ) ) ; } return super . addTypeDescription ( definition ) ; }
Overridden to capture what tags are defined specially .
22,553
protected Construct getConstructor ( Node node ) { Construct construct = super . getConstructor ( node ) ; logger . trace ( "getting constructor for node {} Tag {} = {}" , new Object [ ] { node , node . getTag ( ) , construct } ) ; if ( construct instanceof ConstructYamlObject && ! tagsDefined . contains ( node . getTag ( ) ) ) { try { node . getTag ( ) . getClassName ( ) ; } catch ( YAMLException e ) { node . setUseClassConstructor ( true ) ; String value = null ; if ( node . getNodeId ( ) == NodeId . scalar ) { value = ( ( ScalarNode ) node ) . getValue ( ) ; } node . setTag ( resolver . resolve ( node . getNodeId ( ) , value , true ) ) ; construct = super . getConstructor ( node ) ; try { resolveType ( node ) ; } catch ( ClassNotFoundException e1 ) { logger . debug ( "Could not find class." , e1 ) ; } } } logger . trace ( "returning constructor for node {} type {} Tag {} = {}" , new Object [ ] { node , node . getType ( ) , node . getTag ( ) , construct } ) ; return construct ; }
Overridden to fetch constructor even if tag is not mapped .
22,554
private void resolveType ( Node node ) throws ClassNotFoundException { String typeName = node . getTag ( ) . getClassName ( ) ; if ( typeName . equals ( "int" ) ) { node . setType ( Integer . TYPE ) ; } else if ( typeName . equals ( "float" ) ) { node . setType ( Float . TYPE ) ; } else if ( typeName . equals ( "double" ) ) { node . setType ( Double . TYPE ) ; } else if ( typeName . equals ( "bool" ) ) { node . setType ( Boolean . TYPE ) ; } else if ( typeName . equals ( "date" ) ) { node . setType ( Date . class ) ; } else if ( typeName . equals ( "seq" ) ) { node . setType ( List . class ) ; } else if ( typeName . equals ( "str" ) ) { node . setType ( String . class ) ; } else if ( typeName . equals ( "map" ) ) { node . setType ( Map . class ) ; } else { node . setType ( getClassForName ( node . getTag ( ) . getClassName ( ) ) ) ; } }
Resolves the type of a node after the tag gets re - resolved .
22,555
protected UUID getRequestIdFrom ( Request request , Response response ) { return optUuid ( response . getHeader ( OTHeaders . REQUEST_ID ) ) ; }
Provides a hook whereby an alternate source can be provided for grabbing the requestId
22,556
public static LoggerConfig [ ] setLogLevel ( String loggerName , String level ) { if ( StringUtils . isBlank ( loggerName ) ) { loggerName = ch . qos . logback . classic . Logger . ROOT_LOGGER_NAME ; } LoggerContext context = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; log . debug ( "Setting {} to level {}" , loggerName , level ) ; ch . qos . logback . classic . Logger logger = null ; try { logger = context . getLogger ( loggerName ) ; if ( logger != null ) { if ( level . equals ( "null" ) || level . equals ( "none" ) ) { logger . setLevel ( null ) ; } else { logger . setLevel ( Level . toLevel ( level ) ) ; } logger = context . getLogger ( loggerName ) ; return new LoggerConfig [ ] { new LoggerConfig ( logger . getName ( ) , logger . getLevel ( ) + "" ) } ; } return new LoggerConfig [ ] { } ; } catch ( Throwable t ) { log . warn ( "Failed to change log level for logger " + loggerName + " to level " + level , t ) ; return new LoggerConfig [ ] { } ; } }
Updates a logger with a given name to the given level .
22,557
public int decodeNBitUnsignedInteger ( int n ) throws IOException { assert ( n >= 0 ) ; int bitsRead = 0 ; int result = 0 ; while ( bitsRead < n ) { result += ( decode ( ) << bitsRead ) ; bitsRead += 8 ; } return result ; }
Decodes and returns an n - bit unsigned integer using the minimum number of bytes required for n bits .
22,558
public Set < String > configureJob ( Job job ) throws FileNotFoundException , IOException , TupleMRException { Set < String > instanceFiles = new HashSet < String > ( ) ; for ( Output output : getNamedOutputs ( ) ) { try { if ( output . isDefault ) { instanceFiles . add ( PangoolMultipleOutputs . setDefaultNamedOutput ( job , output . outputFormat , output . keyClass , output . valueClass ) ) ; } else { instanceFiles . add ( PangoolMultipleOutputs . addNamedOutput ( job , output . name , output . outputFormat , output . keyClass , output . valueClass ) ) ; } } catch ( URISyntaxException e1 ) { throw new TupleMRException ( e1 ) ; } for ( Map . Entry < String , String > contextKeyValue : output . specificContext . entrySet ( ) ) { PangoolMultipleOutputs . addNamedOutputContext ( job , output . name , contextKeyValue . getKey ( ) , contextKeyValue . getValue ( ) ) ; } } return instanceFiles ; }
Use this method for configuring a Job instance according to the named outputs specs that has been specified . Returns the instance files that have been created .
22,559
public boolean canCheckWar ( String warName , String url , HttpClient client ) { HttpOptions opt = new HttpOptions ( url + "/" + warName ) ; try { HttpResponse response = client . execute ( opt ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { Header allowHeader [ ] = response . getHeaders ( "Allow" ) ; for ( Header allow : allowHeader ) { List < String > values = Arrays . asList ( allow . getValue ( ) . toUpperCase ( ) . split ( "," ) ) ; if ( values . contains ( "GET" ) ) { return true ; } } } EntityUtils . consumeQuietly ( response . getEntity ( ) ) ; } catch ( Exception e ) { log . warn ( "Failed to check if endpoint exists." , e ) ; } finally { opt . releaseConnection ( ) ; } return false ; }
Checks via an http options request that the endpoint exists to check for deployment state .
22,560
public void encodeBinary ( byte [ ] b ) throws IOException { encodeUnsignedInteger ( b . length ) ; encode ( b , 0 , b . length ) ; }
Encode a binary value as a length - prefixed sequence of octets .
22,561
public void encodeString ( final String s ) throws IOException { final int lenChars = s . length ( ) ; final int lenCharacters = s . codePointCount ( 0 , lenChars ) ; encodeUnsignedInteger ( lenCharacters ) ; encodeStringOnly ( s ) ; }
Encode a string as a length - prefixed sequence of UCS codepoints each of which is encoded as an integer . Look for codepoints of more than 16 bits that are represented as UTF - 16 surrogate pairs in Java .
22,562
public void encodeInteger ( int n ) throws IOException { if ( n < 0 ) { encodeBoolean ( true ) ; encodeUnsignedInteger ( ( - n ) - 1 ) ; } else { encodeBoolean ( false ) ; encodeUnsignedInteger ( n ) ; } }
Encode an arbitrary precision integer using a sign bit followed by 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,563
public void encodeUnsignedInteger ( int n ) throws IOException { if ( n < 0 ) { throw new UnsupportedOperationException ( ) ; } if ( n < 128 ) { encode ( n ) ; } else { final int n7BitBlocks = MethodsBag . numberOf7BitBlocksToRepresent ( n ) ; switch ( n7BitBlocks ) { case 5 : encode ( 128 | n ) ; n = n >>> 7 ; case 4 : encode ( 128 | n ) ; n = n >>> 7 ; case 3 : encode ( 128 | n ) ; n = n >>> 7 ; case 2 : encode ( 128 | n ) ; n = n >>> 7 ; case 1 : encode ( 0 | n ) ; } } }
Encode 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,564
public void encodeFloat ( FloatValue fv ) throws IOException { encodeIntegerValue ( fv . getMantissa ( ) ) ; encodeIntegerValue ( fv . getExponent ( ) ) ; }
Encode a Float represented as two consecutive Integers . The first Integer represents the mantissa of the floating point number and the second Integer represents the 10 - based exponent of the floating point number
22,565
private void addAddressHelper ( InternetAddressSet set , String address ) { if ( address . contains ( "," ) || address . contains ( ";" ) ) { String [ ] addresses = address . split ( "[,;]" ) ; for ( String a : addresses ) { set . add ( a ) ; } } else { set . add ( address ) ; } }
Checks if the addresses need to be split either on or ;
22,566
public void simplify ( ) { ccSet . removeAll ( toSet ) ; bccSet . removeAll ( toSet ) ; bccSet . removeAll ( ccSet ) ; }
Simplifies this email by removing duplicate pieces of information . The standard implementation removes duplicate recipient emails in the to cc and bcc sets .
22,567
protected void populate ( MimeMessage message ) throws MessagingException { message . addRecipients ( Message . RecipientType . TO , toSet . toInternetAddressArray ( ) ) ; message . addRecipients ( Message . RecipientType . CC , ccSet . toInternetAddressArray ( ) ) ; message . addRecipients ( Message . RecipientType . BCC , bccSet . toInternetAddressArray ( ) ) ; message . setFrom ( from ) ; if ( replyTo != null ) { message . setReplyTo ( new InternetAddress [ ] { replyTo } ) ; } if ( subject != null ) { message . setSubject ( subject ) ; } }
Populates a mime message with the recipient addresses from address reply to address and the subject .
22,568
public static AttachLogFilter attach ( Filter < ILoggingEvent > filter , String configKey ) { return new AttachLogFilter ( filter , configKey ) ; }
Create an attach log filter
22,569
public static void enableThriftSerialization ( Configuration conf ) { String ser = conf . get ( "io.serializations" ) . trim ( ) ; if ( ser . length ( ) != 0 ) { ser += "," ; } ser += ThriftSerialization . class . getName ( ) ; conf . set ( "io.serializations" , ser ) ; }
Enables Thrift Serialization support in Hadoop .
22,570
public static void main ( String [ ] args ) { try { jCommander = new JCommander ( ) ; jCommander . setProgramName ( "cadmium" ) ; HelpCommand helpCommand = new HelpCommand ( ) ; jCommander . addCommand ( "help" , helpCommand ) ; Map < String , CliCommand > commands = wireCommands ( jCommander ) ; try { jCommander . parse ( args ) ; } catch ( ParameterException pe ) { System . err . println ( pe . getMessage ( ) ) ; System . exit ( 1 ) ; } String commandName = jCommander . getParsedCommand ( ) ; if ( commandName == null ) { System . out . println ( "Please use one of the following commands:" ) ; for ( String command : jCommander . getCommands ( ) . keySet ( ) ) { String desc = jCommander . getCommands ( ) . get ( command ) . getObjects ( ) . get ( 0 ) . getClass ( ) . getAnnotation ( Parameters . class ) . commandDescription ( ) ; System . out . format ( " %16s -%s\n" , command , desc ) ; } } else if ( commandName . equals ( "help" ) ) { if ( helpCommand . subCommand == null || helpCommand . subCommand . size ( ) == 0 ) { jCommander . usage ( ) ; return ; } else { JCommander subCommander = jCommander . getCommands ( ) . get ( helpCommand . subCommand . get ( 0 ) ) ; if ( subCommander == null ) { System . out . println ( "Unknown sub command " + commandName ) ; return ; } subCommander . usage ( ) ; return ; } } else if ( commands . containsKey ( commandName ) ) { CliCommand command = commands . get ( commandName ) ; if ( command instanceof AuthorizedOnly ) { setupSsh ( ( ( AuthorizedOnly ) command ) . isAuthQuiet ( ) ) ; setupAuth ( ( AuthorizedOnly ) command ) ; } command . execute ( ) ; } } catch ( Exception e ) { System . err . println ( "Error: " + e . getMessage ( ) ) ; logger . debug ( "Cli Failed" , e ) ; e . printStackTrace ( ) ; System . exit ( 1 ) ; } }
The main entry point to Cadmium cli .
22,571
private static void setupSsh ( boolean noPrompt ) { File sshDir = new File ( System . getProperty ( "user.home" ) , ".ssh" ) ; if ( sshDir . exists ( ) ) { GitService . setupLocalSsh ( sshDir . getAbsolutePath ( ) , noPrompt ) ; } }
Sets up the ssh configuration that git will use to communicate with the remote git repositories .
22,572
public static void emptyMatrix ( byte [ ] [ ] matrix , int maxX , int maxY ) { for ( int i = 0 ; i < maxX ; i ++ ) { for ( int j = 0 ; j < maxY ; j ++ ) { matrix [ i ] [ j ] = 0 ; } } }
It is not very efficient but it is simple enough
22,573
static public byte [ ] decode ( String encoded ) { if ( encoded == null ) return null ; int lengthData = encoded . length ( ) ; if ( lengthData % 2 != 0 ) return null ; char [ ] binaryData = encoded . toCharArray ( ) ; int lengthDecode = lengthData / 2 ; byte [ ] decodedData = new byte [ lengthDecode ] ; byte temp1 , temp2 ; char tempChar ; for ( int i = 0 ; i < lengthDecode ; i ++ ) { tempChar = binaryData [ i * 2 ] ; temp1 = ( tempChar < BASELENGTH ) ? hexNumberTable [ tempChar ] : - 1 ; if ( temp1 == - 1 ) return null ; tempChar = binaryData [ i * 2 + 1 ] ; temp2 = ( tempChar < BASELENGTH ) ? hexNumberTable [ tempChar ] : - 1 ; if ( temp2 == - 1 ) return null ; decodedData [ i ] = ( byte ) ( ( temp1 << 4 ) | temp2 ) ; } return decodedData ; }
Decode hex string to a byte array
22,574
public static DateTimeValue parse ( Calendar cal , DateTimeType type ) { int sYear = 0 ; int sMonthDay = 0 ; int sTime = 0 ; int sFractionalSecs = 0 ; boolean sPresenceTimezone = false ; int sTimezone ; switch ( type ) { case gYear : case gYearMonth : case date : sYear = cal . get ( Calendar . YEAR ) ; sMonthDay = getMonthDay ( cal ) ; break ; case dateTime : sYear = cal . get ( Calendar . YEAR ) ; sMonthDay = getMonthDay ( cal ) ; case time : sTime = getTime ( cal ) ; sFractionalSecs = cal . get ( Calendar . MILLISECOND ) ; break ; case gMonth : case gMonthDay : case gDay : sMonthDay = getMonthDay ( cal ) ; break ; default : throw new UnsupportedOperationException ( ) ; } sTimezone = getTimeZoneInMinutesOffset ( cal ) ; if ( sTimezone != 0 ) { sPresenceTimezone = true ; } return new DateTimeValue ( type , sYear , sMonthDay , sTime , sFractionalSecs , sPresenceTimezone , sTimezone ) ; }
Encode Date - Time as a sequence of values representing the individual components of the Date - Time .
22,575
protected static void setMonthDay ( int monthDay , Calendar cal ) { int month = monthDay / MONTH_MULTIPLICATOR ; cal . set ( Calendar . MONTH , month - 1 ) ; int day = monthDay - month * MONTH_MULTIPLICATOR ; cal . set ( Calendar . DAY_OF_MONTH , day ) ; }
Sets month and day of the given calendar making use of of the monthDay representation defined in EXI format
22,576
protected static void setTime ( int time , Calendar cal ) { int hour = time / ( 64 * 64 ) ; time -= hour * ( 64 * 64 ) ; int minute = time / 64 ; time -= minute * 64 ; cal . set ( Calendar . HOUR_OF_DAY , hour ) ; cal . set ( Calendar . MINUTE , minute ) ; cal . set ( Calendar . SECOND , time ) ; }
Sets hour minute and second of the given calendar making use of of the time representation defined in EXI format
22,577
private static void addPortMapping ( Integer insecurePort , Integer securePort ) { TO_SECURE_PORT_MAP . put ( insecurePort , securePort ) ; TO_INSECURE_PORT_MAP . put ( securePort , insecurePort ) ; }
Adds an entry to the secure and insecure port map .
22,578
public static int getDefaultPort ( String protocol ) { if ( HTTP_PROTOCOL . equals ( protocol ) ) { return DEFAULT_HTTP_PORT ; } else if ( HTTPS_PROTOCOL . equals ( protocol ) ) { return DEFAULT_HTTPS_PORT ; } else { throw new IllegalArgumentException ( "No known default for " + protocol ) ; } }
Returns the default port for the specified protocol .
22,579
public static int mapPort ( Map < Integer , Integer > mapping , int port ) { Integer mappedPort = mapping . get ( port ) ; if ( mappedPort == null ) throw new RuntimeException ( "Could not map port " + port ) ; return mappedPort ; }
Looks up a corresponding port number from a port mapping .
22,580
public String secureUrl ( HttpServletRequest request , HttpServletResponse response ) throws IOException { String protocol = getProtocol ( request ) ; if ( protocol . equalsIgnoreCase ( HTTP_PROTOCOL ) ) { int port = mapPort ( TO_SECURE_PORT_MAP , getPort ( request ) ) ; try { URI newUri = changeProtocolAndPort ( HTTPS_PROTOCOL , port == DEFAULT_HTTPS_PORT ? - 1 : port , request ) ; return newUri . toString ( ) ; } catch ( URISyntaxException e ) { throw new IllegalStateException ( "Failed to create URI." , e ) ; } } else { throw new UnsupportedProtocolException ( "Cannot build secure url for " + protocol ) ; } }
Returns the secure version of the original URL for the request .
22,581
public String insecureUrl ( HttpServletRequest request , HttpServletResponse response ) throws IOException { String protocol = getProtocol ( request ) ; if ( protocol . equalsIgnoreCase ( HTTPS_PROTOCOL ) ) { int port = mapPort ( TO_INSECURE_PORT_MAP , getPort ( request ) ) ; try { return changeProtocolAndPort ( HTTP_PROTOCOL , port == DEFAULT_HTTP_PORT ? - 1 : port , request ) . toString ( ) ; } catch ( URISyntaxException e ) { throw new IllegalStateException ( "Failed to create URI." , e ) ; } } else { throw new UnsupportedProtocolException ( "Cannot build insecure url for " + protocol ) ; } }
Returns the insecure version of the original URL for the request .
22,582
public void makeSecure ( HttpServletRequest request , HttpServletResponse response ) throws IOException { response . setStatus ( HttpServletResponse . SC_MOVED_PERMANENTLY ) ; response . setHeader ( "Location" , secureUrl ( request , response ) ) ; response . getOutputStream ( ) . flush ( ) ; response . getOutputStream ( ) . close ( ) ; }
Sends a moved perminately redirect to the secure form of the request URL .
22,583
public void makeInsecure ( HttpServletRequest request , HttpServletResponse response ) throws IOException { response . setStatus ( HttpServletResponse . SC_MOVED_PERMANENTLY ) ; response . setHeader ( "Location" , insecureUrl ( request , response ) ) ; response . getOutputStream ( ) . flush ( ) ; response . getOutputStream ( ) . close ( ) ; }
Sends a moved perminately redirect to the insecure form of the request URL .
22,584
public void init ( Configuration conf , Path generatedModel ) throws IOException , InterruptedException { FileSystem fileSystem = FileSystem . get ( conf ) ; for ( Category category : Category . values ( ) ) { wordCountPerCategory . put ( category , new HashMap < String , Integer > ( ) ) ; } Set < String > vocabulary = new HashSet < String > ( ) ; for ( FileStatus fileStatus : fileSystem . globStatus ( generatedModel ) ) { TupleFile . Reader reader = new TupleFile . Reader ( fileSystem , conf , fileStatus . getPath ( ) ) ; Tuple tuple = new Tuple ( reader . getSchema ( ) ) ; while ( reader . next ( tuple ) ) { Integer count = ( Integer ) tuple . get ( "count" ) ; Category category = ( Category ) tuple . get ( "category" ) ; String word = tuple . get ( "word" ) . toString ( ) ; vocabulary . add ( word ) ; tokensPerCategory . put ( category , MapUtils . getInteger ( tokensPerCategory , category , 0 ) + count ) ; wordCountPerCategory . get ( category ) . put ( word , count ) ; } reader . close ( ) ; } V = vocabulary . size ( ) ; }
Read the Naive Bayes Model from HDFS
22,585
public Category classify ( String text ) { StringTokenizer itr = new StringTokenizer ( text ) ; Map < Category , Double > scorePerCategory = new HashMap < Category , Double > ( ) ; double bestScore = Double . NEGATIVE_INFINITY ; Category bestCategory = null ; while ( itr . hasMoreTokens ( ) ) { String token = NaiveBayesGenerate . normalizeWord ( itr . nextToken ( ) ) ; for ( Category category : Category . values ( ) ) { int count = MapUtils . getInteger ( wordCountPerCategory . get ( category ) , token , 0 ) + 1 ; double wordScore = Math . log ( count / ( double ) ( tokensPerCategory . get ( category ) + V ) ) ; double totalScore = MapUtils . getDouble ( scorePerCategory , category , 0. ) + wordScore ; if ( totalScore > bestScore ) { bestScore = totalScore ; bestCategory = category ; } scorePerCategory . put ( category , totalScore ) ; } } return bestCategory ; }
Naive Bayes Text Classification with Add - 1 Smoothing
22,586
public static int numberOf7BitBlocksToRepresent ( final long l ) { if ( l < 0xffffffff ) { return numberOf7BitBlocksToRepresent ( ( int ) l ) ; } else if ( l < 0x800000000L ) { return 5 ; } else if ( l < 0x40000000000L ) { return 6 ; } else if ( l < 0x2000000000000L ) { return 7 ; } else if ( l < 0x100000000000000L ) { return 8 ; } else if ( l < 0x8000000000000000L ) { return 9 ; } else { return 10 ; } }
Returns the least number of 7 bit - blocks that is needed to represent the parameter l . Returns 1 if parameter l is 0 .
22,587
public static MimeBodyPart newMultipartBodyPart ( Multipart multipart ) throws MessagingException { MimeBodyPart mimeBodyPart = new MimeBodyPart ( ) ; mimeBodyPart . setContent ( multipart ) ; return mimeBodyPart ; }
Creates a body part for a multipart .
22,588
public static MimeBodyPart newHtmlAttachmentBodyPart ( URL contentUrl , String contentId ) throws MessagingException { MimeBodyPart mimeBodyPart = new MimeBodyPart ( ) ; mimeBodyPart . setDataHandler ( new DataHandler ( contentUrl ) ) ; if ( contentId != null ) { mimeBodyPart . setHeader ( "Content-ID" , contentId ) ; } return mimeBodyPart ; }
Creates a body part for an attachment that is used by an html body part .
22,589
public static String fileNameForUrl ( URL contentUrl ) { String fileName = null ; Matcher matcher = FILE_NAME_PATTERN . matcher ( contentUrl . getPath ( ) ) ; if ( matcher . find ( ) ) { fileName = matcher . group ( 1 ) ; } return fileName ; }
Returns the content disposition file name for a url . If a file name cannot be parsed from this url then null is returned .
22,590
private void initCommonAndGroupSchemaSerialization ( ) { commonSerializers = getSerializers ( commonSchema , null ) ; commonDeserializers = getDeserializers ( commonSchema , commonSchema , null ) ; groupSerializers = getSerializers ( groupSchema , null ) ; groupDeserializers = getDeserializers ( groupSchema , groupSchema , null ) ; }
This serializers have been defined by the user in an OBJECT field
22,591
private Field checkFieldInAllSchemas ( String name ) throws TupleMRException { Field field = null ; for ( int i = 0 ; i < mrConfig . getIntermediateSchemas ( ) . size ( ) ; i ++ ) { Field fieldInSource = checkFieldInSchema ( name , i ) ; if ( field == null ) { field = fieldInSource ; } else if ( field . getType ( ) != fieldInSource . getType ( ) || field . getObjectClass ( ) != fieldInSource . getObjectClass ( ) ) { throw new TupleMRException ( "The type for field '" + name + "' is not the same in all the sources" ) ; } else if ( fieldInSource . isNullable ( ) ) { field = fieldInSource ; } } return field ; }
Checks that the field with the given name is in all schemas and select a representative field that will be used for serializing . In the case of having a mixture of fields some of them nullable and some others no nullables a nullable Field will be returned .
22,592
public File resolveMavenArtifact ( String artifact ) throws ArtifactResolutionException { ClassLoader oldContext = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( this . getClass ( ) . getClassLoader ( ) ) ; RepositorySystem repoSystem = newRepositorySystem ( ) ; RepositorySystemSession session = newSession ( repoSystem ) ; Artifact artifactObj = new DefaultArtifact ( artifact ) ; RemoteRepository repo = new RemoteRepository ( "cadmium-central" , "default" , remoteMavenRepository ) ; repo . setPolicy ( true , new RepositoryPolicy ( true , RepositoryPolicy . UPDATE_POLICY_ALWAYS , RepositoryPolicy . CHECKSUM_POLICY_WARN ) ) ; repo . setPolicy ( false , new RepositoryPolicy ( true , RepositoryPolicy . UPDATE_POLICY_DAILY , RepositoryPolicy . CHECKSUM_POLICY_WARN ) ) ; ArtifactRequest artifactRequest = new ArtifactRequest ( ) ; artifactRequest . setArtifact ( artifactObj ) ; artifactRequest . addRepository ( repo ) ; ArtifactResult artifactResult = repoSystem . resolveArtifact ( session , artifactRequest ) ; artifactObj = artifactResult . getArtifact ( ) ; return artifactObj . getFile ( ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( oldContext ) ; } }
Fetches a maven artifact and returns a File Object that points to its location .
22,593
protected RepositorySystemSession newSession ( RepositorySystem system ) { MavenRepositorySystemSession session = new MavenRepositorySystemSession ( ) ; LocalRepository localRepo = new LocalRepository ( localRepository ) ; session . setLocalRepositoryManager ( system . newLocalRepositoryManager ( localRepo ) ) ; return session ; }
Creates a new RepositorySystemSession .
22,594
private static Path locateFileInCache ( Configuration conf , String filename ) throws IOException { return new Path ( getInstancesFolder ( FileSystem . get ( conf ) , conf ) , filename ) ; }
Locates a file in the temporal folder
22,595
public static File getWritableDirectoryWithFailovers ( String ... directories ) throws FileNotFoundException { File logDir = null ; for ( String directory : directories ) { if ( directory != null ) { try { logDir = ensureDirectoryWriteable ( new File ( directory ) ) ; } catch ( FileNotFoundException e ) { log . debug ( "Failed to get writeable directory: " + directory , e ) ; continue ; } break ; } } if ( logDir == null ) { throw new FileNotFoundException ( "Could not get a writeable directory!" ) ; } return logDir ; }
Gets the first writable directory that exists or can be created .
22,596
public static File ensureDirectoryWriteable ( File logDir ) throws FileNotFoundException { try { FileUtils . forceMkdir ( logDir ) ; } catch ( IOException e ) { log . debug ( "Failed to create directory " + logDir , e ) ; throw new FileNotFoundException ( "Failed to create directory: " + logDir + " IOException: " + e . getMessage ( ) ) ; } if ( ! logDir . canWrite ( ) ) { log . debug ( "Init param log dir cannot be used!" ) ; throw new FileNotFoundException ( "Directory is not writable: " + logDir ) ; } return logDir ; }
Try s to create a directory and ensures that it is writable .
22,597
public int getPartition ( DatumWrapper < ITuple > key , NullWritable value , int numPartitions ) { if ( numPartitions == 1 ) { return 0 ; } else { ITuple tuple = key . datum ( ) ; String sourceName = tuple . getSchema ( ) . getName ( ) ; Integer schemaId = tupleMRConfig . getSchemaIdByName ( sourceName ) ; if ( schemaId == null ) { throw new RuntimeException ( "Schema name '" + sourceName + "' is unknown. Known schemas are : " + tupleMRConfig . getIntermediateSchemaNames ( ) ) ; } int [ ] fieldsToPartition = serInfo . getPartitionFieldsIndexes ( ) . get ( schemaId ) ; if ( fieldsToPartition . length == 0 ) { throw new RuntimeException ( "Fields to partition is 0. Something has been wrongly configured." ) ; } return ( partialHashCode ( tuple , fieldsToPartition ) & Integer . MAX_VALUE ) % numPartitions ; } }
to perform hashCode of strings
22,598
public int partialHashCode ( ITuple tuple , int [ ] fields ) { int result = 0 ; for ( int field : fields ) { Object o = tuple . get ( field ) ; if ( o == null ) { continue ; } int hashCode ; if ( o instanceof String ) { HELPER_UTF8 . set ( ( String ) o ) ; hashCode = HELPER_UTF8 . hashCode ( ) ; } else if ( o instanceof Text ) { HELPER_UTF8 . set ( ( Text ) o ) ; hashCode = HELPER_UTF8 . hashCode ( ) ; } else if ( o instanceof byte [ ] ) { hashCode = hashBytes ( ( byte [ ] ) o , 0 , ( ( byte [ ] ) o ) . length ) ; } else if ( o instanceof ByteBuffer ) { ByteBuffer buffer = ( ByteBuffer ) o ; int offset = buffer . arrayOffset ( ) + buffer . position ( ) ; int length = buffer . limit ( ) - buffer . position ( ) ; hashCode = hashBytes ( buffer . array ( ) , offset , length ) ; } else { hashCode = o . hashCode ( ) ; } result = result * 31 + hashCode ; } return result ; }
Calculates a combinated hashCode using the specified number of fields .
22,599
public void init ( FilterConfig config ) throws ServletException { if ( config . getInitParameter ( "ignorePrefix" ) != null ) { ignorePath = config . getInitParameter ( "ignorePrefix" ) ; } }
Configures the ignore prefix .