idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
40,600
|
private boolean matchletMagicCompare ( int offset , byte [ ] data ) { if ( oneMatchletMagicEquals ( offset , data ) ) { int nChildren = content . getInt ( offset + 24 ) ; if ( nChildren > 0 ) { int firstChildOffset = content . getInt ( offset + 28 ) ; return matchletMagicCompareOr ( nChildren , firstChildOffset , data ) ; } else { return true ; } } else { return false ; } }
|
Returns whether data satisfies the matchlet and its children .
|
40,601
|
private boolean isRetryable ( Exception e ) { final String mName = "isRetryable" ; String exClassName = e . getClass ( ) . getName ( ) ; boolean retVal = containsException ( _retryIncludeExceptions , e ) && ! containsException ( _retryExcludeExceptions , e ) ; if ( logger . isLoggable ( Level . FINE ) ) logger . logp ( Level . FINE , className , mName , mName + ": " + retVal + ": " + exClassName ) ; return retVal ; }
|
Check the retryable exception lists to determine whether the given Exception is retryable .
|
40,602
|
public void registerPlatformMode ( PlatformMode mode ) { platformMode = mode ; if ( mode . equals ( PlatformMode . EE ) ) { logger . config ( "Batch configured in EE mode by SPI, taking precedence over properties file" ) ; } else if ( mode . equals ( PlatformMode . SE ) ) { logger . config ( "Batch configured in SE mode by SPI, taking precedence over properties file" ) ; } }
|
Override properties - file based config with programmatic setting of SE or EE platform mode .
|
40,603
|
private boolean isSkippable ( Exception e ) { final String mName = "isSkippable" ; String exClassName = e . getClass ( ) . getName ( ) ; boolean retVal = containsSkippable ( _skipIncludeExceptions , e ) && ! containsSkippable ( _skipExcludeExceptions , e ) ; if ( logger . isLoggable ( Level . FINE ) ) logger . logp ( Level . FINE , className , mName , mName + ": " + retVal + ": " + exClassName ) ; return retVal ; }
|
Check the skipCount and skippable exception lists to determine whether the given Exception is skippable .
|
40,604
|
private boolean containsSkippable ( Set < String > skipList , Exception e ) { final String mName = "containsSkippable" ; boolean retVal = false ; for ( Iterator it = skipList . iterator ( ) ; it . hasNext ( ) ; ) { String exClassName = ( String ) it . next ( ) ; try { ClassLoader tccl = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( retVal = tccl . loadClass ( exClassName ) . isInstance ( e ) ) break ; } catch ( ClassNotFoundException cnf ) { logger . logp ( Level . FINE , className , mName , cnf . getLocalizedMessage ( ) ) ; } } if ( logger . isLoggable ( Level . FINE ) ) logger . logp ( Level . FINE , className , mName , mName + ": " + retVal ) ; return retVal ; }
|
Check whether given exception is in skippable exception list
|
40,605
|
private Object processItem ( Object itemRead ) { logger . entering ( sourceClass , "processItem" , itemRead ) ; Object processedItem = null ; if ( processorProxy == null ) { return itemRead ; } try { for ( ItemProcessListenerProxy processListenerProxy : itemProcessListeners ) { processListenerProxy . beforeProcess ( itemRead ) ; } processedItem = processorProxy . processItem ( itemRead ) ; if ( processedItem == null ) { currentItemStatus . setFiltered ( true ) ; } for ( ItemProcessListenerProxy processListenerProxy : itemProcessListeners ) { processListenerProxy . afterProcess ( itemRead , processedItem ) ; } } catch ( Exception e ) { for ( ItemProcessListenerProxy processListenerProxy : itemProcessListeners ) { processListenerProxy . onProcessError ( itemRead , e ) ; } if ( ! currentChunkStatus . isRetryingAfterRollback ( ) ) { if ( retryProcessException ( e , itemRead ) ) { if ( ! retryHandler . isRollbackException ( e ) ) { processedItem = processItem ( itemRead ) ; } else { currentChunkStatus . markForRollbackWithRetry ( e ) ; } } else if ( skipProcessException ( e , itemRead ) ) { currentItemStatus . setSkipped ( true ) ; stepContext . getMetric ( MetricImpl . MetricType . PROCESS_SKIP_COUNT ) . incValue ( ) ; } else { throw new BatchContainerRuntimeException ( e ) ; } } else { if ( skipProcessException ( e , itemRead ) ) { currentItemStatus . setSkipped ( true ) ; stepContext . getMetric ( MetricImpl . MetricType . PROCESS_SKIP_COUNT ) . incValue ( ) ; } else if ( retryProcessException ( e , itemRead ) ) { if ( ! retryHandler . isRollbackException ( e ) ) { processedItem = processItem ( itemRead ) ; } else { currentChunkStatus . markForRollbackWithRetry ( e ) ; } } else { throw new BatchContainerRuntimeException ( e ) ; } } } catch ( Throwable e ) { throw new BatchContainerRuntimeException ( e ) ; } logger . exiting ( sourceClass , "processItem" , processedItem == null ? "<null>" : processedItem ) ; return processedItem ; }
|
Process an item previously read by the reader
|
40,606
|
private void initPlatformSEorEE ( ) { String seMode = serviceImplClassNames . get ( Name . JAVA_EDITION_IS_SE_DUMMY_SERVICE ) ; if ( seMode . equalsIgnoreCase ( "true" ) ) { platformMode = PlatformMode . SE ; batchConfigImpl . setJ2seMode ( true ) ; } else { platformMode = PlatformMode . EE ; batchConfigImpl . setJ2seMode ( false ) ; } }
|
Push hardened config value onto batchConfigImpl and cache the value in a field .
|
40,607
|
public static synchronized Schema getXJCLSchema ( ) { if ( schema == null ) { try { URL url = ValidatorHelper . class . getResource ( "/" + SCHEMA_LOCATION ) ; schema = sf . newSchema ( url ) ; } catch ( SAXException e ) { throw new RuntimeException ( e ) ; } } return schema ; }
|
This method must be synchronized as SchemaFactory is not thread - safe
|
40,608
|
private void buildSubJobBatchWorkUnits ( ) { List < Flow > flows = this . split . getFlows ( ) ; parallelBatchWorkUnits = new ArrayList < BatchFlowInSplitWorkUnit > ( ) ; synchronized ( subJobs ) { for ( Flow flow : flows ) { subJobs . add ( PartitionedStepBuilder . buildFlowInSplitSubJob ( jobContext , this . split , flow ) ) ; } for ( JSLJob job : subJobs ) { int count = batchKernel . getJobInstanceCount ( job . getId ( ) ) ; FlowInSplitBuilderConfig config = new FlowInSplitBuilderConfig ( job , completedWorkQueue , rootJobExecutionId ) ; if ( count == 0 ) { parallelBatchWorkUnits . add ( batchKernel . buildNewFlowInSplitWorkUnit ( config ) ) ; } else if ( count == 1 ) { parallelBatchWorkUnits . add ( batchKernel . buildOnRestartFlowInSplitWorkUnit ( config ) ) ; } else { throw new IllegalStateException ( "There is an inconsistency somewhere in the internal subjob creation" ) ; } } } }
|
Note we restart all flows . There is no concept of the flow completed . It is only steps within the flows that may have already completed and so may not have needed to be rerun .
|
40,609
|
private static void initializeWithDefaultScope ( ) { try { Class < ? > aClass = Class . forName ( DEFAULT_SCOPE_FACTORY ) ; INSTANCE = ( SingletonProvider ) aClass . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
|
Initialize with the default instance
|
40,610
|
public static void initialize ( SingletonProvider instance ) { synchronized ( SingletonProvider . class ) { if ( INSTANCE == null ) { INSTANCE = instance ; } else { throw new RuntimeException ( "SingletonProvider is already initialized with " + INSTANCE ) ; } } }
|
Initialize with an explicit instance
|
40,611
|
private List < GraphResult > getPcaData ( double [ ] [ ] data , BiMap < Integer , String > dataNames ) { int rows = data . length ; int cols = data . length ; double matrixSum = 0 ; double [ ] rowSums = new double [ rows ] ; for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < cols ; j ++ ) { matrixSum += data [ i ] [ j ] ; rowSums [ i ] += data [ i ] [ j ] ; } } double matrixMean = matrixSum / rows / cols ; for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < cols ; j ++ ) { double rowMean = rowSums [ i ] / rows ; double colMean = rowSums [ j ] / rows ; data [ i ] [ j ] = data [ i ] [ j ] - rowMean - colMean + matrixMean ; } } Matrix matrix = new Matrix ( data ) ; EigenvalueDecomposition eig = matrix . eig ( ) ; Matrix eigenvectors = eig . getV ( ) ; double [ ] realEigenvalues = eig . getRealEigenvalues ( ) ; for ( int j = 0 ; j < eigenvectors . getColumnDimension ( ) ; j ++ ) { double sumSquares = 0 ; for ( int i = 0 ; i < eigenvectors . getRowDimension ( ) ; i ++ ) { sumSquares += eigenvectors . get ( i , j ) * eigenvectors . get ( i , j ) ; } for ( int i = 0 ; i < eigenvectors . getRowDimension ( ) ; i ++ ) { eigenvectors . set ( i , j , eigenvectors . get ( i , j ) * Math . sqrt ( realEigenvalues [ j ] / sumSquares ) ) ; } } int maxIndex = - 1 ; int secondIndex = - 1 ; double maxEigenvalue = 0 ; double secondEigenvalue = 0 ; for ( int i = 0 ; i < realEigenvalues . length ; i ++ ) { double eigenvector = realEigenvalues [ i ] ; if ( eigenvector > maxEigenvalue ) { secondEigenvalue = maxEigenvalue ; secondIndex = maxIndex ; maxEigenvalue = eigenvector ; maxIndex = i ; } else if ( eigenvector > secondEigenvalue ) { secondEigenvalue = eigenvector ; secondIndex = i ; } } List < GraphResult > results = Lists . newArrayList ( ) ; for ( int i = 0 ; i < rows ; i ++ ) { results . add ( new GraphResult ( dataNames . get ( i ) , eigenvectors . get ( i , maxIndex ) , eigenvectors . get ( i , secondIndex ) ) ) ; } return results ; }
|
Convert the similarity matrix to an Eigen matrix .
|
40,612
|
public void addBin ( List < Chunk > chunksToAdd , long lastLocus ) { assert chunks != null ; contig = new Contig ( contig . referenceName , contig . start , lastLocus ) ; chunks . addAll ( chunksToAdd ) ; updateSpan ( ) ; }
|
Appends chunks from another bin to the list and moved the end position .
|
40,613
|
public long finish ( ) { final BAMIndexContent content = indexBuilder . processReference ( referenceIndex ) ; outputWriter . writeReference ( content ) ; outputWriter . close ( ) ; return indexBuilder . getNoCoordinateRecordCount ( ) ; }
|
Finalizes writing and closes the file .
|
40,614
|
static Interval gridSearch ( UnivariateFunction fn , double start , double end , double step ) { double lowMax = start ; double alphaMax = start - step ; double likMax = 0.0 ; double lastAlpha = start ; double alpha = start ; while ( alpha < end ) { double likelihood = fn . value ( alpha ) ; if ( alphaMax < start || likelihood > likMax ) { lowMax = lastAlpha ; alphaMax = alpha ; likMax = likelihood ; } lastAlpha = alpha ; alpha += step ; } double likelihood = fn . value ( end ) ; if ( likelihood > likMax ) { lowMax = lastAlpha ; alphaMax = end ; likMax = likelihood ; } return new Interval ( lowMax , Math . min ( end , alphaMax + step ) ) ; }
|
Runs a grid search for the maximum value of a univariate function .
|
40,615
|
public static double maximize ( UnivariateFunction fn , double gridStart , double gridEnd , double gridStep , double relErr , double absErr , int maxIter , int maxEval ) { Interval interval = gridSearch ( fn , gridStart , gridEnd , gridStep ) ; BrentOptimizer bo = new BrentOptimizer ( relErr , absErr ) ; UnivariatePointValuePair max = bo . optimize ( new MaxIter ( maxIter ) , new MaxEval ( maxEval ) , new SearchInterval ( interval . getInf ( ) , interval . getSup ( ) ) , new UnivariateObjectiveFunction ( fn ) , GoalType . MAXIMIZE ) ; return max . getPoint ( ) ; }
|
Maximizes a univariate function using a grid search followed by Brent s algorithm .
|
40,616
|
static boolean passesFilter ( SAMRecord record , Filter filter , String referenceName ) { if ( filter == Filter . UNMAPPED_ONLY && ! record . getReadUnmappedFlag ( ) ) { return false ; } if ( filter == Filter . MAPPED_ONLY && record . getReadUnmappedFlag ( ) ) { return false ; } final boolean referenceNameMismatch = referenceName != null && ! referenceName . isEmpty ( ) && ! referenceName . equals ( record . getReferenceName ( ) ) ; if ( ( filter == Filter . MAPPED_ONLY || filter == Filter . MAPPED_AND_UNMAPPED ) && referenceNameMismatch ) { return false ; } return true ; }
|
Checks if the record matches our filter .
|
40,617
|
public void writeReference ( final BAMIndexContent content ) { if ( content == null ) { writeNullContent ( ) ; return ; } final BAMIndexContent . BinList bins = content . getBins ( ) ; final int size = bins == null ? 0 : content . getNumberOfNonNullBins ( ) ; if ( size == 0 ) { writeNullContent ( ) ; return ; } final BAMIndexMetaData metaData = content . getMetaData ( ) ; codec . writeInt ( size + ( ( metaData != null ) ? 1 : 0 ) ) ; for ( final Bin bin : bins ) { if ( bin . getBinNumber ( ) == GenomicIndexUtil . MAX_BINS ) continue ; writeBin ( bin ) ; } if ( metaData != null ) writeChunkMetaData ( metaData ) ; final LinearIndex linearIndex = content . getLinearIndex ( ) ; final long [ ] entries = linearIndex == null ? null : linearIndex . getIndexEntries ( ) ; final int indexStart = linearIndex == null ? 0 : linearIndex . getIndexStart ( ) ; final int n_intv = entries == null ? indexStart : entries . length + indexStart ; codec . writeInt ( n_intv ) ; if ( entries == null ) { return ; } for ( int i = 0 ; i < indexStart ; i ++ ) { codec . writeLong ( 0 ) ; } for ( int k = 0 ; k < entries . length ; k ++ ) { codec . writeLong ( entries [ k ] ) ; } try { codec . getOutputStream ( ) . flush ( ) ; } catch ( final IOException e ) { throw new SAMException ( "IOException in BinaryBAMIndexWriter reference " + content . getReferenceSequence ( ) , e ) ; } }
|
Write this content as binary output
|
40,618
|
private void writeChunkMetaData ( final BAMIndexMetaData metaData ) { codec . writeInt ( GenomicIndexUtil . MAX_BINS ) ; final int nChunk = 2 ; codec . writeInt ( nChunk ) ; codec . writeLong ( metaData . getFirstOffset ( ) ) ; codec . writeLong ( metaData . getLastOffset ( ) ) ; codec . writeLong ( metaData . getAlignedRecordCount ( ) ) ; codec . writeLong ( metaData . getUnalignedRecordCount ( ) ) ; }
|
Write the meta data represented by the chunkLists associated with bin MAX_BINS 37450
|
40,619
|
public double similarity ( VariantCall call1 , VariantCall call2 ) { int minNumberOfGenotypes = Math . min ( call1 . getGenotypeCount ( ) , call2 . getGenotypeCount ( ) ) ; int numberOfSharedAlleles = 0 ; for ( int i = 0 ; i < minNumberOfGenotypes ; ++ i ) { if ( call1 . getGenotype ( i ) == call2 . getGenotype ( i ) ) { ++ numberOfSharedAlleles ; } } int maxNumberOfGenotypes = Math . max ( call1 . getGenotypeCount ( ) , call2 . getGenotypeCount ( ) ) ; return ( double ) numberOfSharedAlleles / maxNumberOfGenotypes ; }
|
scores when the number of alleles is different than 2 and when the genotypes are unphased .
|
40,620
|
public static List < ReadBaseWithReference > extractReadBases ( Read read ) { if ( ! read . hasAlignment ( ) || ( read . getAlignment ( ) . getCigarCount ( ) == 0 ) ) { return null ; } ImmutableList . Builder < ReadBaseWithReference > bases = ImmutableList . builder ( ) ; String readSeq = read . getAlignedSequence ( ) ; List < Integer > readQual = read . getAlignedQualityList ( ) ; String refSeq = UNINITIALIZED_REFERENCE_SEQUENCE ; int refPosAbsoluteOffset = 0 ; int readOffset = 0 ; for ( CigarUnit unit : read . getAlignment ( ) . getCigarList ( ) ) { switch ( unit . getOperation ( ) ) { case ALIGNMENT_MATCH : case SEQUENCE_MISMATCH : case SEQUENCE_MATCH : for ( int i = 0 ; i < unit . getOperationLength ( ) ; i ++ ) { String refBase = "" ; if ( unit . getOperation ( ) . equals ( CigarUnit . Operation . SEQUENCE_MATCH ) ) { refBase = readSeq . substring ( readOffset , readOffset + 1 ) ; } else if ( ! unit . getReferenceSequence ( ) . isEmpty ( ) ) { refBase = unit . getReferenceSequence ( ) . substring ( i , i + 1 ) ; } else { if ( refSeq != null && refSeq . equals ( UNINITIALIZED_REFERENCE_SEQUENCE ) ) { refSeq = com . google . cloud . genomics . utils . grpc . ReadUtils . inferReferenceSequenceByParsingMdFlag ( read ) ; } if ( refSeq != null ) { refBase = refSeq . substring ( readOffset , readOffset + 1 ) ; } } String name = read . getAlignment ( ) . getPosition ( ) . getReferenceName ( ) ; Matcher m = Pattern . compile ( "^(chr)?(X|Y|([12]?\\d))$" ) . matcher ( name ) ; if ( m . matches ( ) ) { name = m . group ( m . groupCount ( ) - 1 ) ; } Position refPosition = Position . newBuilder ( ) . setReferenceName ( name ) . setPosition ( read . getAlignment ( ) . getPosition ( ) . getPosition ( ) + refPosAbsoluteOffset ) . build ( ) ; bases . add ( new ReadBaseWithReference ( new ReadBaseQuality ( readSeq . substring ( readOffset , readOffset + 1 ) , readQual . get ( readOffset ) ) , refBase , refPosition ) ) ; refPosAbsoluteOffset ++ ; readOffset ++ ; } break ; case PAD : case CLIP_HARD : break ; case CLIP_SOFT : case INSERT : readOffset += unit . getOperationLength ( ) ; break ; case DELETE : case SKIP : refPosAbsoluteOffset += unit . getOperationLength ( ) ; break ; default : throw new IllegalArgumentException ( "Illegal cigar code: " + unit . getOperation ( ) ) ; } } return bases . build ( ) ; }
|
Use the given read to build a list of aligned read and reference base information .
|
40,621
|
private static double pGenotype ( Genotype g , double refProb ) { switch ( g ) { case REF_HOMOZYGOUS : return refProb * refProb ; case HETEROZYGOUS : return refProb * ( 1.0 - refProb ) ; case NONREF_HOMOZYGOUS : return ( 1.0 - refProb ) * ( 1.0 - refProb ) ; default : throw new IllegalArgumentException ( "Illegal genotype" ) ; } }
|
Compute the probability of a genotype given the reference allele probability .
|
40,622
|
private static double probObsGivenTruth ( Base observed , Genotype trueGenotype , ReadStatus trueStatus ) { return P_OBS_GIVEN_TRUTH . get ( toTableIndex ( observed , trueGenotype , trueStatus ) ) ; }
|
Look up the probability of an observation conditioned on the underlying state .
|
40,623
|
public double value ( double alpha ) { double logLikelihood = 0.0 ; for ( ReadCounts rc : readCounts . values ( ) ) { double refProb = rc . getRefFreq ( ) ; double pPosition = 0.0 ; for ( Genotype trueGenotype1 : Genotype . values ( ) ) { double pGenotype1 = pGenotype ( trueGenotype1 , refProb ) ; for ( Genotype trueGenotype2 : Genotype . values ( ) ) { double pGenotype2 = pGenotype ( trueGenotype2 , refProb ) ; double pObsGivenGenotype = 1.0 ; for ( ReadQualityCount rqc : rc . getReadQualityCounts ( ) ) { Base base = rqc . getBase ( ) ; double pErr = phredToProb ( rqc . getQuality ( ) ) ; double pObs = ( ( 1.0 - alpha ) * probObsGivenTruth ( base , trueGenotype1 , ReadStatus . CORRECT ) + ( alpha ) * probObsGivenTruth ( base , trueGenotype2 , ReadStatus . CORRECT ) ) * ( 1.0 - pErr ) + ( ( 1.0 - alpha ) * probObsGivenTruth ( base , trueGenotype1 , ReadStatus . ERROR ) + ( alpha ) * probObsGivenTruth ( base , trueGenotype2 , ReadStatus . ERROR ) ) * pErr ; pObsGivenGenotype *= Math . pow ( pObs , rqc . getCount ( ) ) ; } pPosition += pObsGivenGenotype * pGenotype1 * pGenotype2 ; } } logLikelihood += Math . log ( pPosition ) ; } return logLikelihood ; }
|
Compute the likelihood of a contaminant fraction alpha .
|
40,624
|
public static PCollection < Read > getReadsFromBAMFileSharded ( Pipeline p , PipelineOptions pipelineOptions , OfflineAuth auth , List < Contig > contigs , ReaderOptions options , String BAMFile , ShardingPolicy shardingPolicy ) throws IOException { ReadBAMTransform readBAMSTransform = new ReadBAMTransform ( options ) ; readBAMSTransform . setAuth ( auth ) ; final Storage . Objects storage = Transport . newStorageClient ( pipelineOptions . as ( GCSOptions . class ) ) . build ( ) . objects ( ) ; final List < BAMShard > shardsList = Sharder . shardBAMFile ( storage , BAMFile , contigs , shardingPolicy ) ; PCollection < BAMShard > shards = p . apply ( Create . of ( shardsList ) ) ; return readBAMSTransform . expand ( shards ) ; }
|
Get reads from a single BAM file by serially reading one shard at a time .
|
40,625
|
public void addFile ( String loaderPath , URL file ) { List list = ( List ) filesMap . get ( loaderPath ) ; if ( list == null ) { list = new ArrayList ( ) ; filesMap . put ( loaderPath , list ) ; } list . add ( file ) ; }
|
add a file to the given loader
|
40,626
|
public static final void releaseMultiple ( CMutex mutex [ ] ) { Arrays . sort ( mutex , new CMutexComparator ( ) ) ; for ( int i = mutex . length - 1 ; i >= 0 ; i -- ) { mutex [ i ] . release ( ) ; } }
|
Releases an array of mutex previously acquired
|
40,627
|
public final void release ( ) { synchronized ( this . LOCK ) { if ( ( this . owner != null ) && ( this . owner . get ( ) == Thread . currentThread ( ) ) ) { this . acquire -- ; if ( this . acquire == 0 ) { this . owner = null ; this . LOCK . notify ( ) ; } return ; } if ( ( this . owner != null ) && ( this . owner . get ( ) == null ) ) { this . owner = null ; this . acquire = 0 ; this . LOCK . notify ( ) ; } throw new IllegalMonitorStateException ( Thread . currentThread ( ) . getName ( ) + " is not the owner of the lock. " + ( ( this . owner != null ) ? ( ( Thread ) this . owner . get ( ) ) . getName ( ) : "nobody" ) + " is the owner." ) ; } }
|
Releases the mutex
|
40,628
|
private static boolean isDescendant ( final Node n , final Node ref ) { if ( ref == null ) { return false ; } if ( n == ref ) { return true ; } NodeList nl = ref . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { boolean result = isDescendant ( n , nl . item ( i ) ) ; if ( result ) { return result ; } } return false ; }
|
return true if n is a descendant of ref
|
40,629
|
private static PbDocument [ ] getPbDocs ( final NodeList nl ) { List list = new ArrayList ( ) ; Element prevpb = null ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Element pb = ( Element ) nl . item ( i ) ; PbDocument pbdoc = new PbDocument ( prevpb , pb ) ; list . add ( pbdoc ) ; prevpb = pb ; if ( i == ( nl . getLength ( ) - 1 ) ) { pbdoc = new PbDocument ( pb , null ) ; list . add ( pbdoc ) ; } } PbDocument array [ ] = new PbDocument [ list . size ( ) ] ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { array [ i ] = ( PbDocument ) list . get ( i ) ; } return array ; }
|
Return the pagebreaks
|
40,630
|
private static void copyHeader ( final Document doc , final Document ndoc ) { NodeList headnl = doc . getElementsByTagName ( "head" ) ; if ( headnl . getLength ( ) > 0 ) { Element head = ( Element ) headnl . item ( 0 ) ; ndoc . getDocumentElement ( ) . insertBefore ( ndoc . adoptNode ( head . cloneNode ( true ) ) , ndoc . getDocumentElement ( ) . getFirstChild ( ) ) ; } }
|
Copy the html header from doc to ndoc
|
40,631
|
private static String getParameter ( final String args [ ] , final String name ) { for ( int i = 0 ; i < args . length ; i ++ ) { if ( args [ i ] . equals ( name ) ) { if ( ( i + 1 ) < args . length ) { return args [ i + 1 ] ; } break ; } } return null ; }
|
Return the value of the given parameter if set
|
40,632
|
private static boolean hasParameter ( final String args [ ] , final String name ) { for ( int i = 0 ; i < args . length ; i ++ ) { if ( args [ i ] . equals ( name ) ) { return true ; } } return false ; }
|
return true if the given parameter is on the command line
|
40,633
|
private static void showUsage ( final String message ) { if ( message != null ) { System . out . println ( message ) ; } System . out . println ( "Usage :\n\tjava -cp yahp-sample.jar:yahp.jar org.allcolor.yahp.sample.CSimpleConversion" + " --url [http|file]://myuri --out /path/to.pdf [font options] [renderer options] [security options] [--help|-h]" ) ; System . out . println ( "\t[font options]:" ) ; System . out . println ( "\t\t[--fontpath directory where TTF font files are located]" ) ; System . out . println ( "\t[renderer options]:" ) ; System . out . println ( "\t(Default renderer use Flying Saucer XHTML renderer. no option.)" ) ; System . out . println ( "\t[security options]:" ) ; System . out . println ( "\t\t[--password password]" ) ; System . out . println ( "\t\t[--ks keystore file path]" ) ; System . out . println ( "\t\t[--kspassword keystore file password]" ) ; System . out . println ( "\t\t[--keypassword private key password]" ) ; System . out . println ( "\t\t[--cryptreason reason]" ) ; System . out . println ( "\t\t[--cryptlocation location]" ) ; if ( message != null ) { System . exit ( - 2 ) ; } else { System . exit ( 0 ) ; } }
|
Show the usage of the tool
|
40,634
|
public void addClassPreload ( final String path , final byte array [ ] ) { try { this . preload . put ( path , new SoftReference ( new CGCCleaner ( path , array ) ) ) ; } catch ( Exception ignore ) { } }
|
add a class byte representation in the preload map
|
40,635
|
public static final CThreadContext getInstance ( ) { SoftReference ref = ( SoftReference ) CThreadContext . contextLocal . get ( Thread . currentThread ( ) ) ; CThreadContext context = null ; if ( ( ref == null ) || ( ref . get ( ) == null ) ) { context = new CThreadContext ( ) ; ref = new SoftReference ( context ) ; CThreadContext . contextLocal . put ( Thread . currentThread ( ) , ref ) ; } else { context = ( CThreadContext ) ref . get ( ) ; } return context ; }
|
Return a thread context
|
40,636
|
public final Object get ( String key ) { try { this . mutex . acquire ( ) ; return this . valueMap . get ( key ) ; } finally { try { this . mutex . release ( ) ; } catch ( Exception ignore ) { } } }
|
Get the value with the given key from this context
|
40,637
|
public final void set ( String key , Object value ) { try { this . mutex . acquire ( ) ; if ( value == null ) { this . valueMap . remove ( key ) ; } else { this . valueMap . put ( key , value ) ; } } finally { try { this . mutex . release ( ) ; } catch ( Exception ignore ) { } } }
|
Set a value in this context
|
40,638
|
public final String replaceExpr ( String message , String type ) { message = decode ( message ) ; List mapFilter = getFilter ( type ) ; if ( mapFilter == null ) return message ; Iterator it = mapFilter . iterator ( ) ; while ( it . hasNext ( ) ) { Object value [ ] = ( Object [ ] ) it . next ( ) ; String replacement = ( String ) value [ 0 ] ; List vFilter = ( List ) value [ 1 ] ; if ( ( vFilter . size ( ) == 0 ) && ( replacement . equals ( "[VALIDATE]" ) ) ) { message = validate ( message , type ) ; continue ; } for ( int j = 0 ; j < vFilter . size ( ) ; j ++ ) { Pattern filter = ( Pattern ) vFilter . get ( j ) ; Matcher match = filter . matcher ( message ) ; while ( match . find ( ) ) { message = match . replaceAll ( replacement ) ; match = filter . matcher ( message ) ; } } } return message ; }
|
Replace the input message using the rules type found in the xml configuration file
|
40,639
|
public static final CPadawan getInstance ( ) { try { mutex . acquire ( ) ; CPadawan toReturn = ( handle == null ) ? ( handle = new CPadawan ( ) ) : handle ; toReturn . init ( ) ; return toReturn ; } finally { try { mutex . release ( ) ; } catch ( Exception ignore ) { } } }
|
Return an instance of the padawan
|
40,640
|
private final List getFilter ( String type ) { try { mutex . acquire ( ) ; return ( List ) mapFilter . get ( type + ".filter" ) ; } finally { try { mutex . release ( ) ; } catch ( Throwable ignore ) { } } }
|
return the filters of type type
|
40,641
|
public final String validate ( String in , String type ) { CShaniDomParser parser = new CShaniDomParser ( ) ; Document doc = parser . parse ( new StringReader ( in ) , getTags ( type ) , getMerge ( type ) ) ; if ( doc != null ) return doc . toString ( ) ; else return in ; }
|
validate for xml the string in using the rules type type
|
40,642
|
public final String createEntityDeclaration ( ) throws UnsupportedEncodingException { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "<!DOCTYPE padawan [\n" ) ; for ( int i = 0 ; i < entity . length ; i ++ ) { buffer . append ( "<!ENTITY " + entity [ i ] [ 1 ] + " '" + entity [ i ] [ 0 ] + "' >\n" ) ; } buffer . append ( "]>\n" ) ; return buffer . toString ( ) ; }
|
Create the padawan doctype
|
40,643
|
public final String getEntityDeclaration ( ) { if ( entityDecl == null ) try { entityDecl = createEntityDeclaration ( ) ; } catch ( Exception e ) { entityDecl = null ; } return entityDecl ; }
|
return the padawan doctype
|
40,644
|
public final String decode ( String toDecode ) { CEntityCoDec codec = new CEntityCoDec ( new HashMap ( ) ) ; return codec . decode ( toDecode ) ; }
|
decode entity in the string
|
40,645
|
public final String stringReplace ( String toBeReplaced , String toReplace , String replacement ) { Pattern pattern = Pattern . compile ( toReplace ) ; Matcher match = pattern . matcher ( toBeReplaced ) ; while ( match . find ( ) ) { toBeReplaced = match . replaceAll ( replacement ) ; match = pattern . matcher ( toBeReplaced ) ; } return toBeReplaced ; }
|
A replace string method
|
40,646
|
private final boolean isAlone ( String tagName , String aloneTags [ ] ) { if ( aloneTags == null ) return false ; if ( tagName == null ) return false ; for ( int i = 0 ; i < aloneTags . length ; i ++ ) { if ( tagName . equalsIgnoreCase ( aloneTags [ i ] ) ) return true ; } return false ; }
|
return true if the given tag name is an empty tag
|
40,647
|
public final String escapeAttribute ( String in ) { in = escape ( in ) ; in = in . replaceAll ( "\"" , """ ) ; return in ; }
|
Escape the given string to be a valid content for an xml attribute
|
40,648
|
public final String escape ( String in ) { if ( in == null ) return "" ; if ( in . trim ( ) . equals ( "" ) ) return in ; if ( in . trim ( ) . length ( ) == 0 ) return in ; in = in . replaceAll ( "&" , "&" ) ; in = in . replaceAll ( "<" , "<" ) ; in = in . replaceAll ( ">" , ">" ) ; StringBuffer result = new StringBuffer ( ) ; char chars [ ] = in . toCharArray ( ) ; for ( int i = 0 ; i < chars . length ; i ++ ) { if ( ( chars [ i ] >= 127 ) && ( chars [ i ] < 160 ) ) { chars [ i ] = 32 ; result . append ( chars [ i ] ) ; } else if ( chars [ i ] == 160 ) { result . append ( " " ) ; } else if ( chars [ i ] == 9 ) { result . append ( " " ) ; } else if ( ( chars [ i ] < 32 ) && ( chars [ i ] != 9 ) && ( chars [ i ] != 10 ) && ( chars [ i ] != 13 ) ) { chars [ i ] = 32 ; result . append ( chars [ i ] ) ; } else { result . append ( chars [ i ] ) ; } } in = result . toString ( ) ; return in ; }
|
Escape the given string to be a valid content for an xml text node content
|
40,649
|
private static final CClassLoader createLoader ( final ClassLoader parent , final String name ) { try { return new CClassLoader ( parent , name ) ; } catch ( final Exception ignore ) { return null ; } }
|
Create a new loader
|
40,650
|
public static URL createMemoryURL ( final String entryName , final byte [ ] entry ) { try { final Class c = ClassLoader . getSystemClassLoader ( ) . loadClass ( "org.allcolor.yahp.converter.CMemoryURLHandler" ) ; final Method m = c . getDeclaredMethod ( "createMemoryURL" , new Class [ ] { String . class , byte [ ] . class } ) ; m . setAccessible ( true ) ; return ( URL ) m . invoke ( null , new Object [ ] { entryName , entry } ) ; } catch ( final Exception ignore ) { ignore . printStackTrace ( ) ; return null ; } }
|
Creates and allocates a memory URL
|
40,651
|
private static List getClasses ( final File current , final List list ) { if ( current . isDirectory ( ) ) { try { list . add ( current . toURI ( ) . toURL ( ) ) ; } catch ( final Exception ignore ) { } final File children [ ] = current . listFiles ( ) ; for ( int i = 0 ; i < children . length ; i ++ ) { final File element = children [ i ] ; CClassLoader . getClasses ( element , list ) ; } } else if ( current . isFile ( ) ) { final String name = current . getName ( ) ; if ( name . endsWith ( ".class" ) ) { try { list . add ( current . toURI ( ) . toURL ( ) ) ; } catch ( final Exception ignore ) { } } else if ( name . endsWith ( ".jar" ) ) { try { list . add ( current . toURI ( ) . toURL ( ) ) ; } catch ( final Exception ignore ) { } } } return list ; }
|
Return a list of classes and jar files
|
40,652
|
public static final CClassLoader getLoader ( final String fpath ) { String path = fpath ; CClassLoader currentLoader = CClassLoader . rootLoader ; if ( path == null ) { return CClassLoader . getRootLoader ( ) ; } if ( path . startsWith ( CClassLoader . ROOT_LOADER ) ) { path = path . substring ( 10 ) ; } final StringTokenizer tokenizer = new StringTokenizer ( path , "/" , false ) ; while ( tokenizer . hasMoreTokens ( ) ) { final String name = tokenizer . nextToken ( ) ; currentLoader = currentLoader . getLoaderByName ( name ) ; } return currentLoader ; }
|
return the loader with the given path
|
40,653
|
public static final CClassLoader getRootLoader ( ) { if ( CClassLoader . rootLoader == null ) { CClassLoader . rootLoader = CClassLoader . createLoader ( CClassLoader . class . getClassLoader ( ) , CClassLoader . ROOT_LOADER ) ; } return CClassLoader . rootLoader ; }
|
return the rootloader
|
40,654
|
public static URL [ ] getURLs ( final String path ) { final File topDir = new File ( path ) ; final List list = new ArrayList ( ) ; CClassLoader . getClasses ( topDir , list ) ; final URL ret [ ] = new URL [ list . size ( ) + 1 ] ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { ret [ i ] = ( URL ) list . get ( i ) ; } try { ret [ list . size ( ) ] = topDir . toURI ( ) . toURL ( ) ; } catch ( final Exception ignore ) { } return ret ; }
|
Return a list of jar and classes located in path
|
40,655
|
public static final byte [ ] loadByteArray ( final InputStream in ) { try { final ByteArrayOutputStream bOut = new ByteArrayOutputStream ( ) ; final byte buffer [ ] = new byte [ 2048 ] ; int iNbByteRead = - 1 ; while ( ( iNbByteRead = in . read ( buffer ) ) != - 1 ) { bOut . write ( buffer , 0 , iNbByteRead ) ; } return bOut . toByteArray ( ) ; } catch ( final IOException ioe ) { return null ; } }
|
load the given inputstream in a byte array
|
40,656
|
public static final byte [ ] loadByteArray ( final URL urlToResource ) { InputStream in = null ; try { final URLConnection uc = urlToResource . openConnection ( ) ; uc . setUseCaches ( false ) ; in = uc . getInputStream ( ) ; return CClassLoader . loadByteArray ( in ) ; } catch ( final IOException ioe ) { return null ; } finally { try { in . close ( ) ; } catch ( final Exception ignore ) { } } }
|
load the given url in a byte array
|
40,657
|
private static final void loadResources ( final CClassLoader loader , final List URLList , final String resourceName ) { final List l = loader . getPrivateResource ( resourceName ) ; if ( l != null ) { URLList . addAll ( l ) ; } final List loaderList = new ArrayList ( ) ; for ( final Iterator it = loader . childrenMap . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { final Entry entry = ( Entry ) it . next ( ) ; loaderList . add ( entry . getValue ( ) ) ; } for ( int i = 0 ; i < loaderList . size ( ) ; i ++ ) { final Object element = loaderList . get ( i ) ; final CClassLoader child = ( CClassLoader ) element ; CClassLoader . loadResources ( child , URLList , resourceName ) ; } }
|
load multiple resources of same name
|
40,658
|
private static final void log ( final String Message , final int level ) { if ( ( level == CClassLoader . INFO ) && CClassLoader . log . isLoggable ( Level . INFO ) ) { CClassLoader . log . info ( Message ) ; } else if ( ( level == CClassLoader . DEBUG ) && CClassLoader . log . isLoggable ( Level . FINE ) ) { CClassLoader . log . fine ( Message ) ; } else if ( ( level == CClassLoader . FATAL ) && CClassLoader . log . isLoggable ( Level . SEVERE ) ) { CClassLoader . log . severe ( Message ) ; } }
|
log the message
|
40,659
|
public static void releaseMemoryURL ( final URL u ) { try { final Class c = ClassLoader . getSystemClassLoader ( ) . loadClass ( "org.allcolor.yahp.converter.CMemoryURLHandler" ) ; final Method m = c . getDeclaredMethod ( "releaseMemoryURL" , new Class [ ] { URL . class } ) ; m . setAccessible ( true ) ; m . invoke ( null , new Object [ ] { u } ) ; } catch ( final Exception ignore ) { ignore . printStackTrace ( ) ; } }
|
Release a previously allocated memory URL
|
40,660
|
private static final void setInit ( final CClassLoader loader ) { loader . booInit = true ; for ( final Iterator it = loader . getChildLoader ( ) ; it . hasNext ( ) ; ) { final Map . Entry entry = ( Map . Entry ) it . next ( ) ; CClassLoader . setInit ( ( CClassLoader ) entry . getValue ( ) ) ; } }
|
set the init flag of all loaders
|
40,661
|
private static final boolean sl ( final int level ) { if ( ( level == CClassLoader . INFO ) && CClassLoader . log . isLoggable ( Level . INFO ) ) { return true ; } else if ( ( level == CClassLoader . DEBUG ) && CClassLoader . log . isLoggable ( Level . FINE ) ) { return true ; } else if ( ( level == CClassLoader . FATAL ) && CClassLoader . log . isLoggable ( Level . SEVERE ) ) { return true ; } return false ; }
|
test if the logging level is enabled
|
40,662
|
private final void _destroy ( final Method logFactoryRelease ) { for ( final Iterator it = this . childrenMap . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { final Map . Entry entry = ( Map . Entry ) it . next ( ) ; final CClassLoader loader = ( CClassLoader ) entry . getValue ( ) ; loader . _destroy ( logFactoryRelease ) ; it . remove ( ) ; } try { logFactoryRelease . invoke ( null , new Object [ ] { this } ) ; } catch ( final Exception e ) { } try { final Field parent = ClassLoader . class . getDeclaredField ( "parent" ) ; parent . setAccessible ( true ) ; parent . set ( this , ClassLoader . getSystemClassLoader ( ) ) ; parent . setAccessible ( false ) ; } catch ( final Throwable ignore ) { } this . classesMap . clear ( ) ; for ( final Iterator it = this . dllMap . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { final Object element = it . next ( ) ; final Map . Entry entry = ( Map . Entry ) element ; if ( entry . getValue ( ) instanceof File ) { ( ( File ) entry . getValue ( ) ) . delete ( ) ; } } this . cacheMap . clear ( ) ; this . dllMap . clear ( ) ; this . resourcesMap . clear ( ) ; this . config = null ; this . name = null ; this . finalizepath = this . path ; this . path = null ; System . runFinalization ( ) ; System . gc ( ) ; }
|
Destroy instance variables .
|
40,663
|
public final void addClass ( final String className , final URL urlToClass ) { if ( ( className == null ) || ( urlToClass == null ) ) { return ; } if ( ! this . classesMap . containsKey ( className ) ) { this . classesMap . put ( className , urlToClass ) ; } }
|
add a class to known class
|
40,664
|
public final void addResource ( final String resouceName , final URL urlToResource ) { if ( ( urlToResource == null ) || ( resouceName == null ) ) { return ; } if ( this . resourcesMap . containsKey ( resouceName . replace ( '\\' , '/' ) ) ) { final Object to = this . resourcesMap . get ( resouceName . replace ( '\\' , '/' ) ) ; if ( to instanceof URL ) { final URL uo = ( URL ) to ; final List l = new ArrayList ( ) ; l . add ( uo ) ; this . resourcesMap . put ( resouceName . replace ( '\\' , '/' ) , l ) ; } else if ( to instanceof List ) { final List uo = ( List ) to ; uo . add ( urlToResource ) ; this . resourcesMap . put ( resouceName . replace ( '\\' , '/' ) , uo ) ; } } else { this . resourcesMap . put ( resouceName . replace ( '\\' , '/' ) , urlToResource ) ; } }
|
add a resource
|
40,665
|
private final CClassLoader getLoaderByName ( final String name ) { try { CClassLoader loader = ( CClassLoader ) this . childrenMap . get ( name ) ; if ( loader == null ) { loader = CClassLoader . createLoader ( this , name ) ; this . childrenMap . put ( name , loader ) ; } return loader ; } finally { try { } catch ( final Exception ignore ) { } } }
|
Return the child loader with the given name
|
40,666
|
private final List getPrivateResource ( final String name ) { try { final Object to = this . resourcesMap . get ( name ) ; final List list = new ArrayList ( ) ; if ( to instanceof URL ) { list . add ( ( URL ) to ) ; return list ; } else if ( to instanceof List ) { final List l = ( List ) to ; for ( int i = 0 ; i < l . size ( ) ; i ++ ) { list . add ( ( URL ) l . get ( i ) ) ; } return list ; } else { return null ; } } finally { try { } catch ( final Exception ignore ) { } } }
|
get the resource with the given name
|
40,667
|
private final String nGetLoaderPath ( ) { ClassLoader currentLoader = this ; final StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( this . name ) ; while ( ( currentLoader = currentLoader . getParent ( ) ) != null ) { if ( currentLoader . getClass ( ) == CClassLoader . class ) { buffer . insert ( 0 , "/" ) ; buffer . insert ( 0 , ( ( CClassLoader ) currentLoader ) . name ) ; } else { break ; } } return buffer . toString ( ) ; }
|
calculate the loader path
|
40,668
|
public final void reload ( final CClassLoaderConfig config ) { if ( this == CClassLoader . getRootLoader ( ) ) { return ; } if ( config == null ) { return ; } final CClassLoader parent = ( ( CClassLoader ) this . getParent ( ) ) ; parent . removeLoader ( this . name ) ; if ( this . isMandatory ( ) ) { CClassLoader . mandatoryLoadersMap . remove ( this . getPath ( ) ) ; } final CClassLoader newLoader = CClassLoader . getLoader ( parent . getPath ( ) + "/" + this . name ) ; newLoader . config = this . config ; newLoader . booAlone = this . booAlone ; newLoader . booMandatory = this . booMandatory ; newLoader . booResourceOnly = this . booResourceOnly ; newLoader . booDoNotForwardToParent = this . booDoNotForwardToParent ; final List list = ( List ) config . getFilesMap ( ) . get ( this . path ) ; for ( final Iterator f = list . iterator ( ) ; f . hasNext ( ) ; ) { final URL file = ( URL ) f . next ( ) ; newLoader . readDirectories ( file ) ; } final Iterator it = this . childrenMap . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { final CClassLoader child = ( CClassLoader ) this . childrenMap . get ( it . next ( ) ) ; child . reload ( ) ; } this . _destroy ( null ) ; if ( newLoader . isMandatory ( ) ) { CClassLoader . mandatoryLoadersMap . put ( newLoader . getPath ( ) , newLoader ) ; } newLoader . booInit = true ; }
|
reload this loader
|
40,669
|
public final CClassLoader removeLoader ( final String loaderToRemove ) { if ( loaderToRemove . trim ( ) . length ( ) == 0 ) { throw new NullPointerException ( ) ; } return ( CClassLoader ) this . childrenMap . remove ( loaderToRemove ) ; }
|
remove the given loader from this loader
|
40,670
|
private static final int getSecurityFlags ( final Map properties ) { int securityType = 0 ; securityType = "true" . equals ( properties . get ( IHtmlToPdfTransformer . PDF_ALLOW_PRINTING ) ) ? ( securityType | PdfWriter . ALLOW_PRINTING ) : securityType ; securityType = "true" . equals ( properties . get ( IHtmlToPdfTransformer . PDF_ALLOW_MODIFY_CONTENTS ) ) ? ( securityType | PdfWriter . ALLOW_MODIFY_CONTENTS ) : securityType ; securityType = "true" . equals ( properties . get ( IHtmlToPdfTransformer . PDF_ALLOW_COPY ) ) ? ( securityType | PdfWriter . ALLOW_COPY ) : securityType ; securityType = "true" . equals ( properties . get ( IHtmlToPdfTransformer . PDF_ALLOW_MODIFT_ANNOTATIONS ) ) ? ( securityType | PdfWriter . ALLOW_MODIFY_ANNOTATIONS ) : securityType ; securityType = "true" . equals ( properties . get ( IHtmlToPdfTransformer . PDF_ALLOW_FILLIN ) ) ? ( securityType | PdfWriter . ALLOW_FILL_IN ) : securityType ; securityType = "true" . equals ( properties . get ( IHtmlToPdfTransformer . PDF_ALLOW_SCREEN_READERS ) ) ? ( securityType | PdfWriter . ALLOW_SCREENREADERS ) : securityType ; securityType = "true" . equals ( properties . get ( IHtmlToPdfTransformer . PDF_ALLOW_ASSEMBLY ) ) ? ( securityType | PdfWriter . ALLOW_ASSEMBLY ) : securityType ; securityType = "true" . equals ( properties . get ( IHtmlToPdfTransformer . PDF_ALLOW_DEGRADED_PRINTING ) ) ? ( securityType | PdfWriter . ALLOW_DEGRADED_PRINTING ) : securityType ; return securityType ; }
|
return the itext security flags for encryption
|
40,671
|
public static void destroy ( ) { try { countMutex . acquire ( ) ; for ( int i = 0 ; i < fileToDeleteOnDestroy . size ( ) ; i ++ ) { File f = ( File ) fileToDeleteOnDestroy . get ( i ) ; if ( f != null && f . exists ( ) ) try { f . delete ( ) ; } catch ( Exception ignore ) { } } CClassLoader . destroy ( ) ; } finally { countInstance = 0 ; try { countMutex . release ( ) ; } catch ( final Exception e ) { } } }
|
Delete the jar file from the temp directory Destroy the classloader
|
40,672
|
public final void convertToPdf ( final URL url , final IHtmlToPdfTransformer . PageSize size , final List hf , final OutputStream out , final Map fproperties ) throws CConvertException { Map properties = ( fproperties != null ) ? fproperties : new HashMap ( ) ; ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; int priority = Thread . currentThread ( ) . getPriority ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( new URLClassLoader ( new URL [ 0 ] , this . useClassLoader ? CClassLoader . getLoader ( "/main" ) : this . getClass ( ) . getClassLoader ( ) ) ) ; Thread . currentThread ( ) . setPriority ( Thread . MIN_PRIORITY ) ; String uri = url . toExternalForm ( ) ; if ( uri . indexOf ( "://" ) != - 1 ) { String tmp = uri . substring ( uri . indexOf ( "://" ) + 3 ) ; if ( tmp . indexOf ( '/' ) == - 1 ) { uri += "/" ; } } uri = uri . substring ( 0 , uri . lastIndexOf ( "/" ) + 1 ) ; if ( uri . startsWith ( "file:/" ) ) { uri = uri . substring ( 6 ) ; while ( uri . startsWith ( "/" ) ) { uri = uri . substring ( 1 ) ; } uri = "file:///" + uri ; } try { IHtmlToPdfTransformer transformer = getTransformer ( properties ) ; transformer . transform ( url . openStream ( ) , uri , size , hf , properties , out ) ; } catch ( final CConvertException e ) { throw e ; } catch ( final Exception e ) { throw new CConvertException ( e . getMessage ( ) , e ) ; } } finally { Thread . currentThread ( ) . setContextClassLoader ( loader ) ; Thread . currentThread ( ) . setPriority ( priority ) ; } }
|
Convert the document pointed by url in a PDF file . This method is thread safe .
|
40,673
|
public final void convertToPdf ( final String content , final IHtmlToPdfTransformer . PageSize size , final List hf , final String furlForBase , final OutputStream out , final Map fproperties ) throws CConvertException { String urlForBase = furlForBase ; Map properties = ( fproperties != null ) ? fproperties : new HashMap ( ) ; if ( urlForBase != null ) { try { URL url = new URL ( urlForBase ) ; if ( url == null ) { throw new CConvertException ( "urlForBase must be a valid URI." , null ) ; } } catch ( final Exception e ) { throw new CConvertException ( "urlForBase must be a valid URI." , null ) ; } if ( urlForBase . indexOf ( "://" ) != - 1 ) { String tmp = urlForBase . substring ( urlForBase . indexOf ( "://" ) + 3 ) ; if ( tmp . indexOf ( '/' ) == - 1 ) { urlForBase += "/" ; } } } ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; int priority = Thread . currentThread ( ) . getPriority ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( new URLClassLoader ( new URL [ 0 ] , this . useClassLoader ? CClassLoader . getLoader ( "/main" ) : this . getClass ( ) . getClassLoader ( ) ) ) ; Thread . currentThread ( ) . setPriority ( Thread . MIN_PRIORITY ) ; try { IHtmlToPdfTransformer transformer = getTransformer ( properties ) ; transformer . transform ( new ByteArrayInputStream ( content . getBytes ( "utf-8" ) ) , urlForBase , size , hf , properties , out ) ; } catch ( final CConvertException e ) { throw e ; } catch ( final Exception e ) { throw new CConvertException ( e . getMessage ( ) , e ) ; } } finally { Thread . currentThread ( ) . setContextClassLoader ( loader ) ; Thread . currentThread ( ) . setPriority ( priority ) ; } }
|
Convert the document in content in a PDF file . This method is thread safe .
|
40,674
|
private final void init ( boolean useClassLoader ) { final CYaHPConverter converter = this ; System . out . println ( "Initializing..." ) ; long time = System . currentTimeMillis ( ) ; if ( ! useClassLoader ) { System . out . println ( "init time: " + ( System . currentTimeMillis ( ) - time ) ) ; return ; } if ( CClassLoader . getRootLoader ( ) . isInit ( ) ) { return ; } Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { public void run ( ) { try { converter . finalize ( ) ; } catch ( final Throwable e ) { } } } ) ; ClassLoader loader = this . getClass ( ) . getClassLoader ( ) ; CClassLoaderConfig config = new CClassLoaderConfig ( ) ; config . addLoaderInfo ( "/main" , new CClassLoaderConfig . CLoaderInfo ( true , true , false , false ) ) ; config . addFile ( "/main" , loader . getResource ( "itext-yahp.jar" ) ) ; config . addFile ( "/main" , loader . getResource ( "tidy-yahp.jar" ) ) ; config . addFile ( "/main" , loader . getResource ( "log4j-yahp.jar" ) ) ; config . addFile ( "/main" , loader . getResource ( "shanijar-yahp.jar" ) ) ; config . addFile ( "/main" , loader . getResource ( "xmlapi-yahp.jar" ) ) ; config . addFile ( "/main" , loader . getResource ( "yahp-internal.jar" ) ) ; config . addFile ( "/main" , loader . getResource ( "commonio-yahp.jar" ) ) ; config . addFile ( "/main" , loader . getResource ( "commonlog-yahp.jar" ) ) ; config . addFile ( "/main" , loader . getResource ( "core-renderer-yahp.jar" ) ) ; config . addFile ( "/main" , loader . getResource ( "jaxen-yahp.jar" ) ) ; CClassLoader . init ( config ) ; try { URL url = CClassLoader . getRootLoader ( ) . getResource ( "log4j.properties" ) ; if ( url != null ) { ClassLoader cx = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( CClassLoader . getRootLoader ( ) ) ; Class pc = CClassLoader . getRootLoader ( ) . loadClass ( "org.apache.log4j.PropertyConfigurator" ) ; Method configure = pc . getDeclaredMethod ( "configure" , new Class [ ] { URL . class } ) ; configure . invoke ( null , new Object [ ] { url } ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( cx ) ; } } } catch ( Exception ignore ) { } System . out . println ( "init time: " + ( System . currentTimeMillis ( ) - time ) ) ; }
|
initialize the classloader and the transformer
|
40,675
|
private IHtmlToPdfTransformer getTransformer ( final Map properties ) { try { mutex . acquire ( ) ; IHtmlToPdfTransformer transformer = null ; String rendererClassName = IHtmlToPdfTransformer . DEFAULT_PDF_RENDERER ; if ( ( properties != null ) && properties . containsKey ( IHtmlToPdfTransformer . PDF_RENDERER_CLASS ) ) { rendererClassName = ( String ) properties . get ( IHtmlToPdfTransformer . PDF_RENDERER_CLASS ) ; } if ( transformers . containsKey ( rendererClassName ) ) { transformer = ( IHtmlToPdfTransformer ) transformers . get ( rendererClassName ) ; } else { ClassLoader bootStrap = this . useClassLoader ? CClassLoader . getLoader ( "/main" ) : this . getClass ( ) . getClassLoader ( ) ; try { ClassLoader cx = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( this . useClassLoader ? CClassLoader . getRootLoader ( ) : this . getClass ( ) . getClassLoader ( ) ) ; transformer = ( IHtmlToPdfTransformer ) bootStrap . loadClass ( rendererClassName ) . newInstance ( ) ; transformers . put ( rendererClassName , transformer ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( cx ) ; } } catch ( final Exception e ) { e . printStackTrace ( ) ; System . err . println ( "SEVERE: Error while getting transformer '" + rendererClassName + "' ! : " + e . getMessage ( ) ) ; return null ; } } return transformer ; } finally { try { mutex . release ( ) ; } catch ( final Exception e ) { } } }
|
Get a transformer .
|
40,676
|
protected String signRSAWithQuote ( final List < StringPair > p ) { String param = join ( p , false , true ) ; String sign = rsaSign ( param ) ; return sign ; }
|
Mobile SDK join the fields with quote which is not documented at all .
|
40,677
|
public Map < String , Object > calculateObjects ( Map < String , Object > objects ) { Map < String , Object > result = new HashMap < String , Object > ( ) ; return result ; }
|
this is not the best way
|
40,678
|
private List < String > existingRootFiles ( ) { List < String > filesFound = new ArrayList < > ( ) ; for ( String path : SU_PATHS ) { if ( new File ( path ) . exists ( ) ) { filesFound . add ( path ) ; } } return filesFound ; }
|
Checks for files that are known to indicate root .
|
40,679
|
private List < String > existingRootPackages ( ) { ArrayList < String > packages = new ArrayList < > ( ) ; packages . addAll ( Arrays . asList ( KNOWN_ROOT_APPS_PACKAGES ) ) ; packages . addAll ( Arrays . asList ( KNOWN_DANGEROUS_APPS_PACKAGES ) ) ; packages . addAll ( Arrays . asList ( KNOWN_ROOT_CLOAKING_PACKAGES ) ) ; PackageManager pm = context . getPackageManager ( ) ; List < String > packagesFound = new ArrayList < > ( ) ; for ( String packageName : packages ) { try { pm . getPackageInfo ( packageName , 0 ) ; packagesFound . add ( packageName ) ; } catch ( PackageManager . NameNotFoundException e ) { } } return packagesFound ; }
|
Checks for packages that are known to indicate root .
|
40,680
|
private List < String > existingDangerousProperties ( ) { String [ ] lines = propertiesReader ( ) ; List < String > propertiesFound = new ArrayList < > ( ) ; for ( String line : lines ) { for ( String key : DANGEROUS_PROPERTIES . keySet ( ) ) { if ( line . contains ( key ) && line . contains ( DANGEROUS_PROPERTIES . get ( key ) ) ) { propertiesFound . add ( line ) ; } } } return propertiesFound ; }
|
Checks system properties for any dangerous properties that indicate root .
|
40,681
|
private List < String > existingRWPaths ( ) { String [ ] lines = mountReader ( ) ; List < String > pathsFound = new ArrayList < > ( ) ; for ( String line : lines ) { String [ ] args = line . split ( " " ) ; if ( args . length < 4 ) { Log . e ( TAG , String . format ( "Error formatting mount: %s" , line ) ) ; continue ; } String mountPoint = args [ 1 ] ; String mountOptions = args [ 3 ] ; for ( String pathToCheck : PATHS_THAT_SHOULD_NOT_BE_WRITABLE ) { if ( mountPoint . equalsIgnoreCase ( pathToCheck ) ) { for ( String option : mountOptions . split ( "," ) ) { if ( option . equalsIgnoreCase ( "rw" ) ) { pathsFound . add ( pathToCheck ) ; break ; } } } } } return pathsFound ; }
|
When you re root you can change the write permissions on common system directories . This method checks if any of the paths in PATHS_THAT_SHOULD_NOT_BE_WRITABLE are writable .
|
40,682
|
private Request makeRequest ( List < MobileEventJson > batch ) throws IOException { if ( batch . isEmpty ( ) ) { return null ; } Sift . Config config = configProvider . getConfig ( ) ; if ( config == null ) { Log . d ( TAG , "Missing Sift.Config object" ) ; return null ; } if ( config . accountId == null || config . beaconKey == null || config . serverUrlFormat == null ) { Log . d ( TAG , "Missing account ID, beacon key, and/or server URL format" ) ; return null ; } if ( batch . isEmpty ( ) ) { Log . d ( TAG , "Batch is null or empty" ) ; return null ; } URL url = new URL ( String . format ( config . serverUrlFormat , config . accountId ) ) ; final String encodedBeaconKey = Base64 . encodeToString ( config . beaconKey . getBytes ( US_ASCII ) , Base64 . NO_WRAP ) ; Map < String , String > headers = new HashMap < String , String > ( ) ; headers . put ( "Authorization" , "Basic " + encodedBeaconKey ) ; headers . put ( "Accept" , "application/json" ) ; headers . put ( "Content-Encoding" , "gzip" ) ; headers . put ( "Content-Type" , "application/json" ) ; ListRequestJson request = new ListRequestJson ( ) . withData ( Collections . < Object > unmodifiableList ( batch ) ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; OutputStream gzip = new GZIPOutputStream ( os ) ; Writer writer = new OutputStreamWriter ( gzip , UTF8 ) ; Sift . GSON . toJson ( request , writer ) ; writer . close ( ) ; Log . d ( TAG , String . format ( "Built HTTP request for batch of size %d" , batch . size ( ) ) ) ; return new Request . Builder ( ) . withMethod ( "PUT" ) . withUrl ( url ) . withHeaders ( headers ) . withBody ( os . toByteArray ( ) ) . build ( ) ; }
|
Builds a Request for the specified event batch
|
40,683
|
public List < T > getList ( ) { if ( isCacheEnabled ) { if ( cachedResult == null ) { cachedResult = makeUnmodifiableUniqueList ( ) ; } return cachedResult ; } else { return makeUnmodifiableUniqueList ( ) ; } }
|
Returns the list that this ListHolder backs .
|
40,684
|
private List < T > makeUnmodifiableUniqueList ( ) { Set < T > tmp = newHashSet ( ) ; List < T > uniques = newArrayList ( ) ; for ( T t : getIterable ( ) ) { if ( tmp . add ( t ) ) { uniques . add ( t ) ; } } sort ( uniques ) ; return unmodifiableList ( uniques ) ; }
|
remove duplication if any
|
40,685
|
public List < T > getSubList ( int maxSubListSize ) { List < T > subList = newArrayList ( ) ; int counter = 0 ; for ( T t : getList ( ) ) { if ( counter ++ < maxSubListSize ) { subList . add ( t ) ; } else { break ; } } return subList ; }
|
Returns at most the first maxSubListSize elements of this list .
|
40,686
|
public SimpleListHolder < T > except ( String ... namesToExclude ) { String key = "current" + getCacheKey ( namesToExclude ) ; SimpleListHolder < T > result = cache . get ( key ) ; if ( result == null ) { result = new SimpleListHolder < T > ( getIterable ( ) , asNameNotEqualsToPredicates ( namesToExclude ) , getSortProperty ( ) ) ; cache . put ( key , result ) ; } return result ; }
|
Fork this list with extra predicates .
|
40,687
|
public int inputStreamToOutputStream ( InputStream is , OutputStream os ) throws IOException { byte buffer [ ] = new byte [ 1024 * 100 ] ; int len = - 1 ; int total = 0 ; while ( ( len = is . read ( buffer ) ) >= 0 ) { os . write ( buffer , 0 , len ) ; total += len ; } return total ; }
|
Write to the outputstream the bytes read from the input stream .
|
40,688
|
public void inputStreamToFile ( InputStream is , String filename ) throws IOException { FileOutputStream fos = new FileOutputStream ( filename ) ; inputStreamToOutputStream ( is , fos ) ; fos . close ( ) ; }
|
Write to a file the bytes read from an input stream .
|
40,689
|
public String inputStreamToString ( InputStream is , String charset ) throws IOException { InputStreamReader isr = null ; if ( null == charset ) { isr = new InputStreamReader ( is ) ; } else { isr = new InputStreamReader ( is , charset ) ; } StringWriter sw = new StringWriter ( ) ; int c = - 1 ; while ( ( c = isr . read ( ) ) != - 1 ) { sw . write ( c ) ; } isr . close ( ) ; return sw . getBuffer ( ) . toString ( ) ; }
|
Write to a string the bytes read from an input stream .
|
40,690
|
public boolean isParentAnEmptyDirectory ( File file ) { File parent = file . getParentFile ( ) ; if ( parent != null && parent . exists ( ) && parent . isDirectory ( ) && parent . list ( ) . length == 0 ) { return true ; } return false ; }
|
Determine if the directory where the passed file resides is empty .
|
40,691
|
public void pruneEmptyDirs ( File targetFile ) { while ( isParentAnEmptyDirectory ( targetFile ) ) { try { targetFile . getParentFile ( ) . delete ( ) ; targetFile = targetFile . getParentFile ( ) ; } catch ( Exception e ) { } } }
|
prune empty dir
|
40,692
|
@ SuppressWarnings ( "unchecked" ) public Collection < String > listFolders ( File folder ) { IOFileFilter ioFileFilter = FileFilterUtils . makeSVNAware ( FileFilterUtils . makeCVSAware ( FileFilterUtils . trueFileFilter ( ) ) ) ; Collection < File > files = FileUtils . listFiles ( folder , FileFilterUtils . fileFileFilter ( ) , ioFileFilter ) ; Set < String > ret = newTreeSet ( ) ; for ( File file : files ) { ret . add ( file . getParentFile ( ) . getAbsolutePath ( ) ) ; } return ret ; }
|
Recurse in the folder to get the list all files and folders of all non svn files
|
40,693
|
public void forceDelete ( File tempFile ) { try { if ( tempFile != null && tempFile . exists ( ) ) { FileUtils . forceDelete ( tempFile ) ; } } catch ( Throwable t ) { t . printStackTrace ( ) ; } }
|
force the deletion of a file
|
40,694
|
public List < String > getAnnotations ( ) { AnnotationBuilder result = new AnnotationBuilder ( ) ; result . add ( getFixedLengthAnnotation ( ) , getLengthAnnotation ( ) , getNotNullAnnotation ( ) , getNotEmptyAnnotation ( ) , getCharPaddingAnnotation ( ) , getEmailAnnotation ( ) , getDigitsAnnotation ( ) , getSafeHtmlAnnotation ( ) , getUrlAnnotation ( ) ) ; return result . getAnnotations ( ) ; }
|
Returns all the validation annotations for the attribute . Imports are processed automatically .
|
40,695
|
private String convertFileNameToBaseClassName ( String filename ) { if ( filename . endsWith ( "_.java" ) ) { return substringBeforeLast ( filename , "_.java" ) + BASE_SUFFIX_ ; } else { return substringBeforeLast ( filename , ".java" ) + BASE_SUFFIX ; } }
|
add Base to a given java filename it is used for transparently subclassing generated classes
|
40,696
|
private String getFullPathForLog ( OutputResult or , String targetFilename ) { if ( or . sameDirectory ( ) ) { return targetFilename ; } else { return or . getGeneratedSource ( ) . getFullPath ( targetFilename ) ; } }
|
Use it only to display proper path in log
|
40,697
|
private void buildSimpleEntity ( EntityConfig entityConfig , Entity entity ) { Table table = entity . getTable ( ) ; for ( Column column : table . getColumns ( ) ) { boolean processed = processColumnUsingColumnConfigIfAny ( entityConfig , entity , column ) ; if ( ! processed ) { entity . addAttribute ( attributeFactory . build ( entity , table , column ) ) ; } } processInvalidColumnConfigAndJpaSecondaryTable ( entityConfig , entity ) ; }
|
Build simple entity using user configuration
|
40,698
|
private void namerDefault ( Entity entity ) { entity . put ( "searchForm" , new ClassNamer2 ( entity , null , "web.domain" , null , "SearchForm" ) ) ; entity . put ( "editForm" , new ClassNamer2 ( entity , null , "web.domain" , null , "EditForm" ) ) ; entity . put ( "graphLoader" , new ClassNamer2 ( entity , null , "web.domain" , null , "GraphLoader" ) ) ; entity . put ( "controller" , new ClassNamer2 ( entity , null , "web.domain" , null , "Controller" ) ) ; entity . put ( "excelExporter" , new ClassNamer2 ( entity , null , "web.domain" , null , "ExcelExporter" ) ) ; entity . put ( "lazyDataModel" , new ClassNamer2 ( entity , null , "web.domain" , null , "LazyDataModel" ) ) ; entity . put ( "fileUpload" , new ClassNamer2 ( entity , null , "web.domain" , null , "FileUpload" ) ) ; entity . put ( "fileDownload" , new ClassNamer2 ( entity , null , "web.domain" , null , "FileDownload" ) ) ; }
|
Namers declared here can be overridden easily through configuration .
|
40,699
|
public static String toReadablePluralLabel ( String value ) { String label = toReadableLabel ( value ) ; return label . endsWith ( "ss" ) ? label . substring ( 0 , label . length ( ) - 1 ) : label ; }
|
Convert strings such as banquePayss to Banque Pays it will remove trailing ss and replace them with s
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.