idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
9,100
public static Formdef scan ( AfpInputStream in ) throws IOException { Formdef formdef = new FormdefImpl ( ) ; SF sf ; LinkedList < SF > sfbuffer = null ; while ( ( sf = in . readStructuredField ( ) ) != null ) { log . trace ( "{}" , sf ) ; switch ( sf . eClass ( ) . getClassifierID ( ) ) { case AfplibPackage . ERG : case AfplibPackage . BDT : return null ; case AfplibPackage . EFM : return formdef ; case AfplibPackage . BDG : sfbuffer = new LinkedList < SF > ( ) ; break ; case AfplibPackage . EDG : sfbuffer . add ( sf ) ; formdef . setBDG ( ( SF [ ] ) sfbuffer . toArray ( new SF [ sfbuffer . size ( ) ] ) ) ; sfbuffer = null ; break ; case AfplibPackage . BMM : sfbuffer = new LinkedList < SF > ( ) ; break ; case AfplibPackage . EMM : sfbuffer . add ( sf ) ; formdef . add ( ( SF [ ] ) sfbuffer . toArray ( new SF [ sfbuffer . size ( ) ] ) ) ; sfbuffer = null ; break ; } if ( sfbuffer != null ) sfbuffer . add ( sf ) ; } return null ; }
Scans the input for medium maps and adds to the formdef .
9,101
public static String decode ( String urlString ) { StringBuilder s = new StringBuilder ( ) ; UrlDecoderState state = UrlDecoderState . INITIAL ; int hiNibble = 0 ; int lowNibble = 0 ; int length = urlString . length ( ) ; for ( int i = 0 ; i < length ; i ++ ) { char c = urlString . charAt ( i ) ; switch ( state ) { case INITIAL : if ( c == '%' ) { state = UrlDecoderState . FIRST_HEX ; } else { s . append ( c ) ; } break ; case FIRST_HEX : hiNibble = lookup ( c ) ; state = UrlDecoderState . SECOND_HEX ; break ; case SECOND_HEX : lowNibble = lookup ( c ) ; byte b = ( byte ) ( ( hiNibble << 4 ) | lowNibble ) ; s . append ( ( char ) b ) ; state = UrlDecoderState . INITIAL ; break ; } } return s . toString ( ) ; }
Like java . net . URLDecoder except no conversion of + to space
9,102
public SF next ( ) throws IOException { int remaining = afpData . remaining ( ) ; if ( remaining == 0 ) return null ; if ( remaining < 9 ) throw new IOException ( "trailing garbage at the end of file." ) ; byte buf ; long thisOffset = afpData . position ( ) ; try { if ( leadingLengthBytes == - 1 ) { int leadingLength = 0 ; do { buf = afpData . get ( ) ; leadingLength ++ ; } while ( ( buf & 0xff ) != 0x5a && afpData . remaining ( ) > 0 && leadingLength < 5 ) ; leadingLengthBytes = leadingLength - 1 ; } else { if ( leadingLengthBytes > 0 ) afpData . position ( afpData . position ( ) + leadingLengthBytes ) ; buf = afpData . get ( ) ; } if ( ( buf & 0xff ) != 0x5a ) throw new IOException ( "cannot find 5a magic byte" ) ; data [ 0 ] = buf ; buf = afpData . get ( ) ; data [ 1 ] = buf ; length = ( byte ) buf << 8 ; buf = afpData . get ( ) ; data [ 2 ] = ( byte ) ( buf & 0xff ) ; length |= ( byte ) buf & 0xff ; length -= 2 ; if ( length + 3 > data . length ) throw new IOException ( "length of structured field is too large: " + length ) ; afpData . get ( data , 3 , length ) ; } catch ( BufferUnderflowException e ) { return null ; } SF sf = factory . sf ( data , 0 , getLength ( ) + 2 ) ; sf . setLength ( length + 3 ) ; sf . setOffset ( thisOffset ) ; sf . setNumber ( number ++ ) ; return sf ; }
Reads a new structured field from the mapped file . This method is not thread - safe!
9,103
public static BankCardMagneticTrack from ( final String rawTrackData ) { final Track1FormatB track1 = Track1FormatB . from ( rawTrackData ) ; final Track2 track2 = Track2 . from ( rawTrackData ) ; final Track3 track3 = Track3 . from ( rawTrackData ) ; return new BankCardMagneticTrack ( rawTrackData , track1 , track2 , track3 ) ; }
Parses magnetic track data into a BankCardMagneticTrack object .
9,104
public BankCard toBankCard ( ) { final AccountNumber pan ; if ( track1 . hasAccountNumber ( ) ) { pan = track1 . getAccountNumber ( ) ; } else { pan = track2 . getAccountNumber ( ) ; } final Name name ; if ( track1 . hasName ( ) ) { name = track1 . getName ( ) ; } else { name = new Name ( ) ; } final ExpirationDate expirationDate ; if ( track1 . hasExpirationDate ( ) ) { expirationDate = track1 . getExpirationDate ( ) ; } else { expirationDate = track2 . getExpirationDate ( ) ; } final ServiceCode serviceCode ; if ( track1 . hasServiceCode ( ) ) { serviceCode = track1 . getServiceCode ( ) ; } else { serviceCode = track2 . getServiceCode ( ) ; } final BankCard cardInfo = new BankCard ( pan , expirationDate , name , serviceCode ) ; return cardInfo ; }
Constructs and returns bank card information if all the track data is consistent . That is if any bank card information is repeated in track 1 and track 2 it should be the same data .
9,105
public boolean isConsistentWith ( final BaseBankCardTrackData other ) { if ( this == other ) { return true ; } if ( other == null ) { return false ; } boolean equals = true ; if ( hasAccountNumber ( ) && other . hasAccountNumber ( ) ) { if ( ! getAccountNumber ( ) . equals ( other . getAccountNumber ( ) ) ) { equals = false ; } } if ( hasExpirationDate ( ) && other . hasExpirationDate ( ) ) { if ( ! getExpirationDate ( ) . equals ( other . getExpirationDate ( ) ) ) { equals = false ; } } if ( hasServiceCode ( ) && other . hasServiceCode ( ) ) { if ( ! getServiceCode ( ) . equals ( other . getServiceCode ( ) ) ) { equals = false ; } } return equals ; }
Verifies that the available data is consistent between Track 1 and Track 2 or any other track .
9,106
public static Track1FormatB from ( final String rawTrackData ) { final Matcher matcher = track1FormatBPattern . matcher ( trimToEmpty ( rawTrackData ) ) ; final String rawTrack1Data ; final AccountNumber pan ; final ExpirationDate expirationDate ; final Name name ; final ServiceCode serviceCode ; final String formatCode ; final String discretionaryData ; if ( matcher . matches ( ) ) { rawTrack1Data = getGroup ( matcher , 1 ) ; formatCode = getGroup ( matcher , 2 ) ; pan = new AccountNumber ( getGroup ( matcher , 3 ) ) ; name = new Name ( getGroup ( matcher , 4 ) ) ; expirationDate = new ExpirationDate ( getGroup ( matcher , 5 ) ) ; serviceCode = new ServiceCode ( getGroup ( matcher , 6 ) ) ; discretionaryData = getGroup ( matcher , 7 ) ; } else { rawTrack1Data = null ; formatCode = "" ; pan = new AccountNumber ( ) ; name = new Name ( ) ; expirationDate = new ExpirationDate ( ) ; serviceCode = new ServiceCode ( ) ; discretionaryData = "" ; } return new Track1FormatB ( rawTrack1Data , pan , expirationDate , name , serviceCode , formatCode , discretionaryData ) ; }
Parses magnetic track 1 format B data into a Track1FormatB object .
9,107
public static Track3 from ( final String rawTrackData ) { final Matcher matcher = track3Pattern . matcher ( trimToEmpty ( rawTrackData ) ) ; final String rawTrack3Data ; final String discretionaryData ; if ( matcher . matches ( ) ) { rawTrack3Data = getGroup ( matcher , 1 ) ; discretionaryData = getGroup ( matcher , 2 ) ; } else { rawTrack3Data = null ; discretionaryData = "" ; } return new Track3 ( rawTrack3Data , discretionaryData ) ; }
Parses magnetic track 3 data into a Track3 object .
9,108
public static Track2 from ( final String rawTrackData ) { final Matcher matcher = track2Pattern . matcher ( trimToEmpty ( rawTrackData ) ) ; final String rawTrack2Data ; final AccountNumber pan ; final ExpirationDate expirationDate ; final ServiceCode serviceCode ; final String discretionaryData ; if ( matcher . matches ( ) ) { rawTrack2Data = getGroup ( matcher , 1 ) ; pan = new AccountNumber ( getGroup ( matcher , 2 ) ) ; expirationDate = new ExpirationDate ( getGroup ( matcher , 3 ) ) ; serviceCode = new ServiceCode ( getGroup ( matcher , 4 ) ) ; discretionaryData = getGroup ( matcher , 5 ) ; } else { rawTrack2Data = null ; pan = new AccountNumber ( ) ; expirationDate = new ExpirationDate ( ) ; serviceCode = new ServiceCode ( ) ; discretionaryData = "" ; } return new Track2 ( rawTrack2Data , pan , expirationDate , serviceCode , discretionaryData ) ; }
Parses magnetic track 2 data into a Track2 object .
9,109
void ensureRequiredZnodesExist ( ZooKeeper zookeeper , String znode ) throws KeeperException , InterruptedException { mkdirp ( zookeeper , znode ) ; createIfNotThere ( zookeeper , QUEUE_NODE ) ; createIfNotThere ( zookeeper , POOL_NODE ) ; }
Make sure the required znodes are present on the quorum .
9,110
static String acquireLock ( ZooKeeper zookeeper , String lockNode ) throws KeeperException , InterruptedException { String placeInLine = takeQueueTicket ( zookeeper , lockNode ) ; logger . debug ( "Acquiring lock, waiting in queue: {}." , placeInLine ) ; return waitInLine ( zookeeper , lockNode , placeInLine ) ; }
Try to acquire a lock on for choosing a resource . This method will wait until it has acquired the lock .
9,111
static String takeQueueTicket ( ZooKeeper zookeeper , String lockNode ) throws InterruptedException , KeeperException { String ticket = String . format ( "nr-%014d-%04d" , System . currentTimeMillis ( ) , random . nextInt ( 10000 ) ) ; if ( grabTicket ( zookeeper , lockNode , ticket ) ) { return ticket ; } else { return takeQueueTicket ( zookeeper , lockNode ) ; } }
Take a ticket for the queue . If the ticket was already claimed by another process this method retries until it succeeds .
9,112
static void releaseTicket ( ZooKeeper zookeeper , String lockNode , String ticket ) throws KeeperException , InterruptedException { logger . debug ( "Releasing ticket {}." , ticket ) ; try { zookeeper . delete ( lockNode + "/" + ticket , - 1 ) ; } catch ( KeeperException e ) { if ( e . code ( ) != KeeperException . Code . NONODE ) { throw e ; } } }
Release an acquired lock .
9,113
static String waitInLine ( ZooKeeper zookeeper , String lockNode , String placeInLine ) throws KeeperException , InterruptedException { List < String > children = zookeeper . getChildren ( lockNode , false ) ; Collections . sort ( children ) ; if ( children . size ( ) == 0 ) { logger . warn ( "getChildren() returned empty list, but we created a ticket." ) ; return acquireLock ( zookeeper , lockNode ) ; } boolean lockingTicketExists = children . get ( 0 ) . equals ( LOCKING_TICKET ) ; if ( lockingTicketExists ) { children . remove ( 0 ) ; } int positionInQueue = - 1 ; int i = 0 ; for ( String child : children ) { if ( child . equals ( placeInLine ) ) { positionInQueue = i ; break ; } i ++ ; } if ( positionInQueue < 0 ) { throw new RuntimeException ( "Created node (" + placeInLine + ") not found in getChildren()." ) ; } String placeBeforeUs ; if ( positionInQueue == 0 ) { if ( grabTicket ( zookeeper , lockNode , LOCKING_TICKET ) ) { releaseTicket ( zookeeper , lockNode , placeInLine ) ; return LOCKING_TICKET ; } else { placeBeforeUs = LOCKING_TICKET ; } } else { placeBeforeUs = children . get ( positionInQueue - 1 ) ; } final CountDownLatch latch = new CountDownLatch ( 1 ) ; Stat stat = zookeeper . exists ( lockNode + "/" + placeBeforeUs , event -> { latch . countDown ( ) ; } ) ; if ( stat != null ) { logger . debug ( "Watching place in queue before us ({})" , placeBeforeUs ) ; latch . await ( ) ; } return waitInLine ( zookeeper , lockNode , placeInLine ) ; }
Wait in the queue until the znode in front of us changes .
9,114
static boolean grabTicket ( ZooKeeper zookeeper , String lockNode , String ticket ) throws InterruptedException , KeeperException { try { zookeeper . create ( lockNode + "/" + ticket , new byte [ 0 ] , ZooDefs . Ids . OPEN_ACL_UNSAFE , CreateMode . EPHEMERAL ) ; } catch ( KeeperException e ) { if ( e . code ( ) == KeeperException . Code . NODEEXISTS ) { logger . debug ( "Failed to claim ticket {}." , ticket ) ; return false ; } else { throw e ; } } logger . debug ( "Claimed ticket {}." , ticket ) ; return true ; }
Grab a ticket in the queue .
9,115
int claimResource ( ZooKeeper zookeeper , String poolNode , int poolSize ) throws KeeperException , InterruptedException { logger . debug ( "Trying to claim a resource." ) ; List < String > claimedResources = zookeeper . getChildren ( poolNode , false ) ; if ( claimedResources . size ( ) >= poolSize ) { logger . debug ( "No resources available at the moment (pool size: {}), waiting." , poolSize ) ; final CountDownLatch latch = new CountDownLatch ( 1 ) ; zookeeper . getChildren ( poolNode , event -> latch . countDown ( ) ) ; latch . await ( ) ; return claimResource ( zookeeper , poolNode , poolSize ) ; } for ( int i = 0 ; i < poolSize ; i ++ ) { String resourcePath = Integer . toString ( i ) ; if ( ! claimedResources . contains ( resourcePath ) ) { String node ; try { logger . debug ( "Trying to claim seemingly available resource {}." , resourcePath ) ; node = zookeeper . create ( poolNode + "/" + resourcePath , new byte [ 0 ] , ZooDefs . Ids . OPEN_ACL_UNSAFE , CreateMode . EPHEMERAL ) ; } catch ( KeeperException e ) { if ( e . code ( ) == KeeperException . Code . NODEEXISTS ) { continue ; } else { throw e ; } } zookeeper . exists ( node , event -> { if ( event . getType ( ) == EventType . NodeDeleted ) { logger . debug ( "Resource-claim node unexpectedly deleted ({})" , resource ) ; close ( true ) ; } } ) ; logger . debug ( "Successfully claimed resource {}." , resourcePath ) ; return i ; } } return claimResource ( zookeeper , poolNode , poolSize ) ; }
Try to claim an available resource from the resource pool .
9,116
private void relinquishResource ( ZooKeeper zookeeper , String poolNode , int resource ) { logger . debug ( "Relinquishing claimed resource {}." , resource ) ; try { zookeeper . delete ( poolNode + "/" + Integer . toString ( resource ) , - 1 ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } catch ( KeeperException e ) { logger . error ( "Failed to remove resource claim node {}/{}" , poolNode , resource ) ; } }
Relinquish a claimed resource .
9,117
public static int get ( ZooKeeper zookeeper , String znode ) throws IOException { try { Stat stat = zookeeper . exists ( znode + CLUSTER_ID_NODE , false ) ; if ( stat == null ) { mkdirp ( zookeeper , znode ) ; create ( zookeeper , znode + CLUSTER_ID_NODE , String . valueOf ( DEFAULT_CLUSTER_ID ) . getBytes ( ) ) ; } byte [ ] id = zookeeper . getData ( znode + CLUSTER_ID_NODE , false , null ) ; return Integer . valueOf ( new String ( id ) ) ; } catch ( KeeperException e ) { throw new IOException ( String . format ( "Failed to retrieve the cluster ID from the ZooKeeper quorum. " + "Expected to find it at znode %s." , znode + CLUSTER_ID_NODE ) , e ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new IOException ( e ) ; } }
Retrieves the numeric cluster ID from the ZooKeeper quorum .
9,118
static List < String > pathParts ( String path ) { String [ ] pathParts = path . split ( "/" ) ; List < String > parts = new ArrayList < > ( pathParts . length ) ; String pathSoFar = "" ; for ( String pathPart : pathParts ) { if ( ! pathPart . equals ( "" ) ) { pathSoFar += "/" + pathPart ; parts . add ( pathSoFar ) ; } } return parts ; }
Parse a znode path and return a list containing the full paths to its constituent directories .
9,119
public synchronized static IDGenerator generatorFor ( int generatorId , int clusterId , Mode mode ) { assertParameterWithinBounds ( "generatorId" , 0 , Blueprint . MAX_GENERATOR_ID , generatorId ) ; assertParameterWithinBounds ( "clusterId" , 0 , Blueprint . MAX_CLUSTER_ID , clusterId ) ; String generatorAndCluster = String . format ( "%d_%d" , generatorId , clusterId ) ; if ( ! instances . containsKey ( generatorAndCluster ) ) { GeneratorIdentityHolder identityHolder = LocalGeneratorIdentity . with ( clusterId , generatorId ) ; instances . putIfAbsent ( generatorAndCluster , new BaseUniqueIDGenerator ( identityHolder , mode ) ) ; } return instances . get ( generatorAndCluster ) ; }
Return the UniqueIDGenerator instance for this specific generator - ID cluster - ID combination . If one was already created that is returned .
9,120
private ZooKeeper connect ( String quorumAddresses ) throws IOException { final CountDownLatch latch = new CountDownLatch ( 1 ) ; ZooKeeper zookeeper ; zookeeper = new ZooKeeper ( quorumAddresses , ( int ) SECONDS . toMillis ( 10 ) , watchedEvent -> { if ( watchedEvent . getState ( ) == Watcher . Event . KeeperState . SyncConnected ) { latch . countDown ( ) ; } } ) ; boolean successfullyConnected = false ; try { successfullyConnected = latch . await ( 11 , SECONDS ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } if ( ! successfullyConnected ) { throw new IOException ( String . format ( "Connection to ZooKeeper quorum timed out after %d seconds." , CONNECTION_TIMEOUT ) ) ; } return zookeeper ; }
Connect to the ZooKeeper quorum or timeout if it is unreachable .
9,121
byte [ ] popOne ( ) throws GeneratorException { try { return idStack . pop ( ) ; } catch ( NoSuchElementException e ) { idStack . addAll ( generator . batch ( batchSize ) ) ; return popOne ( ) ; } }
Grab a single ID from the stack . If the stack is empty load up a new batch from the wrapped generator .
9,122
public static byte [ ] build ( Blueprint blueprint ) { ByteBuffer bb = ByteBuffer . allocate ( 8 ) ; switch ( blueprint . getMode ( ) ) { case SPREAD : long reverseTimestamp = Long . reverse ( blueprint . getTimestamp ( ) ) ; bb . putLong ( reverseTimestamp ) ; break ; case TIME_SEQUENTIAL : long timestamp = blueprint . getTimestamp ( ) ; bb . putLong ( timestamp << 22 ) ; break ; } byte [ ] tsBytes = bb . array ( ) ; int or = tsBytes [ 5 ] | ( byte ) blueprint . getSequence ( ) ; tsBytes [ 5 ] = ( byte ) or ; int flagGeneratorCluster = blueprint . getGeneratorId ( ) << 4 ; flagGeneratorCluster += blueprint . getClusterId ( ) ; flagGeneratorCluster += blueprint . getMode ( ) . getModeMask ( ) << 12 ; tsBytes [ 7 ] = ( byte ) flagGeneratorCluster ; flagGeneratorCluster >>>= 8 ; tsBytes [ 6 ] = ( byte ) flagGeneratorCluster ; return tsBytes ; }
Perform all the byte mangling needed to create the eight byte ID .
9,123
private void ensureAccessible ( Key < ? > key , GinjectorBindings parent , GinjectorBindings child ) { if ( parent != null && ! child . equals ( parent ) && ! child . isBound ( key ) ) { PrettyPrinter . log ( logger , TreeLogger . DEBUG , "In %s: inheriting binding for %s from the parent %s" , child , key , parent ) ; Context context = Context . format ( "Inheriting %s from parent" , key ) ; child . addBinding ( key , bindingFactory . getParentBinding ( key , parent , context ) ) ; } }
Ensure that the binding for key which exists in the parent Ginjector is also available to the child Ginjector .
9,124
public Key < ? > getKey ( FieldLiteral < ? > field ) { return getKey ( field . getFieldType ( ) . getType ( ) , field . getBindingAnnotation ( ) ) ; }
Returns a key based on the passed field taking any binding annotations into account .
9,125
private Key < ? > getKey ( Type type , Annotation bindingAnnotation ) throws ProvisionException { if ( bindingAnnotation == null ) { return Key . get ( type ) ; } else { return Key . get ( type , bindingAnnotation ) ; } }
Gets the Guice binding key for a given Java type with optional annotations .
9,126
public Collection < Dependency > getMemberInjectionDependencies ( Key < ? > typeKey , TypeLiteral < ? > type ) { Set < Dependency > required = new LinkedHashSet < Dependency > ( ) ; for ( MethodLiteral < ? , Method > method : memberCollector . getMethods ( type ) ) { required . addAll ( getDependencies ( typeKey , method ) ) ; } for ( FieldLiteral < ? > field : memberCollector . getFields ( type ) ) { Key < ? > key = getKey ( field ) ; required . add ( new Dependency ( typeKey , key , isOptional ( field ) , false , "member injection of " + field ) ) ; } return required ; }
Collects and returns all keys required to member - inject the given class .
9,127
public Collection < Dependency > getDependencies ( Key < ? > typeKey , MethodLiteral < ? , ? > method ) { String context ; if ( method . isConstructor ( ) ) { context = "@Inject constructor of " + method . getDeclaringType ( ) ; } else if ( typeKey == Dependency . GINJECTOR ) { context = "Member injector " + method ; } else { context = "Member injection via " + method ; } Set < Dependency > required = new LinkedHashSet < Dependency > ( ) ; for ( Key < ? > key : method . getParameterKeys ( ) ) { required . add ( new Dependency ( typeKey , key , isOptional ( method ) , false , context ) ) ; } return required ; }
Collects and returns all keys required to inject the given method .
9,128
public static < T > FieldLiteral < T > get ( Field field , TypeLiteral < T > declaringType ) { Preconditions . checkArgument ( field . getDeclaringClass ( ) . equals ( declaringType . getRawType ( ) ) , "declaringType (%s) must be the type literal where field was declared (%s)!" , declaringType , field . getDeclaringClass ( ) ) ; return new FieldLiteral < T > ( field , declaringType ) ; }
Returns a new field literal based on the passed field and its declaring type .
9,129
public PlayerGuessResult displayNextCard ( RelationshipToPreviousCard guess ) { Card card = deck . turnCard ( ) ; grid . nextCard ( card ) ; cardsTurnedPlusOne ++ ; RelationshipToPreviousCard actualRelationshipToPrevious = getRelationshipToPreviousCard ( card ) ; previous = card ; if ( actualRelationshipToPrevious == null ) { return null ; } return actualRelationshipToPrevious . equals ( guess ) ? PlayerGuessResult . RIGHT : PlayerGuessResult . WRONG ; }
Turn the next card .
9,130
protected final < T > GinAnnotatedBindingBuilder < T > bind ( Class < T > clazz ) { return binder . bind ( clazz ) ; }
Everything below is copied from AbstractGinModule
9,131
public static boolean isConstantKey ( Key < ? > key ) { Type type = key . getTypeLiteral ( ) . getType ( ) ; if ( ! ( type instanceof Class ) ) { return false ; } Class clazz = ( Class ) type ; return clazz == String . class || clazz == Class . class || clazz . isPrimitive ( ) || Number . class . isAssignableFrom ( clazz ) || Character . class . isAssignableFrom ( clazz ) || Boolean . class . isAssignableFrom ( clazz ) || clazz . isEnum ( ) ; }
Returns true if the provided key is a valid constant key i . e . if a constant binding can be legally created for it .
9,132
public static void log ( TreeLogger logger , TreeLogger . Type type , String formatString , Object ... args ) { if ( logger . isLoggable ( type ) ) { logger . log ( type , format ( formatString , args ) ) ; } }
Log a pretty - printed message if the given log level is active . The message is only formatted if it will be logged .
9,133
private static Object formatObject ( Object object ) { if ( object instanceof Class ) { return formatArg ( ( Class < ? > ) object ) ; } else if ( object instanceof Key ) { return formatArg ( ( Key < ? > ) object ) ; } else if ( object instanceof List ) { List < ? > list = ( List < ? > ) object ; boolean allDependencies = true ; for ( Object entry : list ) { if ( ! ( entry instanceof Dependency ) ) { allDependencies = false ; break ; } } if ( allDependencies ) { return formatArg ( ( List < Dependency > ) list ) ; } else { return object ; } } else { return object ; } }
Pretty - print a single object .
9,134
private String [ ] extractConstructorParameters ( Key < ? > factoryKey , TypeLiteral < ? > implementation , Constructor constructor , List < Key < ? > > methodParams , Errors errors , Set < Dependency > dependencyCollector ) throws ErrorsException { List < TypeLiteral < ? > > ctorParams = implementation . getParameterTypes ( constructor ) ; Annotation [ ] [ ] ctorParamAnnotations = constructor . getParameterAnnotations ( ) ; int p = 0 ; String [ ] parameterNames = new String [ ctorParams . size ( ) ] ; Set < Key < ? > > keySet = new LinkedHashSet < Key < ? > > ( ) ; for ( TypeLiteral < ? > ctorParam : ctorParams ) { Key < ? > ctorParamKey = getKey ( ctorParam , constructor , ctorParamAnnotations [ p ] , errors ) ; if ( ctorParamKey . getAnnotationType ( ) == Assisted . class ) { if ( ! keySet . add ( ctorParamKey ) ) { errors . addMessage ( PrettyPrinter . format ( "%s has more than one parameter of type %s annotated with @Assisted(\"%s\"). " + "Please specify a unique value with the annotation to avoid confusion." , implementation , ctorParamKey . getTypeLiteral ( ) . getType ( ) , ( ( Assisted ) ctorParamKey . getAnnotation ( ) ) . value ( ) ) ) ; } int location = methodParams . indexOf ( ctorParamKey ) ; Preconditions . checkState ( location != - 1 ) ; parameterNames [ p ] = ReflectUtil . formatParameterName ( location ) ; } else { dependencyCollector . add ( new Dependency ( factoryKey , ctorParamKey , false , true , constructor . toString ( ) ) ) ; } p ++ ; } return parameterNames ; }
Matches constructor parameters to method parameters for injection and records remaining parameters as required keys .
9,135
public void pruneInvalidOptional ( DependencyExplorerOutput output , InvalidKeys invalidKeys ) { DependencyGraph . GraphPruner prunedGraph = new DependencyGraph . GraphPruner ( output . getGraph ( ) ) ; for ( Key < ? > key : invalidKeys . getInvalidOptionalKeys ( ) ) { prunedGraph . remove ( key ) ; output . removeBinding ( key ) ; } output . setGraph ( prunedGraph . update ( ) ) ; }
Prune all of the invalid optional keys from the graph . After this method all of the keys remaining in the graph are resolvable .
9,136
private Map < Key < ? > , String > getAllInvalidKeys ( DependencyExplorerOutput output ) { Map < Key < ? > , String > invalidKeys = new LinkedHashMap < Key < ? > , String > ( ) ; for ( Entry < Key < ? > , String > error : output . getBindingErrors ( ) ) { invalidKeys . put ( error . getKey ( ) , "Unable to create or inherit binding: " + error . getValue ( ) ) ; } GinjectorBindings origin = output . getGraph ( ) . getOrigin ( ) ; for ( Key < ? > key : output . getImplicitlyBoundKeys ( ) ) { if ( origin . isBoundLocallyInChild ( key ) ) { GinjectorBindings child = origin . getChildWhichBindsLocally ( key ) ; Binding childBinding = child . getBinding ( key ) ; PrettyPrinter . log ( logger , TreeLogger . DEBUG , "Marking the key %s as bound in the ginjector %s (implicitly), and in the child" + " %s (%s)" , key , origin , child , childBinding . getContext ( ) ) ; invalidKeys . put ( key , PrettyPrinter . format ( "Already bound in child Ginjector %s. Consider exposing it?" , child ) ) ; } } return invalidKeys ; }
Returns a map from keys that are invalid to errors explaining why each key is invalid .
9,137
private Set < Key < ? > > getKeysToRemove ( DependencyGraph graph , Collection < Key < ? > > discovered ) { Set < Key < ? > > toRemove = new LinkedHashSet < Key < ? > > ( ) ; while ( ! discovered . isEmpty ( ) ) { toRemove . addAll ( discovered ) ; discovered = getRequiredSourcesTargeting ( graph , discovered ) ; discovered . removeAll ( toRemove ) ; } return toRemove ; }
Given the set of optional keys that had problems compute the set of all optional keys that should be removed . This may include additional keys for instance if an optional key requires an invalid key than the optional key should also be removed .
9,138
private Collection < Key < ? > > getRequiredSourcesTargeting ( DependencyGraph graph , Iterable < Key < ? > > targets ) { Collection < Key < ? > > requiredSources = new LinkedHashSet < Key < ? > > ( ) ; for ( Key < ? > target : targets ) { for ( Dependency edge : graph . getDependenciesTargeting ( target ) ) { if ( ! edge . isOptional ( ) ) { PrettyPrinter . log ( logger , TreeLogger . DEBUG , "Removing the key %s because of %s" , edge . getSource ( ) , edge ) ; requiredSources . add ( edge . getSource ( ) ) ; } } } return requiredSources ; }
Returns all of the source keys that have a required dependency on any key in the target set .
9,139
public Void visitScope ( Scope scope ) { messages . add ( new Message ( PrettyPrinter . format ( "Explicit scope unsupported: key=%s scope=%s" , targetKey , scope ) ) ) ; return null ; }
strange to be using the Guice Scope instead of javax . inject . Scope
9,140
public static String getUserPackageName ( TypeLiteral < ? > typeLiteral ) { Map < String , Class < ? > > packageNames = new LinkedHashMap < String , Class < ? > > ( ) ; getTypePackageNames ( typeLiteral . getType ( ) , packageNames ) ; if ( packageNames . size ( ) == 0 ) { return typeLiteral . getRawType ( ) . getPackage ( ) . getName ( ) ; } else if ( packageNames . size ( ) == 1 ) { return packageNames . keySet ( ) . iterator ( ) . next ( ) ; } else { StringBuilder packageNamesListBuilder = new StringBuilder ( ) ; for ( Class < ? > entry : packageNames . values ( ) ) { packageNamesListBuilder . append ( entry . getCanonicalName ( ) ) . append ( "\n" ) ; } throw new IllegalArgumentException ( PrettyPrinter . format ( "Unable to inject an instance of %s because it references protected classes" + " from multiple packages:\n%s" , typeLiteral , packageNamesListBuilder ) ) ; } }
Return the name of the package from which the given type can be used .
9,141
private static void getClassPackageNames ( Class < ? > clazz , Map < String , Class < ? > > packageNames ) { if ( isPrivate ( clazz ) ) { throw new IllegalArgumentException ( PrettyPrinter . format ( "Unable to inject an instance of %s because it is a private class." , clazz ) ) ; } else if ( ! isPublic ( clazz ) ) { packageNames . put ( clazz . getPackage ( ) . getName ( ) , clazz ) ; } Class < ? > enclosingClass = clazz . getEnclosingClass ( ) ; if ( enclosingClass != null ) { getClassPackageNames ( enclosingClass , packageNames ) ; } }
Visits classes to collect package names .
9,142
private static void getParameterizedTypePackageNames ( ParameterizedType type , Map < String , Class < ? > > packageNames ) { for ( Type argumentType : type . getActualTypeArguments ( ) ) { getTypePackageNames ( argumentType , packageNames ) ; } getTypePackageNames ( type . getRawType ( ) , packageNames ) ; Type ownerType = type . getOwnerType ( ) ; if ( ownerType != null ) { getTypePackageNames ( ownerType , packageNames ) ; } }
Visits parameterized types to collect package names .
9,143
private static void getTypeVariablePackageNames ( TypeVariable type , Map < String , Class < ? > > packageNames ) { for ( Type boundType : type . getBounds ( ) ) { getTypePackageNames ( boundType , packageNames ) ; } }
Visits type variables to collect package names .
9,144
private static void getWildcardTypePackageNames ( WildcardType type , Map < String , Class < ? > > packageNames ) { for ( Type boundType : type . getUpperBounds ( ) ) { getTypePackageNames ( boundType , packageNames ) ; } for ( Type boundType : type . getLowerBounds ( ) ) { getTypePackageNames ( boundType , packageNames ) ; } }
Visits wildcard types to collect package names .
9,145
public SourceSnippet getCreationStatements ( NameGenerator nameGenerator , List < InjectorMethod > methodsOutput ) throws NoSourceNameException { String moduleSourceName = ReflectUtil . getSourceName ( moduleType ) ; String createModule = "new " + moduleSourceName + "()" ; String type = ReflectUtil . getSourceName ( targetKey . getTypeLiteral ( ) ) ; return new SourceSnippetBuilder ( ) . append ( type ) . append ( " result = " ) . append ( methodCallUtil . createMethodCallWithInjection ( providerMethod , createModule , nameGenerator , methodsOutput ) ) . build ( ) ; }
provider methods .
9,146
public String getGetterMethodPackage ( ) { Binding childBinding = childBindings . getBinding ( key ) ; if ( childBinding == null ) { errorManager . logError ( "No child binding found in %s for %s." , childBindings , key ) ; return "" ; } else { return childBinding . getGetterMethodPackage ( ) ; } }
The getter must be placed in the same package as the child getter to ensure that its return type is visible .
9,147
public String getGetterMethodPackage ( ) { Binding parentBinding = parentBindings . getBinding ( key ) ; if ( parentBinding == null ) { errorManager . logError ( "No parent binding found in %s for %s." , parentBindings , key ) ; return "" ; } else { return parentBinding . getGetterMethodPackage ( ) ; } }
The getter must be placed in the same package as the parent getter to ensure that its return type is visible .
9,148
public GinjectorBindings getInstallPosition ( Key < ? > key ) { Preconditions . checkNotNull ( positions , "Must call position before calling getInstallPosition(Key<?>)" ) ; GinjectorBindings position = installOverrides . get ( key ) ; if ( position == null ) { position = positions . get ( key ) ; } return position ; }
Returns the Ginjector where the binding for key should be placed or null if the key was removed from the dependency graph earlier .
9,149
private void computeInitialPositions ( ) { positions . putAll ( output . getPreExistingLocations ( ) ) ; for ( Key < ? > key : output . getImplicitlyBoundKeys ( ) ) { GinjectorBindings initialPosition = computeInitialPosition ( key ) ; PrettyPrinter . log ( logger , TreeLogger . DEBUG , PrettyPrinter . format ( "Initial highest visible position of %s is %s" , key , initialPosition ) ) ; positions . put ( key , initialPosition ) ; } }
Place an initial guess in the position map that places each implicit binding as high as possible in the injector tree without causing double binding .
9,150
private GinjectorBindings computeInitialPosition ( Key < ? > key ) { GinjectorBindings initialPosition = output . getGraph ( ) . getOrigin ( ) ; boolean pinned = initialPosition . isPinned ( key ) ; if ( pinned ) { PrettyPrinter . log ( logger , TreeLogger . DEBUG , PrettyPrinter . format ( "Forcing %s to be installed in %s due to a pin." , key , initialPosition ) ) ; installOverrides . put ( key , initialPosition ) ; } while ( canExposeKeyFrom ( key , initialPosition , pinned ) ) { PrettyPrinter . log ( logger , TreeLogger . SPAM , "Moving the highest visible position of %s from %s to %s." , key , initialPosition , initialPosition . getParent ( ) ) ; initialPosition = initialPosition . getParent ( ) ; } return initialPosition ; }
Returns the highest injector that we could possibly position the key at without causing a double binding .
9,151
private boolean canExposeKeyFrom ( Key < ? > key , GinjectorBindings child , boolean pinned ) { GinjectorBindings parent = child . getParent ( ) ; if ( parent == null ) { return false ; } else if ( parent . isBoundLocallyInChild ( key ) ) { return false ; } else if ( pinned ) { Binding binding = parent . getBinding ( key ) ; if ( binding == null ) { return false ; } else if ( ! ( binding instanceof ExposedChildBinding ) ) { throw new RuntimeException ( "Unexpected binding shadowing a pinned binding: " + binding ) ; } else { ExposedChildBinding exposedChildBinding = ( ExposedChildBinding ) binding ; if ( exposedChildBinding . getChildBindings ( ) != child ) { throw new RuntimeException ( "Unexpected exposed child binding shadowing a pinned binding: " + binding ) ; } else { return true ; } } } else { return true ; } }
Tests whether a key from the given child injector can be made visible in its parent . For pinned keys this means that they re exposed to the parent ; for keys that aren t pinned it means that there s no other constraint preventing them from floating up .
9,152
private void calculateExactPositions ( ) { while ( ! workqueue . isEmpty ( ) ) { Key < ? > key = workqueue . iterator ( ) . next ( ) ; workqueue . remove ( key ) ; Set < GinjectorBindings > injectors = getSourceGinjectors ( key ) ; injectors . add ( positions . get ( key ) ) ; GinjectorBindings newPosition = lowest ( injectors ) ; GinjectorBindings oldPosition = positions . put ( key , newPosition ) ; if ( oldPosition != newPosition ) { PrettyPrinter . log ( logger , TreeLogger . DEBUG , "Moved the highest visible position of %s from %s to %s, the lowest injector of %s." , key , oldPosition , newPosition , injectors ) ; for ( Dependency dependency : output . getGraph ( ) . getDependenciesTargeting ( key ) ) { PrettyPrinter . log ( logger , TreeLogger . DEBUG , "Re-enqueuing %s due to %s" , dependency . getSource ( ) , dependency ) ; workqueue . add ( dependency . getSource ( ) ) ; } } } }
Iterates on the position equation updating each binding in the queue and re - queueing nodes that depend on any node we move . This will always terminate since we only re - queue when we make a change and there are a finite number of entries in the injector hierarchy .
9,153
private Set < GinjectorBindings > getSourceGinjectors ( Key < ? > key ) { Set < GinjectorBindings > sourceInjectors = new LinkedHashSet < GinjectorBindings > ( ) ; for ( Dependency dep : output . getGraph ( ) . getDependenciesOf ( key ) ) { sourceInjectors . add ( positions . get ( dep . getTarget ( ) ) ) ; } return sourceInjectors ; }
Returns the injectors where the dependencies for node are currently placed .
9,154
public static SourceSnippet callChildGetter ( final GinjectorBindings childBindings , final Key < ? > key ) { return new SourceSnippet ( ) { public String getSource ( InjectorWriteContext writeContext ) { return writeContext . callChildGetter ( childBindings , key ) ; } } ; }
Creates a snippet that evaluates to an injected instance of the given key as produced by the given child .
9,155
public static SourceSnippet callMethod ( final String methodName , final String fragmentPackageName , final Iterable < String > parameters ) { return new SourceSnippet ( ) { public String getSource ( InjectorWriteContext writeContext ) { return writeContext . callMethod ( methodName , fragmentPackageName , parameters ) ; } } ; }
Creates a snippet that evaluates to an invocation of the named method on the given package fragment .
9,156
public static SourceSnippet callParentGetter ( final Key < ? > key , final GinjectorBindings parentBindings ) { return new SourceSnippet ( ) { public String getSource ( InjectorWriteContext writeContext ) { return writeContext . callParentGetter ( key , parentBindings ) ; } } ; }
Creates a snippet that evaluates to an injected instance of the given key as produced by the given parent injector .
9,157
public static SourceSnippet forText ( final String text ) { return new SourceSnippet ( ) { public String getSource ( InjectorWriteContext writeContext ) { return text ; } } ; }
Creates a snippet that generates a constant text string .
9,158
public String getFragmentClassName ( String injectorClassName , FragmentPackageName fragmentPackageName ) { Preconditions . checkArgument ( ! injectorClassName . contains ( "." ) , "The injector class must be a simple name, but it was \"%s\"" , injectorClassName ) ; return injectorClassName + "_fragment" ; }
Computes the name of a single fragment of a Ginjector .
9,159
public static String replaceLast ( String source , char toReplace , char with ) { StringBuilder sb = new StringBuilder ( source ) ; int index = sb . lastIndexOf ( String . valueOf ( toReplace ) ) ; if ( index != - 1 ) { sb . setCharAt ( index , with ) ; } return sb . toString ( ) ; }
Static for access from enum .
9,160
public DependencyExplorerOutput explore ( GinjectorBindings origin ) { DependencyExplorerOutput output = new DependencyExplorerOutput ( ) ; DependencyGraph . Builder builder = new DependencyGraph . Builder ( origin ) ; for ( Dependency edge : origin . getDependencies ( ) ) { Preconditions . checkState ( Dependency . GINJECTOR . equals ( edge . getSource ( ) ) || origin . isBound ( edge . getSource ( ) ) , "Expected non-null source %s to be bound in origin!" , edge . getSource ( ) ) ; builder . addEdge ( edge ) ; if ( ! edge . getSource ( ) . equals ( Dependency . GINJECTOR ) && visited . add ( edge . getSource ( ) ) ) { PrettyPrinter . log ( logger , TreeLogger . DEBUG , "Registering %s as available at %s because of the dependency %s" , edge . getSource ( ) , origin , edge ) ; output . preExistingBindings . put ( edge . getSource ( ) , locateHighestAccessibleSource ( edge . getSource ( ) , origin ) ) ; } PrettyPrinter . log ( logger , TreeLogger . DEBUG , "Exploring from %s in %s because of the dependency %s" , edge . getTarget ( ) , origin , edge ) ; visit ( edge . getTarget ( ) , builder , output , origin ) ; } output . setGraph ( builder . build ( ) ) ; return output ; }
Explore the unresolved dependencies in the origin Ginjector and create the corresponding dependency graph . Also gathers information about key in the dependency graph such as which Ginjector it is already available on or what implicit binding was created for it .
9,161
private GinjectorBindings locateHighestAccessibleSource ( Key < ? > key , GinjectorBindings origin ) { if ( ! origin . isBound ( key ) && origin . isPinned ( key ) ) { return null ; } GinjectorBindings source = null ; for ( GinjectorBindings iter = origin ; iter != null ; iter = iter . getParent ( ) ) { if ( iter . isBound ( key ) || iter . isPinned ( key ) ) { source = iter ; } } return source ; }
Find the highest binding in the Ginjector tree that could be used to supply the given key .
9,162
public boolean findAndReportCycles ( DependencyGraph graph ) { this . graph = graph ; cycleDetected = false ; visitedEdge = new LinkedHashMap < Key < ? > , Dependency > ( graph . size ( ) ) ; for ( Key < ? > key : graph . getAllKeys ( ) ) { visit ( key , null ) ; } return cycleDetected ; }
Detects cycles in the given graph .
9,163
static List < Dependency > rootCycleAt ( List < Dependency > cycle , Key < ? > key ) { for ( int i = 0 ; i < cycle . size ( ) ; ++ i ) { if ( key . equals ( cycle . get ( i ) . getSource ( ) ) ) { List < Dependency > returnValue = new ArrayList < Dependency > ( ) ; returnValue . addAll ( cycle . subList ( i , cycle . size ( ) ) ) ; returnValue . addAll ( cycle . subList ( 0 , i ) ) ; return returnValue ; } } return cycle ; }
Attempts to root the given dependency cycle at the given key . If the key is present in the cycle rotates the dependency cycle so that the key is the first source . Otherwise returns the cycle unchanged .
9,164
public List < TypeLiteral < ? > > getParameterTypes ( ) { if ( parameterTypes == null ) { parameterTypes = getDeclaringType ( ) . getParameterTypes ( getMember ( ) ) ; } return parameterTypes ; }
Returns this method s parameter types if appropriate parametrized with the declaring class s type parameters .
9,165
private ClassLoader createGinClassLoader ( TreeLogger logger , GeneratorContext context ) { Set < String > exceptions = new LinkedHashSet < String > ( ) ; exceptions . add ( "com.google.inject" ) ; exceptions . add ( "javax.inject" ) ; exceptions . add ( "com.google.gwt.inject.client" ) ; exceptions . add ( "com.google.gwt.core.client" ) ; exceptions . add ( "com.google.gwt.core.client.impl" ) ; exceptions . addAll ( getValuesForProperty ( "gin.classloading.exceptedPackages" ) ) ; return new GinBridgeClassLoader ( context , logger , exceptions ) ; }
Creates a new gin - specific class loader that will load GWT and non - GWT types such that there is never a conflict especially with super source .
9,166
Class < ? > loadClass ( String requestedClass , boolean initialize ) throws ClassNotFoundException { String binaryName = requestedClass ; while ( true ) { try { return Class . forName ( binaryName , initialize , classLoader ) ; } catch ( ClassNotFoundException e ) { if ( ! binaryName . contains ( "." ) ) { throw e ; } else { binaryName = replaceLastPeriodWithDollar ( binaryName ) ; } } } }
Package accessible for testing .
9,167
void write ( GinjectorBindings bindings ) throws UnableToCompleteException { TypeLiteral < ? > ginjectorInterface = bindings . getGinjectorInterface ( ) ; String implClassName = ginjectorNameGenerator . getClassName ( bindings ) ; if ( implClassName . contains ( "." ) ) { errorManager . logError ( "Internal error: the injector class name \"%s\" contains a full stop." , implClassName ) ; } String packageName = ReflectUtil . getUserPackageName ( TypeLiteral . get ( bindings . getModule ( ) ) ) ; PrintWriter printWriter = ctx . tryCreate ( logger , packageName , implClassName ) ; if ( printWriter == null ) { return ; } ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory ( packageName , implClassName ) ; SourceWriter writer = composerFactory . createSourceWriter ( ctx , printWriter ) ; FragmentMap fragments = new FragmentMap ( bindings , packageName , implClassName , fragmentOutputterFactory ) ; outputBindings ( bindings , fragments , writer ) ; errorManager . checkForError ( ) ; fragments . commitAll ( ) ; writer . commit ( logger ) ; }
Writes the Ginjector class for the given bindings object and all its package - specific fragments .
9,168
private void outputInterfaceField ( GinjectorBindings bindings , SourceWriteUtil sourceWriteUtil , SourceWriter writer ) { if ( bindings . getParent ( ) != null ) { return ; } Class < ? > boundGinjectorInterface = getBoundGinjector ( bindings ) ; if ( boundGinjectorInterface == null ) { errorManager . logError ( "Injector interface not bound in the root module." ) ; return ; } NameGenerator nameGenerator = bindings . getNameGenerator ( ) ; String fieldName = nameGenerator . getGinjectorInterfaceFieldName ( ) ; String getterName = nameGenerator . getGinjectorInterfaceGetterMethodName ( ) ; writer . beginJavaDocComment ( ) ; writer . print ( "The implementation of " + boundGinjectorInterface ) ; writer . endJavaDocComment ( ) ; writer . println ( "private final %s %s;" , boundGinjectorInterface . getCanonicalName ( ) , fieldName ) ; sourceWriteUtil . writeMethod ( writer , String . format ( "public %s %s()" , boundGinjectorInterface . getCanonicalName ( ) , getterName ) , String . format ( "return %s;" , fieldName ) ) ; }
Writes code to store and retrieve the current injector interface if one is bound .
9,169
private void outputMemberInjections ( GinjectorBindings bindings , FragmentMap fragments , SourceWriteUtil sourceWriteUtil ) { NameGenerator nameGenerator = bindings . getNameGenerator ( ) ; for ( TypeLiteral < ? > type : bindings . getMemberInjectRequests ( ) ) { if ( ! reachabilityAnalyzer . isReachableMemberInject ( bindings , type ) ) { continue ; } List < InjectorMethod > memberInjectionHelpers = new ArrayList < InjectorMethod > ( ) ; try { sourceWriteUtil . createMemberInjection ( type , nameGenerator , memberInjectionHelpers ) ; outputMethods ( memberInjectionHelpers , fragments ) ; } catch ( NoSourceNameException e ) { errorManager . logError ( e . getMessage ( ) , e ) ; } } }
Adds member injections to each fragment .
9,170
void outputStaticInjectionMethods ( Class < ? > type , FragmentMap fragments , NameGenerator nameGenerator , SourceWriteUtil sourceWriteUtil ) { String methodName = nameGenerator . convertToValidMemberName ( "injectStatic_" + type . getName ( ) ) ; SourceSnippetBuilder body = new SourceSnippetBuilder ( ) ; for ( InjectionPoint injectionPoint : InjectionPoint . forStaticMethodsAndFields ( type ) ) { Member member = injectionPoint . getMember ( ) ; try { List < InjectorMethod > staticInjectionHelpers = new ArrayList < InjectorMethod > ( ) ; if ( member instanceof Method ) { MethodLiteral < ? , Method > method = MethodLiteral . get ( ( Method ) member , TypeLiteral . get ( member . getDeclaringClass ( ) ) ) ; body . append ( methodCallUtil . createMethodCallWithInjection ( method , null , nameGenerator , staticInjectionHelpers ) ) ; } else if ( member instanceof Field ) { FieldLiteral < ? > field = FieldLiteral . get ( ( Field ) member , TypeLiteral . get ( member . getDeclaringClass ( ) ) ) ; body . append ( sourceWriteUtil . createFieldInjection ( field , null , nameGenerator , staticInjectionHelpers ) ) ; } outputMethods ( staticInjectionHelpers , fragments ) ; } catch ( NoSourceNameException e ) { errorManager . logError ( e . getMessage ( ) , e ) ; } } String packageName = type . getPackage ( ) . getName ( ) ; InjectorMethod method = SourceSnippets . asMethod ( false , "private void " + methodName + "()" , packageName , body . build ( ) ) ; GinjectorFragmentOutputter fragment = fragments . get ( fragmentPackageNameFactory . create ( packageName ) ) ; fragment . outputMethod ( method ) ; fragment . invokeInInitializeStaticInjections ( methodName ) ; }
Outputs all the static injection methods for the given class .
9,171
void outputMethods ( Iterable < InjectorMethod > methods , FragmentMap fragments ) { for ( InjectorMethod method : methods ) { FragmentPackageName fragmentPackageName = fragmentPackageNameFactory . create ( method . getPackageName ( ) ) ; GinjectorFragmentOutputter fragment = fragments . get ( fragmentPackageName ) ; fragment . outputMethod ( method ) ; } }
Outputs some methods to the fragments they belong to .
9,172
private static Class < ? > getBoundGinjector ( GinjectorBindings bindings ) { if ( bindings . getGinjectorInterface ( ) == null ) { return null ; } TypeLiteral < ? > ginjectorInterface = bindings . getGinjectorInterface ( ) ; Key < ? > ginjectorKey = Key . get ( ginjectorInterface ) ; if ( ! bindings . isBound ( ginjectorKey ) ) { return null ; } if ( ! ( bindings . getBinding ( ginjectorKey ) instanceof GinjectorBinding ) ) { return null ; } return ginjectorInterface . getRawType ( ) ; }
Gets the Ginjector interface that is bound by the given bindings if any .
9,173
void writeBindingGetter ( Key < ? > key , Binding binding , GinScope scope , List < InjectorMethod > helperMethodsOutput ) { Context bindingContext = binding . getContext ( ) ; SourceSnippetBuilder getterBuilder = new SourceSnippetBuilder ( ) ; SourceSnippet creationStatements ; String getter = nameGenerator . getGetterMethodName ( key ) ; String typeName ; try { typeName = ReflectUtil . getSourceName ( key . getTypeLiteral ( ) ) ; creationStatements = binding . getCreationStatements ( nameGenerator , helperMethodsOutput ) ; } catch ( NoSourceNameException e ) { errorManager . logError ( "Error trying to write getter for [%s] -> [%s];" + " binding declaration: %s" , e , key , binding , bindingContext ) ; return ; } String field = nameGenerator . getSingletonFieldName ( key ) ; switch ( scope ) { case EAGER_SINGLETON : initializeEagerSingletonsBody . append ( "// Eager singleton bound at:\n" ) ; appendBindingContextCommentToMethod ( bindingContext , initializeEagerSingletonsBody ) ; initializeEagerSingletonsBody . append ( getter ) . append ( "();\n" ) ; case SINGLETON : writer . println ( "private " + typeName + " " + field + " = null;" ) ; writer . println ( ) ; getterBuilder . append ( String . format ( "\nif (%s == null) {\n" , field ) ) . append ( creationStatements ) . append ( "\n" ) . append ( String . format ( " %s = result;\n" , field ) ) . append ( "}\n" ) . append ( String . format ( "return %s;\n" , field ) ) ; break ; case NO_SCOPE : sourceWriteUtil . writeBindingContextJavadoc ( writer , bindingContext , key ) ; getterBuilder . append ( creationStatements ) . append ( "\n" ) . append ( "return result;\n" ) ; break ; default : throw new IllegalStateException ( ) ; } outputMethod ( SourceSnippets . asMethod ( false , String . format ( "public %s %s()" , typeName , getter ) , fragmentPackageName . toString ( ) , getterBuilder . build ( ) ) ) ; }
Writes a method describing the getter for the given key along with any other code necessary to support it . Produces a list of helper methods that still need to be written .
9,174
void commit ( ) { if ( committed ) { errorManager . logError ( "Committed the fragment for %s twice." , fragmentPackageName ) ; return ; } committed = true ; writer . beginJavaDocComment ( ) ; writer . print ( "Field for the enclosing injector." ) ; writer . endJavaDocComment ( ) ; writer . println ( "private final %s injector;" , ginjectorClassName ) ; sourceWriteUtil . writeMethod ( writer , String . format ( "public %s(%s injector)" , fragmentClassName , ginjectorClassName ) , "this.injector = injector;" ) ; if ( hasEagerSingletonInitialization ( ) ) { sourceWriteUtil . writeMethod ( writer , "public void initializeEagerSingletons()" , initializeEagerSingletonsBody . toString ( ) ) ; } if ( hasStaticInjectionInitialization ( ) ) { sourceWriteUtil . writeMethod ( writer , "public void initializeStaticInjections()" , initializeStaticInjectionsBody . toString ( ) ) ; } writer . commit ( logger ) ; }
Outputs all the top - level methods and fields of the class and commits the writer . Must be the last method invoked on this object .
9,175
private void registerGinjectorBinding ( ) { Key < ? extends Ginjector > ginjectorKey = Key . get ( ginjectorInterface ) ; rootGinjectorBindings . addBinding ( ginjectorKey , bindingFactory . getGinjectorBinding ( ) ) ; }
Create an explicit binding for the Ginjector .
9,176
private void resolveAllUnresolvedBindings ( GinjectorBindings collection ) throws UnableToCompleteException { createBindingsForFactories ( collection ) ; for ( GinjectorBindings child : collection . getChildren ( ) ) { resolveAllUnresolvedBindings ( child ) ; } collection . resolveBindings ( ) ; }
Create bindings for factories and resolve all implicit bindings for all unresolved bindings in the each injector .
9,177
public SourceSnippet createFieldInjection ( final FieldLiteral < ? > field , final String injecteeName , NameGenerator nameGenerator , List < InjectorMethod > methodsOutput ) throws NoSourceNameException { final boolean hasInjectee = injecteeName != null ; final boolean useNativeMethod = field . isPrivate ( ) || ReflectUtil . isPrivate ( field . getDeclaringType ( ) ) || field . isLegacyFinalField ( ) ; final String injecteeTypeName = ReflectUtil . getSourceName ( field . getRawDeclaringType ( ) ) ; String fieldTypeName = ReflectUtil . getSourceName ( field . getFieldType ( ) ) ; String methodBaseName = nameGenerator . convertToValidMemberName ( injecteeTypeName + "_" + field . getName ( ) + "_fieldInjection" ) ; final String methodName = nameGenerator . createMethodName ( methodBaseName ) ; final String packageName = ReflectUtil . getUserPackageName ( field . getDeclaringType ( ) ) ; String signatureParams = fieldTypeName + " value" ; boolean isLongAcccess = field . getFieldType ( ) . getRawType ( ) . equals ( Long . TYPE ) ; if ( hasInjectee ) { signatureParams = injecteeTypeName + " injectee, " + signatureParams ; } String annotation ; if ( isLongAcccess ) { annotation = "@com.google.gwt.core.client.UnsafeNativeLong " ; } else { annotation = "" ; } String header = useNativeMethod ? "public native " : "public " ; String signature = annotation + header + "void " + methodName + "(" + signatureParams + ")" ; InjectorMethod injectionMethod = new AbstractInjectorMethod ( useNativeMethod , signature , packageName ) { public String getMethodBody ( InjectorWriteContext writeContext ) throws NoSourceNameException { if ( ! useNativeMethod ) { return ( hasInjectee ? "injectee." : injecteeTypeName + "." ) + field . getName ( ) + " = value;" ; } else { return ( hasInjectee ? "injectee." : "" ) + getJsniSignature ( field ) + " = value;" ; } } } ; methodsOutput . add ( injectionMethod ) ; return new SourceSnippet ( ) { public String getSource ( InjectorWriteContext writeContext ) { List < String > callParams = new ArrayList < String > ( ) ; if ( hasInjectee ) { callParams . add ( injecteeName ) ; } callParams . add ( writeContext . callGetter ( guiceUtil . getKey ( field ) ) ) ; return writeContext . callMethod ( methodName , packageName , callParams ) + ";\n" ; } } ; }
Creates a field injecting method and returns a string that invokes the written method .
9,178
public void writeBindingContext ( SourceWriter writer , Context context ) { String text = context . toString ( ) ; boolean first = true ; for ( String line : text . split ( "\n" ) ) { if ( first ) { first = false ; } else { writer . println ( ) ; } writer . print ( " " ) ; writer . print ( line ) ; } }
Writes out a binding context followed by a newline .
9,179
public void writeBindingContextJavadoc ( SourceWriter writer , Context bindingContext , String description ) { writer . beginJavaDocComment ( ) ; writer . println ( description ) ; writeBindingContext ( writer , bindingContext ) ; writer . endJavaDocComment ( ) ; }
Write a Javadoc comment for a binding including its context .
9,180
public void writeBindingContextJavadoc ( SourceWriter writer , Context bindingContext , Key < ? > key ) { writeBindingContextJavadoc ( writer , bindingContext , "Binding for " + key . getTypeLiteral ( ) + " declared at:" ) ; }
Write the Javadoc for the binding of a particular key showing the context of the binding .
9,181
public void writeMethod ( SourceWriter writer , String signature , String body ) { writer . println ( signature + " {" ) ; writer . indent ( ) ; writer . println ( body ) ; writer . outdent ( ) ; writer . println ( "}" ) ; writer . println ( ) ; }
Writes a method with the given signature and body to the source writer .
9,182
public void writeMethod ( InjectorMethod method , SourceWriter writer , InjectorWriteContext writeContext ) throws NoSourceNameException { if ( method . isNative ( ) ) { writeNativeMethod ( writer , method . getMethodSignature ( ) , method . getMethodBody ( writeContext ) ) ; } else { writeMethod ( writer , method . getMethodSignature ( ) , method . getMethodBody ( writeContext ) ) ; } }
Writes the given method to the given source writer .
9,183
public void writeMethods ( Iterable < InjectorMethod > methods , SourceWriter writer , InjectorWriteContext writeContext ) throws NoSourceNameException { for ( InjectorMethod method : methods ) { writeMethod ( method , writer , writeContext ) ; } }
Writes the given methods to the given source writer .
9,184
public String createMemberInjection ( TypeLiteral < ? > type , NameGenerator nameGenerator , List < InjectorMethod > methodsOutput ) throws NoSourceNameException { String memberInjectMethodName = nameGenerator . getMemberInjectMethodName ( type ) ; String memberInjectMethodSignature = "public void " + memberInjectMethodName + "(" + ReflectUtil . getSourceName ( type ) + " injectee)" ; SourceSnippetBuilder sb = new SourceSnippetBuilder ( ) ; sb . append ( createFieldInjections ( getFieldsToInject ( type ) , "injectee" , nameGenerator , methodsOutput ) ) ; sb . append ( createMethodInjections ( getMethodsToInject ( type ) , "injectee" , nameGenerator , methodsOutput ) ) ; methodsOutput . add ( SourceSnippets . asMethod ( false , memberInjectMethodSignature , ReflectUtil . getUserPackageName ( type ) , sb . build ( ) ) ) ; return memberInjectMethodName ; }
Generates all the required injector methods to inject members of the given type and a standard member - inject method that invokes them .
9,185
public SourceSnippet createConstructorInjection ( MethodLiteral < ? , Constructor < ? > > constructor , NameGenerator nameGenerator , List < InjectorMethod > methodsOutput ) throws NoSourceNameException { return createMethodCallWithInjection ( constructor , null , nameGenerator , methodsOutput ) ; }
Creates a constructor injecting method and returns a string that invokes the new method . The new method returns the constructed object .
9,186
public SourceSnippet createMethodCallWithInjection ( MethodLiteral < ? , ? > method , String invokeeName , NameGenerator nameGenerator , List < InjectorMethod > methodsOutput ) throws NoSourceNameException { String [ ] params = new String [ method . getParameterTypes ( ) . size ( ) ] ; return createMethodCallWithInjection ( method , invokeeName , params , nameGenerator , methodsOutput ) ; }
Creates a method that calls the passed method injecting its parameters using getters and returns a string that invokes the new method . The new method returns the passed method s return value if any . If a method without parameters is provided that method will be called and no parameters will be passed .
9,187
private boolean isLongAccess ( MethodLiteral < ? , ? > method ) { boolean result = method . getReturnType ( ) . getRawType ( ) . equals ( Long . TYPE ) ; for ( TypeLiteral < ? > paramLiteral : method . getParameterTypes ( ) ) { result |= paramLiteral . getRawType ( ) . equals ( Long . TYPE ) ; } return result ; }
Check whether a method needs to have Long access .
9,188
protected Class < ? > findClass ( String name ) throws ClassNotFoundException { if ( ! loadedClassFiles ) { classFileMap = extractClassFileMap ( ) ; loadedClassFiles = true ; } if ( classFileMap == null ) { throw new ClassNotFoundException ( name ) ; } String internalName = name . replace ( '.' , '/' ) ; CompiledClass compiledClass = classFileMap . get ( internalName ) ; if ( compiledClass == null ) { throw new ClassNotFoundException ( name ) ; } String pkg = compiledClass . getPackageName ( ) ; if ( getPackage ( pkg ) == null ) { definePackage ( pkg , null , null , null , null , null , null , null ) ; } byte [ ] bytes = compiledClass . getBytes ( ) ; return defineClass ( name , bytes , 0 , bytes . length ) ; }
Looks up classes in GWT s compilation state .
9,189
public Binding create ( Key < ? > key ) throws BindingCreationException { TypeLiteral < ? > type = key . getTypeLiteral ( ) ; if ( isProviderKey ( key ) ) { return bindingFactory . getImplicitProviderBinding ( key ) ; } if ( isAsyncProviderKey ( key ) ) { return bindingFactory . getAsyncProviderBinding ( key ) ; } if ( BindConstantBinding . isConstantKey ( key ) ) { throw new BindingCreationException ( "Binding requested for constant key '%s' but no explicit binding was found" , key ) ; } if ( key . getAnnotation ( ) != null || key . getAnnotationType ( ) != null ) { throw new BindingCreationException ( "No implementation bound for '%s' and an implicit binding" + " cannot be created because the type is annotated." , key ) ; } ImplementedBy implementedBy = type . getRawType ( ) . getAnnotation ( ImplementedBy . class ) ; if ( implementedBy != null ) { return createImplementedByBinding ( key , implementedBy ) ; } ProvidedBy providedBy = type . getRawType ( ) . getAnnotation ( ProvidedBy . class ) ; if ( providedBy != null ) { return createProvidedByBinding ( key , providedBy ) ; } return createImplicitBindingForClass ( type ) ; }
Creates the implicit binding .
9,190
private void traceGinjectorMethods ( ) { TypeLiteral < ? > ginjectorInterface = rootBindings . getGinjectorInterface ( ) ; for ( MethodLiteral < ? , Method > method : memberCollector . getMethods ( ginjectorInterface ) ) { if ( ! guiceUtil . isMemberInject ( method ) ) { Key < ? > key = guiceUtil . getKey ( method ) ; PrettyPrinter . log ( logger , TreeLogger . DEBUG , "ROOT -> %s:%s [%s]" , rootBindings , key , method ) ; traceKey ( key , rootBindings ) ; } else { Key < ? > sourceKey = guiceUtil . getKey ( method ) ; getReachableMemberInjects ( rootBindings ) . add ( sourceKey . getTypeLiteral ( ) ) ; for ( Dependency dependency : guiceUtil . getMemberInjectionDependencies ( sourceKey , sourceKey . getTypeLiteral ( ) ) ) { Key < ? > targetKey = dependency . getTarget ( ) ; PrettyPrinter . log ( logger , TreeLogger . DEBUG , "ROOT -> %s:%s [%s]" , rootBindings , targetKey , method ) ; traceKey ( targetKey , rootBindings ) ; } } } }
Traces out bindings that are reachable from a GInjector method .
9,191
private String getNameForType ( Class < ? > type ) { if ( _typeToStringMap . containsKey ( type ) ) { return _typeToStringMap . get ( type ) ; } for ( Entry < String , Class < ? > > entry : _typeMappings . entrySet ( ) ) { if ( entry . getValue ( ) . isAssignableFrom ( type ) ) { return entry . getKey ( ) ; } } return null ; }
given a type get a name . This takes subclassing into consideration . For now this will return the first subclass match to the type not the closest
9,192
public static ProxyInfo setProxyCfg ( String host , String port , String userName , String password ) { return new ProxyInfo ( host , port , userName , password ) ; }
Set proxy configuration .
9,193
@ SuppressWarnings ( "squid:S134" ) private void createHtmlReport ( FilePath reportFolder , String testFolderPath , File artifactsDir , List < String > reportNames , TestResult testResult ) throws IOException , InterruptedException { String archiveTestResultMode = _resultsPublisherModel . getArchiveTestResultsMode ( ) ; boolean createReport = archiveTestResultMode . equals ( ResultsPublisherModel . CreateHtmlReportResults . getValue ( ) ) ; if ( createReport ) { File testFolderPathFile = new File ( testFolderPath ) ; FilePath srcDirectoryFilePath = new FilePath ( reportFolder , HTML_REPORT_FOLDER ) ; if ( srcDirectoryFilePath . exists ( ) ) { FilePath srcFilePath = new FilePath ( srcDirectoryFilePath , IE_REPORT_FOLDER ) ; if ( srcFilePath . exists ( ) ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; srcFilePath . zip ( baos ) ; File reportDirectory = new File ( artifactsDir . getParent ( ) , PERFORMANCE_REPORT_FOLDER ) ; if ( ! reportDirectory . exists ( ) ) { reportDirectory . mkdir ( ) ; } ByteArrayInputStream bais = new ByteArrayInputStream ( baos . toByteArray ( ) ) ; FilePath reportDirectoryFilePath = new FilePath ( reportDirectory ) ; FilePath tmpZipFile = new FilePath ( reportDirectoryFilePath , "tmp.zip" ) ; tmpZipFile . copyFrom ( bais ) ; bais . close ( ) ; baos . close ( ) ; tmpZipFile . unzip ( reportDirectoryFilePath ) ; String newFolderName = org . apache . commons . io . FilenameUtils . getName ( testFolderPathFile . getPath ( ) ) ; FileUtils . moveDirectory ( new File ( reportDirectory , IE_REPORT_FOLDER ) , new File ( reportDirectory , newFolderName ) ) ; tmpZipFile . delete ( ) ; outputReportFiles ( reportNames , reportDirectory , testResult , false ) ; } } } }
Copy Summary Html reports created by LoadRunner
9,194
private void createTransactionSummary ( FilePath reportFolder , String testFolderPath , File artifactsDir , List < String > reportNames , TestResult testResult ) throws IOException , InterruptedException { File testFolderPathFile = new File ( testFolderPath ) ; String subFolder = HTML_REPORT_FOLDER + File . separator + IE_REPORT_FOLDER + File . separator + HTML_REPORT_FOLDER ; FilePath htmlReportPath = new FilePath ( reportFolder , subFolder ) ; if ( htmlReportPath . exists ( ) ) { File reportDirectory = new File ( artifactsDir . getParent ( ) , TRANSACTION_SUMMARY_FOLDER ) ; if ( ! reportDirectory . exists ( ) ) { reportDirectory . mkdir ( ) ; } String newFolderName = org . apache . commons . io . FilenameUtils . getName ( testFolderPathFile . getPath ( ) ) ; File testDirectory = new File ( reportDirectory , newFolderName ) ; if ( ! testDirectory . exists ( ) ) { testDirectory . mkdir ( ) ; } FilePath dstReportPath = new FilePath ( testDirectory ) ; FileFilter reportFileFilter = new WildcardFileFilter ( TRANSACTION_REPORT_NAME + ".*" ) ; List < FilePath > reporFiles = htmlReportPath . list ( reportFileFilter ) ; for ( FilePath fileToCopy : reporFiles ) { FilePath dstFilePath = new FilePath ( dstReportPath , fileToCopy . getName ( ) ) ; fileToCopy . copyTo ( dstFilePath ) ; } FilePath cssFilePath = new FilePath ( htmlReportPath , "Properties.css" ) ; if ( cssFilePath . exists ( ) ) { FilePath dstFilePath = new FilePath ( dstReportPath , cssFilePath . getName ( ) ) ; cssFilePath . copyTo ( dstFilePath ) ; } FilePath pngFilePath = new FilePath ( htmlReportPath , "tbic_toexcel.png" ) ; if ( pngFilePath . exists ( ) ) { FilePath dstFilePath = new FilePath ( dstReportPath , pngFilePath . getName ( ) ) ; pngFilePath . copyTo ( dstFilePath ) ; } outputReportFiles ( reportNames , reportDirectory , testResult , true ) ; } }
Copies and creates the transaction summery on the master
9,195
private void setProxyCredentials ( Run < ? , ? > run ) { if ( proxySettings != null && proxySettings . getFsProxyCredentialsId ( ) != null ) { UsernamePasswordCredentials up = CredentialsProvider . findCredentialById ( proxySettings . getFsProxyCredentialsId ( ) , StandardUsernamePasswordCredentials . class , run , URIRequirementBuilder . create ( ) . build ( ) ) ; if ( up != null ) { proxySettings . setFsProxyUserName ( up . getUsername ( ) ) ; proxySettings . setFsProxyPassword ( up . getPassword ( ) ) ; } } }
Get credentials by the credentials id . Then set the user name and password into the SsePoxySetting .
9,196
private UsernamePasswordCredentials getCredentialsById ( String credentialsId , Run < ? , ? > run , PrintStream logger ) { if ( StringUtils . isBlank ( credentialsId ) ) { throw new NullPointerException ( "credentials is not configured." ) ; } UsernamePasswordCredentials credentials = CredentialsProvider . findCredentialById ( credentialsId , StandardUsernamePasswordCredentials . class , run , URIRequirementBuilder . create ( ) . build ( ) ) ; if ( credentials == null ) { logger . println ( "Can not find credentials with the credentialsId:" + credentialsId ) ; } return credentials ; }
Get user name password credentials by id .
9,197
public void mergeResults ( LrJobResults resultFiles ) { for ( JobLrScenarioResult scenarioResult : resultFiles . getLrScenarioResults ( ) . values ( ) ) { this . _resultFiles . addScenario ( scenarioResult ) ; } }
Merge results of several runs - espcially useful in pipeline jobs with multiple LR steps
9,198
public JSONObject loginToMC ( String mcUrl , String mcUserName , String mcPassword , String proxyAddress , String proxyUsername , String proxyPassword ) { JSONObject returnObject = new JSONObject ( ) ; try { Map < String , String > headers = new HashMap < String , String > ( ) ; headers . put ( Constants . ACCEPT , "application/json" ) ; headers . put ( Constants . CONTENT_TYPE , "application/json;charset=UTF-8" ) ; JSONObject sendObject = new JSONObject ( ) ; sendObject . put ( "name" , mcUserName ) ; sendObject . put ( "password" , mcPassword ) ; sendObject . put ( "accountName" , "default" ) ; HttpResponse response = HttpUtils . post ( HttpUtils . setProxyCfg ( proxyAddress , proxyUsername , proxyPassword ) , mcUrl + Constants . LOGIN_URL , headers , sendObject . toJSONString ( ) . getBytes ( ) ) ; if ( response != null && response . getHeaders ( ) != null ) { Map < String , List < String > > headerFields = response . getHeaders ( ) ; List < String > hp4mSecretList = headerFields . get ( Constants . LOGIN_SECRET ) ; String hp4mSecret = null ; if ( hp4mSecretList != null && hp4mSecretList . size ( ) != 0 ) { hp4mSecret = hp4mSecretList . get ( 0 ) ; } List < String > setCookieList = headerFields . get ( Constants . SET_COOKIE ) ; String setCookie = null ; if ( setCookieList != null && setCookieList . size ( ) != 0 ) { setCookie = setCookieList . get ( 0 ) ; for ( String str : setCookieList ) { if ( str . contains ( Constants . JSESSIONID ) && str . startsWith ( Constants . JSESSIONID ) ) { setCookie = str ; break ; } } } String jsessionId = getJSESSIONID ( setCookie ) ; returnObject . put ( Constants . JSESSIONID , jsessionId ) ; returnObject . put ( Constants . LOGIN_SECRET , hp4mSecret ) ; returnObject . put ( Constants . COOKIE , Constants . JESEEIONEQ + jsessionId ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } return returnObject ; }
Login to MC
9,199
public JSONObject upload ( String mcUrl , String mcUserName , String mcPassword , String proxyAddress , String proxyUsername , String proxyPassword , String appPath ) throws Exception { JSONObject json = null ; String hp4mSecret = null ; String jsessionId = null ; File appFile = new File ( appPath ) ; String uploadUrl = mcUrl + Constants . APP_UPLOAD ; ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( ) ; StringBuffer content = new StringBuffer ( ) ; content . append ( "\r\n" ) . append ( "------" ) . append ( Constants . BOUNDARYSTR ) . append ( "\r\n" ) ; content . append ( "Content-Disposition: form-data; name=\"file\"; filename=\"" + appFile . getName ( ) + "\"\r\n" ) ; content . append ( "Content-Type: application/octet-stream\r\n\r\n" ) ; outputStream . write ( content . toString ( ) . getBytes ( ) ) ; FileInputStream in = new FileInputStream ( appFile ) ; byte [ ] b = new byte [ 1024 ] ; int i = 0 ; while ( ( i = in . read ( b ) ) != - 1 ) { outputStream . write ( b , 0 , i ) ; } in . close ( ) ; outputStream . write ( ( "\r\n------" + Constants . BOUNDARYSTR + "--\r\n" ) . getBytes ( ) ) ; byte [ ] bytes = outputStream . toByteArray ( ) ; outputStream . close ( ) ; JSONObject loginJson = loginToMC ( mcUrl , mcUserName , mcPassword , proxyAddress , proxyUsername , proxyPassword ) ; if ( loginJson != null ) { hp4mSecret = ( String ) loginJson . get ( Constants . LOGIN_SECRET ) ; jsessionId = ( String ) loginJson . get ( Constants . JSESSIONID ) ; } Map < String , String > headers = new HashMap < String , String > ( ) ; headers . put ( Constants . LOGIN_SECRET , hp4mSecret ) ; headers . put ( Constants . COOKIE , Constants . JESEEIONEQ + jsessionId ) ; headers . put ( Constants . CONTENT_TYPE , Constants . CONTENT_TYPE_DOWNLOAD_VALUE + Constants . BOUNDARYSTR ) ; headers . put ( Constants . FILENAME , appFile . getName ( ) ) ; HttpUtils . ProxyInfo proxyInfo = HttpUtils . setProxyCfg ( proxyAddress , proxyUsername , proxyPassword ) ; HttpResponse response = HttpUtils . post ( proxyInfo , uploadUrl , headers , bytes ) ; if ( response != null && response . getJsonObject ( ) != null ) { json = response . getJsonObject ( ) ; } return json ; }
upload app to MC