idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
5,500
@ SuppressWarnings ( "unchecked" ) protected void executeReport ( Locale locale ) throws MavenReportException { getLog ( ) . info ( "Starting generating ajdoc" ) ; project . getCompileSourceRoots ( ) . add ( basedir . getAbsolutePath ( ) + "/" + aspectDirectory ) ; project . getTestCompileSourceRoots ( ) . add ( basedir . getAbsolutePath ( ) + "/" + testAspectDirectory ) ; List < String > arguments = new ArrayList < String > ( ) ; arguments . add ( "-classpath" ) ; arguments . add ( AjcHelper . createClassPath ( project , pluginArtifacts , getClasspathDirectories ( ) ) ) ; arguments . addAll ( ajcOptions ) ; Set < String > includes ; try { if ( null != ajdtBuildDefFile ) { includes = AjcHelper . getBuildFilesForAjdtFile ( ajdtBuildDefFile , basedir ) ; } else { includes = AjcHelper . getBuildFilesForSourceDirs ( getSourceDirectories ( ) , this . includes , this . excludes ) ; } } catch ( MojoExecutionException e ) { throw new MavenReportException ( "AspectJ Report failed" , e ) ; } arguments . add ( "-d" ) ; arguments . add ( StringUtils . replace ( getOutputDirectory ( ) , "//" , "/" ) ) ; arguments . addAll ( includes ) ; if ( getLog ( ) . isDebugEnabled ( ) ) { StringBuilder command = new StringBuilder ( "Running : ajdoc " ) ; for ( String argument : arguments ) { command . append ( ' ' ) . append ( argument ) ; } getLog ( ) . debug ( command ) ; } ClassLoader oldContextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( this . getClass ( ) . getClassLoader ( ) ) ; Main . setOutputWorkingDir ( buildDirectory . getAbsolutePath ( ) ) ; Main . main ( ( String [ ] ) arguments . toArray ( new String [ 0 ] ) ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( oldContextClassLoader ) ; } }
Executes this ajdoc - report generation .
5,501
@ SuppressWarnings ( "unchecked" ) protected List < String > getSourceDirectories ( ) { List < String > sourceDirectories = new ArrayList < String > ( ) ; sourceDirectories . addAll ( project . getCompileSourceRoots ( ) ) ; sourceDirectories . addAll ( project . getTestCompileSourceRoots ( ) ) ; return sourceDirectories ; }
Get the directories containg sources
5,502
protected List < String > getClasspathDirectories ( ) { return Arrays . asList ( project . getBuild ( ) . getOutputDirectory ( ) , project . getBuild ( ) . getTestOutputDirectory ( ) ) ; }
get compileroutput directory .
5,503
public void setComplianceLevel ( String complianceLevel ) { if ( AjcHelper . isValidComplianceLevel ( complianceLevel ) ) { ajcOptions . add ( "-source" ) ; ajcOptions . add ( complianceLevel ) ; } }
Setters which when called sets compiler arguments
5,504
protected void assembleArguments ( ) throws MojoExecutionException { if ( XhasMember ) { ajcOptions . add ( "-XhasMember" ) ; } ajcOptions . add ( "-classpath" ) ; ajcOptions . add ( AjcHelper . createClassPath ( project , null , getClasspathDirectories ( ) ) ) ; if ( null != bootclasspath ) { ajcOptions . add ( "-bootclasspath" ) ; ajcOptions . add ( bootclasspath ) ; } if ( null != Xjoinpoints ) { ajcOptions . add ( "-Xjoinpoints:" + Xjoinpoints ) ; } if ( null != warn ) { ajcOptions . add ( "-warn:" + warn ) ; } if ( null != proc ) { ajcOptions . add ( "-proc:" + proc ) ; } if ( Xset != null && ! Xset . isEmpty ( ) ) { StringBuilder sb = new StringBuilder ( "-Xset:" ) ; for ( Map . Entry < String , String > param : Xset . entrySet ( ) ) { sb . append ( param . getKey ( ) ) ; sb . append ( "=" ) ; sb . append ( param . getValue ( ) ) ; sb . append ( ',' ) ; } ajcOptions . add ( sb . substring ( 0 , sb . length ( ) - 1 ) ) ; } String joinedWeaveDirectories = null ; if ( weaveDirectories != null ) { joinedWeaveDirectories = StringUtils . join ( weaveDirectories , File . pathSeparator ) ; } addModulesArgument ( "-inpath" , ajcOptions , weaveDependencies , joinedWeaveDirectories , "dependencies and/or directories to weave" ) ; addModulesArgument ( "-aspectpath" , ajcOptions , aspectLibraries , getAdditionalAspectPaths ( ) , "an aspect library" ) ; if ( null != xmlConfigured ) { ajcOptions . add ( "-xmlConfigured" ) ; ajcOptions . add ( xmlConfigured . getAbsolutePath ( ) ) ; } ajcOptions . add ( "-d" ) ; ajcOptions . add ( getOutputDirectory ( ) . getAbsolutePath ( ) ) ; ajcOptions . add ( "-s" ) ; ajcOptions . add ( getGeneratedSourcesDirectory ( ) . getAbsolutePath ( ) ) ; if ( null != ajdtBuildDefFile ) { resolvedIncludes = AjcHelper . getBuildFilesForAjdtFile ( ajdtBuildDefFile , basedir ) ; } else { resolvedIncludes = getIncludedSources ( ) ; } ajcOptions . addAll ( resolvedIncludes ) ; }
Assembles a complete ajc compiler arguments list .
5,505
private void addModulesArgument ( final String argument , final List < String > arguments , final Module [ ] modules , final String aditionalpath , final String role ) throws MojoExecutionException { StringBuilder buf = new StringBuilder ( ) ; if ( null != aditionalpath ) { arguments . add ( argument ) ; buf . append ( aditionalpath ) ; } if ( modules != null && modules . length > 0 ) { if ( ! arguments . contains ( argument ) ) { arguments . add ( argument ) ; } for ( int i = 0 ; i < modules . length ; ++ i ) { Module module = modules [ i ] ; Artifact artifact = null ; @ SuppressWarnings ( "unchecked" ) Set < Artifact > allArtifacts = project . getArtifacts ( ) ; for ( Artifact art : allArtifacts ) { if ( art . getGroupId ( ) . equals ( module . getGroupId ( ) ) && art . getArtifactId ( ) . equals ( module . getArtifactId ( ) ) && StringUtils . defaultString ( module . getClassifier ( ) ) . equals ( StringUtils . defaultString ( art . getClassifier ( ) ) ) && StringUtils . defaultString ( module . getType ( ) , "jar" ) . equals ( StringUtils . defaultString ( art . getType ( ) ) ) ) { artifact = art ; break ; } } if ( artifact == null ) { throw new MojoExecutionException ( "The artifact " + module . toString ( ) + " referenced in aspectj plugin as " + role + ", is not found the project dependencies" ) ; } if ( buf . length ( ) != 0 ) { buf . append ( File . pathSeparatorChar ) ; } buf . append ( artifact . getFile ( ) . getPath ( ) ) ; } } if ( buf . length ( ) > 0 ) { String pathString = buf . toString ( ) ; arguments . add ( pathString ) ; getLog ( ) . debug ( "Adding " + argument + ": " + pathString ) ; } }
Finds all artifacts in the weavemodule property and adds them to the ajc options .
5,506
protected boolean isBuildNeeded ( ) throws MojoExecutionException { File outDir = getOutputDirectory ( ) ; return hasNoPreviousBuild ( outDir ) || hasArgumentsChanged ( outDir ) || hasSourcesChanged ( outDir ) || hasNonWeavedClassesChanged ( outDir ) ; }
Checks modifications that would make us need a build
5,507
public RequestLogs next ( ) throws NoSuchElementException { Preconditions . checkNotNull ( logIterator , "Reader was not initialized via beginSlice()" ) ; if ( logIterator . hasNext ( ) ) { lastLog = logIterator . next ( ) ; return lastLog ; } else { log . fine ( "Shard completed: " + shardLogQuery . getStartTimeUsec ( ) + "-" + shardLogQuery . getEndTimeUsec ( ) ) ; throw new NoSuchElementException ( ) ; } }
Retrieve the next RequestLog
5,508
public Double getProgress ( ) { if ( ( shardLogQuery . getStartTimeUsec ( ) == null ) || ( shardLogQuery . getEndTimeUsec ( ) == null ) ) { return null ; } else if ( lastLog == null ) { return 0.0 ; } else { long processedTimeUsec = shardLogQuery . getEndTimeUsec ( ) - lastLog . getEndTimeUsec ( ) ; long totalTimeUsec = shardLogQuery . getEndTimeUsec ( ) - shardLogQuery . getStartTimeUsec ( ) ; return ( ( double ) processedTimeUsec / totalTimeUsec ) ; } }
Determine the approximate progress for this shard assuming the RequestLogs are uniformly distributed across the entire time range .
5,509
private static void enqueueCallbackTask ( final ShufflerParams shufflerParams , final String url , final String taskName ) { RetryHelper . runWithRetries ( callable ( new Runnable ( ) { public void run ( ) { String hostname = ModulesServiceFactory . getModulesService ( ) . getVersionHostname ( shufflerParams . getCallbackModule ( ) , shufflerParams . getCallbackVersion ( ) ) ; Queue queue = QueueFactory . getQueue ( shufflerParams . getCallbackQueue ( ) ) ; String separater = shufflerParams . getCallbackPath ( ) . contains ( "?" ) ? "&" : "?" ; try { queue . add ( TaskOptions . Builder . withUrl ( shufflerParams . getCallbackPath ( ) + separater + url ) . method ( TaskOptions . Method . GET ) . header ( "Host" , hostname ) . taskName ( taskName ) ) ; } catch ( TaskAlreadyExistsException e ) { } } } ) , RETRY_PARAMS , EXCEPTION_HANDLER ) ; }
Notifies the caller that the job has completed .
5,510
public GoogleCloudStorageFileSet finish ( Collection < ? extends OutputWriter < ByteBuffer > > writers ) { List < String > out = Lists . newArrayList ( ) ; for ( OutputWriter < ByteBuffer > w : writers ) { GoogleCloudStorageFileOutputWriter writer = ( GoogleCloudStorageFileOutputWriter ) w ; out . add ( writer . getFile ( ) . getObjectName ( ) ) ; } return new GoogleCloudStorageFileSet ( bucket , out ) ; }
Returns a list of GcsFilename that has one element for each reduce shard .
5,511
public void beginSlice ( ) throws IOException { writer = createWriter ( sliceCount ++ ) ; writer . setContext ( getContext ( ) ) ; writer . beginShard ( ) ; writer . beginSlice ( ) ; }
Creates a new writer .
5,512
public static < I , Void , V > MapOnlyMapper < I , V > forMapper ( Mapper < I , Void , V > mapper ) { return new MapperAdapter < > ( mapper ) ; }
Returns a MapOnlyMapper for a given Mapper passing only the values to the output .
5,513
private void handleLockHeld ( String taskId , ShardedJobStateImpl < T > jobState , IncrementalTaskState < T > taskState ) { long currentTime = System . currentTimeMillis ( ) ; int sliceTimeoutMillis = jobState . getSettings ( ) . getSliceTimeoutMillis ( ) ; long lockExpiration = taskState . getLockInfo ( ) . lockedSince ( ) + sliceTimeoutMillis ; boolean wasRequestCompleted = wasRequestCompleted ( taskState . getLockInfo ( ) . getRequestId ( ) ) ; if ( lockExpiration > currentTime && ! wasRequestCompleted ) { long eta = Math . min ( lockExpiration , currentTime + 60_000 ) ; scheduleWorkerTask ( null , jobState . getSettings ( ) , taskState , eta ) ; log . info ( "Lock for " + taskId + " is being held. Will retry after " + ( eta - currentTime ) ) ; } else { ShardRetryState < T > retryState ; if ( wasRequestCompleted ) { retryState = handleSliceFailure ( jobState , taskState , new RuntimeException ( "Resuming after abandon lock for " + taskId + " on slice: " + taskState . getSequenceNumber ( ) ) , true ) ; } else { retryState = handleShardFailure ( jobState , taskState , new RuntimeException ( "Lock for " + taskId + " expired on slice: " + taskState . getSequenceNumber ( ) ) ) ; } updateTask ( jobState , taskState , retryState , false ) ; } }
Handle a locked slice case .
5,514
public ByteBuffer toBytes ( T object ) { if ( ! type . equals ( object . getClass ( ) ) ) { throw new RuntimeException ( "The type of the object does not match the parameter type of this marshaller. " ) ; } Map < String , Object > jsonObject = dataMarshaller . mapFieldNameToValue ( object ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; try { objectMapper . writeValue ( out , jsonObject ) ; out . write ( NEWLINE_CHARACTER . getBytes ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( "Error in serializing to bigquery json " + jsonObject , e ) ; } return ByteBuffer . wrap ( out . toByteArray ( ) ) ; }
Validates that the type of the object to serialize is the same as the type for which schema was generated . The type should match exactly as interface and abstract classes are not supported .
5,515
static void handleCommand ( String command , HttpServletRequest request , HttpServletResponse response ) { response . setContentType ( "application/json" ) ; boolean isPost = "POST" . equals ( request . getMethod ( ) ) ; JSONObject retValue = null ; try { if ( command . equals ( LIST_JOBS_PATH ) && ! isPost ) { retValue = handleListJobs ( request ) ; } else if ( command . equals ( CLEANUP_JOB_PATH ) && isPost ) { retValue = handleCleanupJob ( request . getParameter ( "mapreduce_id" ) ) ; } else if ( command . equals ( ABORT_JOB_PATH ) && isPost ) { retValue = handleAbortJob ( request . getParameter ( "mapreduce_id" ) ) ; } else if ( command . equals ( GET_JOB_DETAIL_PATH ) && ! isPost ) { retValue = handleGetJobDetail ( request . getParameter ( "mapreduce_id" ) ) ; } } catch ( Exception t ) { log . log ( Level . SEVERE , "Got exception while running command" , t ) ; try { retValue = new JSONObject ( ) ; retValue . put ( "error_class" , t . getClass ( ) . getName ( ) ) ; retValue . put ( "error_message" , "Full stack trace is available in the server logs. Message: " + t . getMessage ( ) ) ; } catch ( JSONException e ) { throw new RuntimeException ( "Couldn't create error JSON object" , e ) ; } } try { if ( retValue == null ) { response . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; } else { retValue . write ( response . getWriter ( ) ) ; response . getWriter ( ) . flush ( ) ; } } catch ( JSONException | IOException e ) { throw new RuntimeException ( "Couldn't write command response" , e ) ; } }
Handles all status page commands .
5,516
private List < Range > getScatterSplitPoints ( String namespace , String kind , final int numSegments ) { Query query = createQuery ( namespace , kind ) . addSort ( SCATTER_RESERVED_PROPERTY ) . setKeysOnly ( ) ; List < Key > splitPoints = sortKeys ( runQuery ( query , numSegments - 1 ) ) ; List < Range > result = new ArrayList < > ( splitPoints . size ( ) + 1 ) ; FilterPredicate lower = null ; for ( Key k : splitPoints ) { result . add ( new Range ( lower , new FilterPredicate ( KEY_RESERVED_PROPERTY , LESS_THAN , k ) ) ) ; lower = new FilterPredicate ( KEY_RESERVED_PROPERTY , GREATER_THAN_OR_EQUAL , k ) ; } result . add ( new Range ( lower , null ) ) ; logger . info ( "Requested " + numSegments + " segments, retrieved " + result . size ( ) ) ; return result ; }
Uses the scatter property to distribute ranges to segments .
5,517
public static void doGet ( HttpServletRequest request , HttpServletResponse response ) throws IOException { String handler = getHandler ( request ) ; if ( handler . startsWith ( COMMAND_PATH ) ) { if ( ! checkForAjax ( request , response ) ) { return ; } StatusHandler . handleCommand ( handler . substring ( COMMAND_PATH . length ( ) + 1 ) , request , response ) ; } else { handleStaticResources ( handler , response ) ; } }
Handle GET http requests .
5,518
public static void doPost ( HttpServletRequest request , HttpServletResponse response ) throws IOException { String handler = getHandler ( request ) ; if ( handler . startsWith ( CONTROLLER_PATH ) ) { if ( ! checkForTaskQueue ( request , response ) ) { return ; } new ShardedJobRunner < > ( ) . completeShard ( checkNotNull ( request . getParameter ( JOB_ID_PARAM ) , "Null job id" ) , checkNotNull ( request . getParameter ( TASK_ID_PARAM ) , "Null task id" ) ) ; } else if ( handler . startsWith ( WORKER_PATH ) ) { if ( ! checkForTaskQueue ( request , response ) ) { return ; } new ShardedJobRunner < > ( ) . runTask ( checkNotNull ( request . getParameter ( JOB_ID_PARAM ) , "Null job id" ) , checkNotNull ( request . getParameter ( TASK_ID_PARAM ) , "Null task id" ) , Integer . parseInt ( request . getParameter ( SEQUENCE_NUMBER_PARAM ) ) ) ; } else if ( handler . startsWith ( COMMAND_PATH ) ) { if ( ! checkForAjax ( request , response ) ) { return ; } StatusHandler . handleCommand ( handler . substring ( COMMAND_PATH . length ( ) + 1 ) , request , response ) ; } else { throw new RuntimeException ( "Received an unknown MapReduce request handler. See logs for more detail." ) ; } }
Handle POST http requests .
5,519
private static boolean checkForAjax ( HttpServletRequest request , HttpServletResponse response ) throws IOException { if ( ! "XMLHttpRequest" . equals ( request . getHeader ( "X-Requested-With" ) ) ) { log . log ( Level . SEVERE , "Received unexpected non-XMLHttpRequest command. Possible CSRF attack." ) ; response . sendError ( HttpServletResponse . SC_FORBIDDEN , "Received unexpected non-XMLHttpRequest command." ) ; return false ; } return true ; }
Checks to ensure that the current request was sent via an AJAX request .
5,520
private static boolean checkForTaskQueue ( HttpServletRequest request , HttpServletResponse response ) throws IOException { if ( request . getHeader ( "X-AppEngine-QueueName" ) == null ) { log . log ( Level . SEVERE , "Received unexpected non-task queue request. Possible CSRF attack." ) ; response . sendError ( HttpServletResponse . SC_FORBIDDEN , "Received unexpected non-task queue request." ) ; return false ; } return true ; }
Checks to ensure that the current request was sent via the task queue .
5,521
private static String getHandler ( HttpServletRequest request ) { String pathInfo = request . getPathInfo ( ) ; return pathInfo == null ? "" : pathInfo . substring ( 1 ) ; }
Returns the handler portion of the URL path .
5,522
public long claim ( long toClaimMb ) throws RejectRequestException { Preconditions . checkArgument ( toClaimMb >= 0 ) ; if ( toClaimMb == 0 ) { return 0 ; } int neededForRequest = capRequestedSize ( toClaimMb ) ; boolean acquired = false ; try { acquired = amountRemaining . tryAcquire ( neededForRequest , TIME_TO_WAIT , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new RejectRequestException ( "Was interupted" , e ) ; } int remaining = amountRemaining . availablePermits ( ) ; if ( acquired ) { log . info ( "Target available memory was " + ( neededForRequest + remaining ) + "mb is now " + remaining + "mb" ) ; return neededForRequest ; } else { throw new RejectRequestException ( "Not enough estimated memory for request: " + ( neededForRequest ) + "mb only have " + remaining + "mb remaining out of " + TOTAL_CLAIMABLE_MEMORY_SIZE_MB + "mb" ) ; } }
This method attempts to claim ram to the provided request . This may block waiting for some to be available . Ultimately it is either granted memory or an exception is thrown .
5,523
static < T extends IncrementalTask > IncrementalTaskState < T > create ( String taskId , String jobId , long createTime , T initialTask ) { return new IncrementalTaskState < > ( taskId , jobId , createTime , new LockInfo ( null , null ) , checkNotNull ( initialTask ) , new Status ( StatusCode . RUNNING ) ) ; }
Returns a new running IncrementalTaskState .
5,524
public void delete ( Key key ) { int bytesHere = KeyFactory . keyToString ( key ) . length ( ) ; if ( deletesBytes + bytesHere >= params . getBytesLimit ( ) ) { flushDeletes ( ) ; } deletesBytes += bytesHere ; deletes . add ( key ) ; if ( deletes . size ( ) >= params . getCountLimit ( ) ) { flushDeletes ( ) ; } }
Adds a mutation to put the given entity to the datastore .
5,525
public void put ( Entity entity ) { int bytesHere = EntityTranslator . convertToPb ( entity ) . getSerializedSize ( ) ; if ( putsBytes + bytesHere >= params . getBytesLimit ( ) ) { flushPuts ( ) ; } putsBytes += bytesHere ; puts . add ( entity ) ; if ( puts . size ( ) >= params . getCountLimit ( ) ) { flushPuts ( ) ; } }
Adds a mutation deleting the entity with the given key .
5,526
private void writeOutData ( ) { if ( valuesHeld == 0 ) { return ; } int batchSize = batchItemSizePerEmmit == null ? DEFAULT_SORT_BATCH_PER_EMIT_BYTES : batchItemSizePerEmmit ; ByteBuffer currentKey = getKeyValueFromPointer ( 0 ) . getKey ( ) ; List < ByteBuffer > currentValues = new ArrayList < > ( ) ; int totalSize = 0 ; for ( int i = 0 ; i < valuesHeld ; i ++ ) { KeyValue < ByteBuffer , ByteBuffer > keyValue = getKeyValueFromPointer ( i ) ; int compare = LexicographicalComparator . compareBuffers ( keyValue . getKey ( ) , currentKey ) ; if ( compare == 0 ) { if ( ! currentValues . isEmpty ( ) && totalSize >= batchSize ) { emitCurrentOrLeftover ( currentKey , currentValues ) ; totalSize = 0 ; } currentValues . add ( keyValue . getValue ( ) ) ; totalSize += Math . max ( 1 , keyValue . getValue ( ) . remaining ( ) ) ; } else if ( compare > 0 ) { emitCurrentOrLeftover ( currentKey , currentValues ) ; currentKey = keyValue . getKey ( ) ; currentValues . add ( keyValue . getValue ( ) ) ; totalSize = Math . max ( 1 , keyValue . getValue ( ) . remaining ( ) ) ; } else { throw new IllegalStateException ( "Sort failed to properly order output" ) ; } } emitCurrentOrLeftover ( currentKey , currentValues ) ; if ( leftover != null ) { emit ( leftover . getKey ( ) , leftover . getValue ( ) ) ; } }
Writes out the key value pairs in order . If there are multiple consecutive values with the same key they can be combined to avoid repeating the key . In the event the buffer is full there is one leftover item which did not go into it and hence was not sorted . So a merge between this one item and the sorted list is done on the way out .
5,527
public void addValue ( ByteBuffer key , ByteBuffer value ) { if ( isFull ) { throw new IllegalArgumentException ( "Already full" ) ; } if ( value . remaining ( ) + key . remaining ( ) + POINTER_SIZE_BYTES > memoryBuffer . remaining ( ) ) { leftover = new KeyValue < > ( key , value ) ; isFull = true ; } else { int keyPos = spliceIn ( key , memoryBuffer ) ; int valuePos = spliceIn ( value , memoryBuffer ) ; addPointer ( keyPos , key . remaining ( ) , valuePos , value . remaining ( ) ) ; } }
Add a new key and value to the in memory buffer .
5,528
final ByteBuffer getKeyFromPointer ( int index ) { int origionalLimit = memoryBuffer . limit ( ) ; memoryBuffer . limit ( memoryBuffer . capacity ( ) ) ; int pointerOffset = computePointerOffset ( index ) ; int keyPos = memoryBuffer . getInt ( pointerOffset ) ; int valuePos = memoryBuffer . getInt ( pointerOffset + 4 ) ; memoryBuffer . limit ( origionalLimit ) ; assert valuePos >= keyPos ; ByteBuffer key = sliceOutRange ( keyPos , valuePos ) ; return key ; }
Get a key given the index of its pointer .
5,529
final KeyValue < ByteBuffer , ByteBuffer > getKeyValueFromPointer ( int index ) { int origionalLimit = memoryBuffer . limit ( ) ; memoryBuffer . limit ( memoryBuffer . capacity ( ) ) ; int pointerOffset = computePointerOffset ( index ) ; int keyPos = memoryBuffer . getInt ( pointerOffset ) ; int valuePos = memoryBuffer . getInt ( pointerOffset + 4 ) ; int valueLength = memoryBuffer . getInt ( pointerOffset + 8 ) ; memoryBuffer . limit ( origionalLimit ) ; assert valuePos >= keyPos ; ByteBuffer key = sliceOutRange ( keyPos , valuePos ) ; ByteBuffer value = sliceOutRange ( valuePos , valuePos + valueLength ) ; return new KeyValue < > ( key , value ) ; }
Get a key and its value given the index of its pointer .
5,530
final void swapPointers ( int indexA , int indexB ) { assert indexA >= 0 && indexA < valuesHeld ; assert indexB >= 0 && indexB < valuesHeld ; ByteBuffer a = copyPointer ( indexA ) ; ByteBuffer b = readPointer ( indexB ) ; writePointer ( indexA , b ) ; writePointer ( indexB , a ) ; }
Place the pointer at indexA in indexB and vice versa .
5,531
final ByteBuffer readPointer ( int index ) { int pointerOffset = computePointerOffset ( index ) ; return sliceOutRange ( pointerOffset , pointerOffset + POINTER_SIZE_BYTES ) ; }
Read a pointer from the specified index .
5,532
final ByteBuffer copyPointer ( int index ) { ByteBuffer pointer = readPointer ( index ) ; ByteBuffer result = ByteBuffer . allocate ( pointer . capacity ( ) ) ; result . put ( pointer ) ; result . flip ( ) ; return result ; }
Get a Copy of a pointer
5,533
final void addPointer ( int keyPos , int keySize , int valuePos , int valueSize ) { assert keyPos + keySize == valuePos ; int start = memoryBuffer . limit ( ) - POINTER_SIZE_BYTES ; memoryBuffer . putInt ( start , keyPos ) ; memoryBuffer . putInt ( start + 4 , valuePos ) ; memoryBuffer . putInt ( start + 8 , valueSize ) ; memoryBuffer . limit ( start ) ; valuesHeld ++ ; }
Add a pointer to the key value pair with the provided parameters .
5,534
private static int spliceIn ( ByteBuffer src , ByteBuffer dest ) { int position = dest . position ( ) ; int srcPos = src . position ( ) ; dest . put ( src ) ; src . position ( srcPos ) ; return position ; }
Write the contents of src to dest without messing with src s position .
5,535
public static < T extends IncrementalTask > void runJob ( List < T > initialTasks , ShardedJobController < T > controller ) { List < T > results = new ArrayList < > ( ) ; for ( T task : initialTasks ) { Preconditions . checkNotNull ( task , "Null initial task: %s" , initialTasks ) ; task . prepare ( ) ; do { task . run ( ) ; } while ( ! task . isDone ( ) ) ; task . cleanup ( ) ; results . add ( task ) ; } controller . completed ( results . iterator ( ) ) ; }
Runs the given job and returns its result .
5,536
private static < K , V > List < KeyValue < K , List < V > > > multimapToList ( Marshaller < K > keyMarshaller , ListMultimap < Bytes , V > in ) { List < Bytes > keys = Ordering . natural ( ) . sortedCopy ( in . keySet ( ) ) ; ImmutableList . Builder < KeyValue < K , List < V > > > out = ImmutableList . builder ( ) ; for ( Bytes keyBytes : keys ) { K key = keyMarshaller . fromBytes ( ByteBuffer . wrap ( keyBytes . bytes ) ) ; out . add ( KeyValue . of ( key , in . get ( keyBytes ) ) ) ; } return out . build ( ) ; }
Also turns the keys back from Bytes into K .
5,537
public List < List < O > > finish ( Collection < ? extends OutputWriter < O > > writers ) { ImmutableList . Builder < List < O > > out = ImmutableList . builder ( ) ; for ( OutputWriter < O > w : writers ) { InMemoryOutputWriter < O > writer = ( InMemoryOutputWriter < O > ) w ; out . add ( ImmutableList . copyOf ( writer . getResult ( ) ) ) ; } return out . build ( ) ; }
Returns a list of lists where the outer list has one element for each reduce shard which is a list of the values emitted by that shard in order .
5,538
public KeyValue < K , Iterator < V > > next ( ) throws NoSuchElementException { if ( combineValues ) { skipLeftoverItems ( ) ; } PeekingInputReader < KeyValue < ByteBuffer , ? extends Iterable < V > > > reader = lowestReaderQueue . remove ( ) ; KeyValue < ByteBuffer , ? extends Iterable < V > > lowest = reader . next ( ) ; ByteBuffer lowestKey = lowest . getKey ( ) ; addReaderToQueueIfNotEmpty ( reader ) ; lastKey = SerializableValue . of ( getByteBufferMarshaller ( ) , lowestKey ) ; if ( combineValues ) { CombiningReader values = new CombiningReader ( lowestKey , lowest . getValue ( ) ) ; return new KeyValue < K , Iterator < V > > ( keyMarshaller . fromBytes ( lowestKey . slice ( ) ) , values ) ; } else { return new KeyValue < > ( keyMarshaller . fromBytes ( lowestKey . slice ( ) ) , lowest . getValue ( ) . iterator ( ) ) ; } }
Returns the next KeyValues object for the reducer . This is the entry point .
5,539
private void skipLeftoverItems ( ) { if ( lastKey == null || lowestReaderQueue . isEmpty ( ) ) { return ; } boolean itemSkiped ; do { PeekingInputReader < KeyValue < ByteBuffer , ? extends Iterable < V > > > reader = lowestReaderQueue . remove ( ) ; itemSkiped = skipItemsOnReader ( reader ) ; addReaderToQueueIfNotEmpty ( reader ) ; } while ( itemSkiped ) ; }
It is possible that a reducer does not iterate over all of the items given to it for a given key . However on the next callback they expect to receive items for the following key . this method skips over all the left over items from the previous key they did not read .
5,540
private boolean skipItemsOnReader ( PeekingInputReader < KeyValue < ByteBuffer , ? extends Iterable < V > > > reader ) { boolean itemSkipped = false ; KeyValue < ByteBuffer , ? extends Iterable < V > > keyValue = reader . peek ( ) ; while ( keyValue != null && compareBuffers ( keyValue . getKey ( ) , lastKey . getValue ( ) ) == 0 ) { consumePeekedValueFromReader ( keyValue , reader ) ; itemSkipped = true ; keyValue = reader . peek ( ) ; } return itemSkipped ; }
Helper function for skipLeftoverItems to skip items matching last key on a single reader .
5,541
private Record readPhysicalRecord ( boolean expectEnd ) throws IOException { int bytesToBlockEnd = findBytesToBlockEnd ( ) ; if ( bytesToBlockEnd < HEADER_LENGTH ) { readToTmp ( bytesToBlockEnd , expectEnd ) ; return createRecordFromTmp ( RecordType . NONE ) ; } readToTmp ( HEADER_LENGTH , expectEnd ) ; int checksum = tmpBuffer . getInt ( ) ; int length = tmpBuffer . getShort ( ) ; if ( length > bytesToBlockEnd || length < 0 ) { throw new CorruptDataException ( "Length is too large:" + length ) ; } RecordType type = RecordType . get ( tmpBuffer . get ( ) ) ; if ( type == RecordType . NONE && length == 0 ) { length = bytesToBlockEnd - HEADER_LENGTH ; } readToTmp ( length , false ) ; if ( ! isValidCrc ( checksum , tmpBuffer , type . value ( ) ) ) { throw new CorruptDataException ( "Checksum doesn't validate." ) ; } return createRecordFromTmp ( type ) ; }
Reads the next record from the LevelDb data stream .
5,542
private static ByteBuffer copyAll ( List < ByteBuffer > buffers ) { int size = 0 ; for ( ByteBuffer b : buffers ) { size += b . remaining ( ) ; } ByteBuffer result = allocate ( size ) ; for ( ByteBuffer b : buffers ) { result . put ( b ) ; } result . flip ( ) ; return result ; }
Copies a list of byteBuffers into a single new byteBuffer .
5,543
public GoogleCloudStorageFileSet finish ( Collection < ? extends OutputWriter < ByteBuffer > > writers ) throws IOException { List < String > fileNames = new ArrayList < > ( ) ; for ( OutputWriter < ByteBuffer > writer : writers ) { SizeSegmentingGoogleCloudStorageFileWriter segWriter = ( SizeSegmentingGoogleCloudStorageFileWriter ) writer ; for ( GoogleCloudStorageFileOutputWriter delegatedWriter : segWriter . getDelegatedWriters ( ) ) { fileNames . add ( delegatedWriter . getFile ( ) . getObjectName ( ) ) ; } } return new GoogleCloudStorageFileSet ( bucket , fileNames ) ; }
Returns a list of all the filenames written by the output writers
5,544
public static void validateNestedParameterizedType ( Type parameterType ) { if ( isParameterized ( parameterType ) || GenericArrayType . class . isAssignableFrom ( parameterType . getClass ( ) ) ) { throw new IllegalArgumentException ( "Invalid field. Cannot marshal fields of type Collection<GenericType> or GenericType[]." ) ; } }
Parameterized types nested more than one level cannot be determined at runtime . So cannot be marshalled .
5,545
public static Class < ? > getParameterTypeOfRepeatedField ( Field field ) { Class < ? > componentType = null ; if ( isCollection ( field . getType ( ) ) ) { validateCollection ( field ) ; Type parameterType = getParameterType ( ( ParameterizedType ) field . getGenericType ( ) ) ; validateNestedParameterizedType ( parameterType ) ; componentType = ( Class < ? > ) parameterType ; } else if ( field . getType ( ) . isArray ( ) ) { componentType = field . getType ( ) . getComponentType ( ) ; return componentType ; } else { throw new IllegalArgumentException ( "Unsupported repeated type " + field . getType ( ) + " Allowed repeated fields are Collection<T> and arrays" ) ; } validateNestedRepeatedType ( componentType , field ) ; return componentType ; }
Returns type of the parameter or component type for the repeated field depending on whether it is a collection or an array .
5,546
static boolean isFieldRequired ( Field field ) { BigQueryDataField bqAnnotation = field . getAnnotation ( BigQueryDataField . class ) ; return ( bqAnnotation != null && bqAnnotation . mode ( ) . equals ( BigQueryFieldMode . REQUIRED ) ) || field . getType ( ) . isPrimitive ( ) ; }
Returns true if the field is annotated as a required bigquery field .
5,547
void padAndWriteBlock ( boolean writeEmptyBlockIfFull ) throws IOException { int remaining = writeBuffer . remaining ( ) ; if ( writeEmptyBlockIfFull || remaining < blockSize ) { writeBlanksToBuffer ( remaining ) ; writeBuffer . flip ( ) ; delegate . write ( writeBuffer ) ; writeBuffer . clear ( ) ; numBlocksWritten ++ ; } }
Adds padding to the stream until to the end of the block .
5,548
public Value < Void > run ( List < GcsFilename > files ) throws Exception { for ( GcsFilename file : files ) { try { gcs . delete ( file ) ; } catch ( RetriesExhaustedException | IOException e ) { log . log ( Level . WARNING , "Failed to cleanup file: " + file , e ) ; } } return null ; }
Deletes the files in the provided GoogleCloudStorageFileSet
5,549
public void update ( int b ) { long newCrc = crc ^ LONG_MASK ; newCrc = updateByte ( ( byte ) b , newCrc ) ; crc = newCrc ^ LONG_MASK ; }
Updates the checksum with a new byte .
5,550
public void update ( byte [ ] bArray , int off , int len ) { long newCrc = crc ^ LONG_MASK ; for ( int i = off ; i < off + len ; i ++ ) { newCrc = updateByte ( bArray [ i ] , newCrc ) ; } crc = newCrc ^ LONG_MASK ; }
Updates the checksum with an array of bytes .
5,551
public static Node getFirstNode ( Document doc , String xPathExpression ) { try { XPathFactory xPathfactory = XPathFactory . newInstance ( ) ; XPath xpath = xPathfactory . newXPath ( ) ; XPathExpression expr ; expr = xpath . compile ( xPathExpression ) ; NodeList nl = ( NodeList ) expr . evaluate ( doc , XPathConstants . NODESET ) ; return nl . item ( 0 ) ; } catch ( XPathExpressionException e ) { e . printStackTrace ( ) ; } return null ; }
Get first node on a Document doc give a xpath Expression
5,552
private boolean isSoapFault ( Document soapMessage ) throws Exception { Element faultElement = DomUtils . getElementByTagNameNS ( soapMessage , SOAP_12_NAMESPACE , "Fault" ) ; if ( faultElement != null ) { return true ; } else { faultElement = DomUtils . getElementByTagNameNS ( soapMessage , SOAP_11_NAMESPACE , "Fault" ) ; if ( faultElement != null ) { return true ; } } return false ; }
A method to check if the message received is a SOAP fault .
5,553
private Document parseSoapFault ( Document soapMessage , PrintWriter logger ) throws Exception { String namespace = soapMessage . getDocumentElement ( ) . getNamespaceURI ( ) ; if ( namespace . equals ( SOAP_12_NAMESPACE ) ) { parseSoap12Fault ( soapMessage , logger ) ; } else { parseSoap11Fault ( soapMessage , logger ) ; } return soapMessage ; }
A method to parse a SOAP fault . It checks the namespace and invoke the correct SOAP 1 . 1 or 1 . 2 Fault parser .
5,554
private void parseSoap11Fault ( Document soapMessage , PrintWriter logger ) throws Exception { Element envelope = soapMessage . getDocumentElement ( ) ; Element element = DomUtils . getElementByTagName ( envelope , "faultcode" ) ; if ( element == null ) { element = DomUtils . getElementByTagNameNS ( envelope , SOAP_11_NAMESPACE , "faultcode" ) ; } String faultcode = element . getTextContent ( ) ; element = DomUtils . getElementByTagName ( envelope , "faultstring" ) ; if ( element == null ) { element = DomUtils . getElementByTagNameNS ( envelope , SOAP_11_NAMESPACE , "faultstring" ) ; } String faultstring = element . getTextContent ( ) ; String msg = "SOAP Fault received - [code:" + faultcode + "][fault string:" + faultstring + "]" ; logger . println ( msg ) ; }
A method to parse a SOAP 1 . 1 fault message .
5,555
private void parseSoap12Fault ( Document soapMessage , PrintWriter logger ) throws Exception { Element envelope = soapMessage . getDocumentElement ( ) ; Element code = DomUtils . getElementByTagNameNS ( envelope , SOAP_12_NAMESPACE , "Code" ) ; String value = DomUtils . getElementByTagNameNS ( code , SOAP_12_NAMESPACE , "Value" ) . getTextContent ( ) ; String msg = "SOAP Fault received - [code:" + value + "]" ; Element subCode = DomUtils . getElementByTagNameNS ( code , SOAP_12_NAMESPACE , "Subcode" ) ; if ( subCode != null ) { value = DomUtils . getElementByTagNameNS ( subCode , SOAP_12_NAMESPACE , "Value" ) . getTextContent ( ) ; msg += "[subcode:" + value + "]" ; } Element reason = DomUtils . getElementByTagNameNS ( envelope , SOAP_12_NAMESPACE , "Reason" ) ; Element text = DomUtils . getElementByTagNameNS ( reason , SOAP_12_NAMESPACE , "Text" ) ; if ( text != null ) { value = text . getTextContent ( ) ; msg += "[reason:" + value + "]" ; } logger . println ( msg ) ; }
A method to parse a SOAP 1 . 2 fault message .
5,556
public static String createEncodedName ( File source ) { String fileURI = source . toURI ( ) . toString ( ) ; String userDirURI = new File ( System . getProperty ( "user.dir" ) ) . toURI ( ) . toString ( ) ; fileURI = fileURI . replace ( userDirURI , "" ) ; String encodedName = fileURI . substring ( fileURI . lastIndexOf ( ':' ) + 1 ) . replace ( "%20" , "-" ) . replace ( '/' , '_' ) ; return encodedName ; }
Creates a directory name from a file path .
5,557
public static Document getSOAPMessage ( InputStream in ) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setNamespaceAware ( true ) ; dbf . setExpandEntityReferences ( false ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; Document soapMessage = db . newDocument ( ) ; TransformerFactory tf = TransformerFactory . newInstance ( ) ; tf . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; Transformer t = tf . newTransformer ( ) ; t . transform ( new StreamSource ( in ) , new DOMResult ( soapMessage ) ) ; return soapMessage ; }
A method to get the SOAP message from the input stream .
5,558
public static Document getSoapBody ( Document soapMessage ) throws Exception { Element envelope = soapMessage . getDocumentElement ( ) ; Element body = DomUtils . getChildElement ( DomUtils . getElementByTagName ( envelope , envelope . getPrefix ( ) + ":Body" ) ) ; Document content = DomUtils . createDocument ( body ) ; Element documentRoot = content . getDocumentElement ( ) ; addNSdeclarations ( envelope , documentRoot ) ; addNSdeclarations ( body , documentRoot ) ; return content ; }
A method to extract the content of the SOAP body .
5,559
public static void addNSdeclarations ( Element source , Element target ) throws Exception { NamedNodeMap sourceAttributes = source . getAttributes ( ) ; Attr attribute ; String attributeName ; for ( int i = 0 ; i <= sourceAttributes . getLength ( ) - 1 ; i ++ ) { attribute = ( Attr ) sourceAttributes . item ( i ) ; attributeName = attribute . getName ( ) ; if ( attributeName . startsWith ( "xmlns" ) && ! attributeName . startsWith ( "xmlns:soap-env" ) ) { target . setAttribute ( attributeName , attribute . getValue ( ) ) ; } } }
A method to copy namespaces declarations .
5,560
public static byte [ ] getSoapMessageAsByte ( String version , List headerBlocks , Element body , String encoding ) throws Exception { Document message = createSoapMessage ( version , headerBlocks , body ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; TransformerFactory tf = TransformerFactory . newInstance ( ) ; tf . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; Transformer t = tf . newTransformer ( ) ; t . setOutputProperty ( OutputKeys . ENCODING , encoding ) ; t . transform ( new DOMSource ( message ) , new StreamResult ( baos ) ) ; return baos . toByteArray ( ) ; }
A method to create a SOAP message and retrieve it as byte .
5,561
public static Document createSoapMessage ( String version , List headerBlocks , Element body ) throws Exception { Document message = null ; NodeList children = body . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { if ( children . item ( i ) . getNodeType ( ) != Node . ELEMENT_NODE && children . item ( i ) . getNodeType ( ) == Node . TEXT_NODE ) { Document bodyDoc = DomUtils . convertToElementNode ( body . getTextContent ( ) . trim ( ) ) ; if ( bodyDoc . getFirstChild ( ) . getNodeType ( ) == Node . ELEMENT_NODE ) { body = ( Element ) bodyDoc . getFirstChild ( ) ; } } if ( version . equals ( SOAP_V_1_1 ) ) { message = Soap11MessageBuilder . getSoapMessage ( headerBlocks , body ) ; } else { message = Soap12MessageBuilder . getSoapMessage ( headerBlocks , body ) ; } break ; } return message ; }
A method to create a SOAP message . The SOAP message including the Header is created and returned as DOM Document .
5,562
public static String getFilenameFromString ( String filePath ) { String newPath = filePath ; int forwardInd = filePath . lastIndexOf ( "/" ) ; int backInd = filePath . lastIndexOf ( "\\" ) ; if ( forwardInd > backInd ) { newPath = filePath . substring ( forwardInd + 1 ) ; } else { newPath = filePath . substring ( backInd + 1 ) ; } return newPath ; }
Extracts the filename from a path .
5,563
public static String replaceAll ( String str , String match , String replacement ) { String newStr = str ; int i = newStr . indexOf ( match ) ; while ( i >= 0 ) { newStr = newStr . substring ( 0 , i ) + replacement + newStr . substring ( i + match . length ( ) ) ; i = newStr . indexOf ( match ) ; } return newStr ; }
Replaces all occurences of match in str with replacement
5,564
public static String getMediaType ( String ext ) { String mediaType = "" ; for ( int i = 0 ; i < ApplicationMediaTypeMappings . length ; i ++ ) { if ( ApplicationMediaTypeMappings [ i ] [ 0 ] . equals ( ext . toLowerCase ( ) ) ) { mediaType = ApplicationMediaTypeMappings [ i ] [ 1 ] ; } } if ( mediaType . equals ( "" ) ) { mediaType = "application/octet-stream" ; } return mediaType ; }
Returns the mime media type value for the given extension
5,565
static public String createMonitor ( String monitorUrl , TECore core ) { return createMonitor ( monitorUrl , null , "" , core ) ; }
Monitor without parser that doesn t trigger a test
5,566
static public String createMonitor ( String monitorUrl , Node parserInstruction , String modifiesResponse , TECore core ) { MonitorCall mc = monitors . get ( monitorUrl ) ; mc . setCore ( core ) ; if ( parserInstruction != null ) { mc . setParserInstruction ( DomUtils . getElement ( parserInstruction ) ) ; mc . setModifiesResponse ( Boolean . parseBoolean ( modifiesResponse ) ) ; } LOGR . log ( Level . CONFIG , "Configured monitor without test:\n {0}" , mc ) ; return "" ; }
Monitor that doesn t trigger a test
5,567
static public String createMonitor ( XPathContext context , String url , String localName , String namespaceURI , NodeInfo params , String callId , TECore core ) throws Exception { return createMonitor ( context , url , localName , namespaceURI , params , null , "" , callId , core ) ; }
Monitor without parser that triggers a test
5,568
static public String createMonitor ( XPathContext context , String monitorUrl , String localName , String namespaceURI , NodeInfo params , NodeInfo parserInstruction , String modifiesResponse , String callId , TECore core ) throws Exception { MonitorCall mc = monitors . get ( monitorUrl ) ; mc . setContext ( context ) ; mc . setLocalName ( localName ) ; mc . setNamespaceURI ( namespaceURI ) ; mc . setCore ( core ) ; if ( params != null ) { Node node = ( Node ) NodeOverNodeInfo . wrap ( params ) ; if ( node . getNodeType ( ) == Node . DOCUMENT_NODE ) { mc . setParams ( ( ( Document ) node ) . getDocumentElement ( ) ) ; } else { mc . setParams ( ( Element ) node ) ; } } if ( parserInstruction != null ) { Node node = ( Node ) NodeOverNodeInfo . wrap ( parserInstruction ) ; if ( node . getNodeType ( ) == Node . DOCUMENT_NODE ) { mc . setParserInstruction ( ( ( Document ) node ) . getDocumentElement ( ) ) ; } else { mc . setParserInstruction ( ( Element ) node ) ; } mc . setModifiesResponse ( Boolean . parseBoolean ( modifiesResponse ) ) ; } mc . setCallId ( callId ) ; LOGR . log ( Level . CONFIG , "Configured monitor with test:\n {0}" , mc ) ; return "" ; }
Monitor that triggers a test
5,569
public void earlHtmlReport ( String outputDir ) { ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; String resourceDir = cl . getResource ( "com/occamlab/te/earl/lib" ) . getPath ( ) ; String earlXsl = cl . getResource ( "com/occamlab/te/earl_html_report.xsl" ) . toString ( ) ; File htmlOutput = new File ( outputDir , "result" ) ; htmlOutput . mkdir ( ) ; File earlResult = findEarlResultFile ( outputDir ) ; LOGR . log ( FINE , "Try to transform earl result file '" + earlResult + "' to directory " + htmlOutput ) ; try { if ( earlResult != null && earlResult . exists ( ) ) { Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( new StreamSource ( earlXsl ) ) ; transformer . setParameter ( "outputDir" , htmlOutput ) ; File indexHtml = new File ( htmlOutput , "index.html" ) ; indexHtml . createNewFile ( ) ; FileOutputStream fo = new FileOutputStream ( indexHtml ) ; transformer . transform ( new StreamSource ( earlResult ) , new StreamResult ( fo ) ) ; fo . close ( ) ; FileUtils . copyDirectory ( new File ( resourceDir ) , htmlOutput ) ; } } catch ( Exception e ) { LOGR . log ( SEVERE , "Transformation of EARL to HTML failed." , e ) ; } }
Transform EARL result into HTML report using XSLT .
5,570
public static boolean recordingInfo ( String testName ) throws ParserConfigurationException , SAXException , IOException { TECore . rootTestName . clear ( ) ; String path = getBaseConfigDirectory ( ) + "/config.xml" ; if ( new File ( path ) . exists ( ) ) { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setExpandEntityReferences ( false ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; Document doc = db . parse ( path ) ; NodeList nodeListForStandardTag = doc . getElementsByTagName ( "standard" ) ; if ( null != nodeListForStandardTag && nodeListForStandardTag . getLength ( ) > 0 ) { for ( int i = 0 ; i < nodeListForStandardTag . getLength ( ) ; i ++ ) { Element elementStandard = ( Element ) nodeListForStandardTag . item ( i ) ; if ( testName . equals ( elementStandard . getElementsByTagName ( "local-name" ) . item ( 0 ) . getTextContent ( ) ) ) { if ( null != elementStandard . getElementsByTagName ( "record" ) . item ( 0 ) ) { System . setProperty ( "Record" , "True" ) ; NodeList rootTestNameArray = elementStandard . getElementsByTagName ( "test-name" ) ; if ( null != rootTestNameArray && rootTestNameArray . getLength ( ) > 0 ) { for ( int counter = 0 ; counter < rootTestNameArray . getLength ( ) ; counter ++ ) { Element rootTestName = ( Element ) rootTestNameArray . item ( counter ) ; TECore . rootTestName . add ( rootTestName . getTextContent ( ) ) ; } } return true ; } } } } } System . setProperty ( "Record" , "False" ) ; return false ; }
Determine the test recording is on or off .
5,571
public static InputStream DocumentToInputStream ( Document edoc ) throws IOException { final org . w3c . dom . Document doc = edoc ; final PipedOutputStream pos = new PipedOutputStream ( ) ; PipedInputStream pis = new PipedInputStream ( ) ; pis . connect ( pos ) ; ( new Thread ( new Runnable ( ) { public void run ( ) { try { TransformerFactory tFactory = TransformerFactory . newInstance ( ) ; tFactory . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; Transformer transformer = tFactory . newTransformer ( ) ; transformer . setOutputProperty ( "encoding" , "UTF-8" ) ; transformer . setOutputProperty ( "indent" , "yes" ) ; transformer . transform ( new DOMSource ( doc ) , new StreamResult ( pos ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Error converting Document to InputStream. " + e . getMessage ( ) ) ; } finally { try { pos . close ( ) ; } catch ( IOException e ) { } } } } , "IOUtils.DocumentToInputStream(Document edoc)" ) ) . start ( ) ; return pis ; }
Converts an org . w3c . dom . Document element to an java . io . InputStream .
5,572
public static String inputStreamToString ( InputStream in ) { StringBuffer buffer = new StringBuffer ( ) ; try { BufferedReader br = new BufferedReader ( new InputStreamReader ( in , "UTF-8" ) , 1024 ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { buffer . append ( line ) ; } } catch ( IOException iox ) { LOGR . warning ( iox . getMessage ( ) ) ; } return buffer . toString ( ) ; }
Reads the content of an input stream into a String value using the UTF - 8 charset .
5,573
public static boolean writeObjectToFile ( Object obj , File f ) { try { FileOutputStream fout = new FileOutputStream ( f ) ; ObjectOutputStream oos = new ObjectOutputStream ( fout ) ; oos . writeObject ( obj ) ; oos . close ( ) ; } catch ( Exception e ) { System . out . println ( "Error writing Object to file: " + e . getMessage ( ) ) ; return false ; } return true ; }
Writes a generic object to a file
5,574
public static Object readObjectFromFile ( File f ) { Object obj = null ; try { FileInputStream fin = new FileInputStream ( f ) ; ObjectInputStream ois = new ObjectInputStream ( fin ) ; obj = ois . readObject ( ) ; ois . close ( ) ; } catch ( Exception e ) { System . out . println ( "Error reading Object from file: " + e . getMessage ( ) ) ; return null ; } return obj ; }
Reads in a file that contains only an object
5,575
public void preload ( Index index , String sourcesName ) throws Exception { for ( String key : index . getTestKeys ( ) ) { TestEntry te = index . getTest ( key ) ; loadExecutable ( te , sourcesName ) ; } for ( String key : index . getFunctionKeys ( ) ) { List < FunctionEntry > functions = index . getFunctions ( key ) ; for ( FunctionEntry fe : functions ) { if ( ! fe . isJava ( ) ) { loadExecutable ( fe , sourcesName ) ; } } } }
Loads all of the XSL executables . This is a time consuming operation .
5,576
private void prettyprint ( String xmlLogsFile , FileOutputStream htmlReportFile ) throws Exception { TransformerFactory tFactory = TransformerFactory . newInstance ( ) ; tFactory . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setExpandEntityReferences ( false ) ; factory . setNamespaceAware ( true ) ; factory . setXIncludeAware ( true ) ; DocumentBuilder parser = factory . newDocumentBuilder ( ) ; Document document = parser . parse ( xmlLogsFile ) ; Transformer transformer = tFactory . newTransformer ( new StreamSource ( xsltFileHandler ) ) ; transformer . transform ( new DOMSource ( document ) , new StreamResult ( htmlReportFile ) ) ; }
Apply xslt stylesheet to xml logs file and crate an HTML report file .
5,577
public void generateDocumentation ( String sourcecodePath , String suiteName , FileOutputStream htmlFileOutput ) throws Exception { TransformerFactory tFactory = TransformerFactory . newInstance ( ) ; tFactory . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setExpandEntityReferences ( false ) ; factory . setNamespaceAware ( true ) ; factory . setXIncludeAware ( true ) ; DocumentBuilder parser = factory . newDocumentBuilder ( ) ; Document document = parser . parse ( sourcecodePath ) ; Transformer transformer = tFactory . newTransformer ( new StreamSource ( xsltSystemId ) ) ; transformer . transform ( new DOMSource ( document ) , new StreamResult ( htmlFileOutput ) ) ; }
Generate pseudocode documentation for CTL test scripts . Apply the stylesheet to documentate the sources of tests .
5,578
public static void deleteDirContents ( File dir ) { if ( ! dir . isDirectory ( ) || ! dir . exists ( ) ) { throw new IllegalArgumentException ( dir . getAbsolutePath ( ) + " is not a directory or does not exist." ) ; } String [ ] children = dir . list ( ) ; for ( int i = 0 ; i < children . length ; i ++ ) { File f = new File ( dir , children [ i ] ) ; if ( f . isDirectory ( ) ) { deleteDirContents ( f ) ; } f . delete ( ) ; } }
Deletes the contents of a directory including subdirectories .
5,579
public static void deleteSubDirs ( File dir ) { String [ ] children = dir . list ( ) ; for ( int i = 0 ; i < children . length ; i ++ ) { File f = new File ( dir , children [ i ] ) ; if ( f . isDirectory ( ) ) { deleteDir ( f ) ; } } }
Deletes just the sub directories for a certain directory
5,580
public static File getResourceAsFile ( String resource ) { ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { return new File ( URLDecoder . decode ( cl . getResource ( resource ) . getFile ( ) , "UTF-8" ) ) ; } catch ( UnsupportedEncodingException uee ) { return null ; } }
Loads a file into memory from the classpath
5,581
Document getResourceAsDoc ( String resource ) throws Exception { ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; InputStream is = cl . getResourceAsStream ( resource ) ; if ( is != null ) { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setNamespaceAware ( true ) ; dbf . setExpandEntityReferences ( false ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; TransformerFactory tf = TransformerFactory . newInstance ( ) ; tf . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; Transformer t = tf . newTransformer ( ) ; Document doc = db . newDocument ( ) ; t . transform ( new StreamSource ( is ) , new DOMResult ( doc ) ) ; is . close ( ) ; return doc ; } else { return null ; } }
Loads a DOM Document from the classpath
5,582
public static String getResourceURL ( String resource ) { ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; return cl . getResource ( resource ) . toString ( ) ; }
Returns the URL for file on the classpath as a String
5,583
public Principal authenticate ( String username , String credentials ) { GenericPrincipal principal = ( GenericPrincipal ) getPrincipal ( username ) ; if ( null != principal ) { try { if ( ! PasswordStorage . verifyPassword ( credentials , principal . getPassword ( ) ) ) { principal = null ; } } catch ( CannotPerformOperationException | InvalidHashException e ) { LOGR . log ( Level . WARNING , e . getMessage ( ) ) ; principal = null ; } } return principal ; }
Return the Principal associated with the specified username and credentials if one exists in the user data store ; otherwise return null .
5,584
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) GenericPrincipal createGenericPrincipal ( String username , String password , List < String > roles ) { Class klass = null ; try { klass = Class . forName ( "org.apache.catalina.realm.GenericPrincipal" ) ; } catch ( ClassNotFoundException ex ) { LOGR . log ( Level . SEVERE , ex . getMessage ( ) ) ; return null ; } Constructor [ ] ctors = klass . getConstructors ( ) ; Class firstParamType = ctors [ 0 ] . getParameterTypes ( ) [ 0 ] ; Class [ ] paramTypes = new Class [ ] { Realm . class , String . class , String . class , List . class } ; Object [ ] ctorArgs = new Object [ ] { this , username , password , roles } ; GenericPrincipal principal = null ; try { if ( Realm . class . isAssignableFrom ( firstParamType ) ) { Constructor ctor = klass . getConstructor ( paramTypes ) ; principal = ( GenericPrincipal ) ctor . newInstance ( ctorArgs ) ; } else { Constructor ctor = klass . getConstructor ( Arrays . copyOfRange ( paramTypes , 1 , paramTypes . length ) ) ; principal = ( GenericPrincipal ) ctor . newInstance ( Arrays . copyOfRange ( ctorArgs , 1 , ctorArgs . length ) ) ; } } catch ( Exception ex ) { LOGR . log ( Level . WARNING , ex . getMessage ( ) ) ; } return principal ; }
Creates a new GenericPrincipal representing the specified user .
5,585
public void saveImages ( Element form ) throws IOException { List < Element > images = DomUtils . getElementsByTagName ( form , "img" ) ; int imageCount = 1 ; for ( Element image : images ) { if ( image . hasAttribute ( "src" ) ) { String src = image . getAttribute ( "src" ) ; String imageFormat = parseImageFormat ( src ) ; String testName = System . getProperty ( "TestName" ) ; String imgName = parseImageName ( testName ) ; URL url = new URL ( src ) ; BufferedImage img = ImageIO . read ( url ) ; File file = createImageFile ( imageCount , imageFormat , imgName ) ; if ( ! file . exists ( ) ) { file . getParentFile ( ) . mkdirs ( ) ; } ImageIO . write ( img , imageFormat , file ) ; imageCount ++ ; } } }
Save images into session if the ets is interactive and it contains the images .
5,586
static Node select_parser ( int partnum , String mime , Element instruction ) { if ( null == instruction ) return null ; NodeList instructions = instruction . getElementsByTagNameNS ( PARSERS_NS , "parse" ) ; Node parserNode = null ; instructionsLoop : for ( int i = 0 ; i < instructions . getLength ( ) ; i ++ ) { Element parse = ( Element ) instructions . item ( i ) ; if ( partnum != 0 ) { String part_i = parse . getAttribute ( "part" ) ; if ( part_i . length ( ) > 0 ) { int n = Integer . parseInt ( part_i ) ; if ( n != partnum ) { continue ; } } } if ( mime != null ) { String mime_i = parse . getAttribute ( "mime" ) ; if ( mime_i . length ( ) > 0 ) { String [ ] mime_parts = mime_i . split ( ";\\s*" ) ; if ( ! mime . startsWith ( mime_parts [ 0 ] ) ) { continue ; } boolean ok = true ; for ( int j = 1 ; j < mime_parts . length ; j ++ ) { if ( mime . indexOf ( mime_parts [ j ] ) < 0 ) { ok = false ; break ; } } if ( ! ok ) { continue ; } } } NodeList children = parse . getChildNodes ( ) ; for ( int j = 0 ; j < children . getLength ( ) ; j ++ ) { if ( children . item ( j ) . getNodeType ( ) == Node . ELEMENT_NODE ) { parserNode = children . item ( j ) ; break instructionsLoop ; } } } return parserNode ; }
Selects a parser for a message part based on the part number and MIME format type if supplied in instructions .
5,587
public TestRunFixture getFixture ( String runId ) { if ( runId . isEmpty ( ) && this . fixtures . size ( ) == 1 ) { runId = this . fixtures . keySet ( ) . iterator ( ) . next ( ) ; } return fixtures . get ( runId ) ; }
Gets the fixture for the specified test run . If runId is an empty String and only one fixture exists this is returned .
5,588
void printError ( String type , SAXParseException e ) { PrintWriter logger = new PrintWriter ( System . out ) ; logger . print ( type ) ; if ( e . getLineNumber ( ) >= 0 ) { logger . print ( " at line " + e . getLineNumber ( ) ) ; if ( e . getColumnNumber ( ) >= 0 ) { logger . print ( ", column " + e . getColumnNumber ( ) ) ; } if ( e . getSystemId ( ) != null ) { logger . print ( " of " + e . getSystemId ( ) ) ; } } else { if ( e . getSystemId ( ) != null ) { logger . print ( " in " + e . getSystemId ( ) ) ; } } logger . println ( ":" ) ; logger . println ( " " + e . getMessage ( ) ) ; logger . flush ( ) ; }
Prints the error to STDOUT used to be consistent with TEAM Engine error handler .
5,589
public List < String > toList ( ) { List < String > errorStrings = new ArrayList < String > ( ) ; ErrorIterator errIterator = iterator ( ) ; while ( errIterator . hasNext ( ) ) { ValidationError err = errIterator . next ( ) ; errorStrings . add ( err . getMessage ( ) ) ; } return errorStrings ; }
Returns a list of errors as strings .
5,590
public Document parse ( URLConnection uc , Element instruction , PrintWriter logger ) throws SSLProtocolException { if ( null == uc ) { throw new NullPointerException ( "Unable to parse resource: URLConnection is null." ) ; } jlogger . fine ( "Received URLConnection object for " + uc . getURL ( ) ) ; Document doc = null ; try ( InputStream inStream = URLConnectionUtils . getInputStream ( uc ) ) { doc = parse ( inStream , instruction , logger ) ; } catch ( SSLProtocolException sslep ) { throw new SSLProtocolException ( "[SSL ERROR] Failed to connect with the requested URL due to \"Invalid server_name\" found!! :" + uc . getURL ( ) + ":" + sslep . getClass ( ) + " : " + sslep . getMessage ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( String . format ( "Failed to parse resource from %s" , uc . getURL ( ) ) , e ) ; } return doc ; }
Attempts to parse a resource read using the given connection to a URL .
5,591
Document parse ( Object input , Element parserConfig , PrintWriter logger ) throws Exception { jlogger . finer ( "Received XML resource of type " + input . getClass ( ) . getName ( ) ) ; ArrayList < Object > schemas = new ArrayList < Object > ( ) ; ArrayList < Object > dtds = new ArrayList < Object > ( ) ; schemas . addAll ( this . schemaList ) ; dtds . addAll ( this . dtdList ) ; loadSchemaLists ( parserConfig , schemas , dtds ) ; Document resultDoc = null ; ErrorHandlerImpl errHandler = new ErrorHandlerImpl ( "Parsing" , logger ) ; if ( input instanceof InputStream ) { DocumentBuilderFactory dbf = nonValidatingDBF ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; db . setErrorHandler ( errHandler ) ; try ( InputStream xmlInput = ( InputStream ) input ) { resultDoc = db . parse ( xmlInput ) ; } catch ( Exception e ) { jlogger . log ( Level . INFO , "Error parsing InputStream" , e ) ; } } else if ( input instanceof Document ) { resultDoc = ( Document ) input ; } else { throw new IllegalArgumentException ( "XML input must be an InputStream or a Document object." ) ; } if ( null == resultDoc ) { throw new RuntimeException ( "Failed to parse input: " + input . getClass ( ) . getName ( ) ) ; } errHandler . setRole ( "Validation" ) ; if ( null == resultDoc . getDoctype ( ) && dtds . isEmpty ( ) ) { validateAgainstXMLSchemaList ( resultDoc , schemas , errHandler ) ; } else { validateAgainstDTDList ( resultDoc , dtds , errHandler ) ; } int error_count = errHandler . getErrorCount ( ) ; int warning_count = errHandler . getWarningCount ( ) ; if ( error_count > 0 || warning_count > 0 ) { String msg = "" ; if ( error_count > 0 ) { msg += error_count + " validation error" + ( error_count == 1 ? "" : "s" ) ; if ( warning_count > 0 ) msg += " and " ; } if ( warning_count > 0 ) { msg += warning_count + " warning" + ( warning_count == 1 ? "" : "s" ) ; } msg += " detected." ; logger . println ( msg ) ; } if ( error_count > 0 ) { String s = ( null != parserConfig ) ? parserConfig . getAttribute ( "ignoreErrors" ) : "false" ; if ( s . length ( ) == 0 || Boolean . parseBoolean ( s ) == false ) { resultDoc = null ; } } if ( warning_count > 0 ) { String s = ( null != parserConfig ) ? parserConfig . getAttribute ( "ignoreWarnings" ) : "true" ; if ( s . length ( ) > 0 && Boolean . parseBoolean ( s ) == false ) { resultDoc = null ; } } return resultDoc ; }
Parses and validates an XML resource using the given schema references .
5,592
public boolean checkXMLRules ( Document doc , Document instruction ) throws Exception { if ( doc == null || doc . getDocumentElement ( ) == null ) return false ; Element e = instruction . getDocumentElement ( ) ; PrintWriter logger = new PrintWriter ( System . out ) ; Document parsedDoc = parse ( doc , e , logger ) ; return ( parsedDoc != null ) ; }
A method to validate a pool of schemas outside of the request element .
5,593
public NodeList validate ( Document doc , Document instruction ) throws Exception { return schemaValidation ( doc , instruction ) . toNodeList ( ) ; }
Validates the given document against the schema references supplied in the accompanying instruction document .
5,594
void validateAgainstXMLSchemaList ( Document doc , ArrayList < Object > xsdList , ErrorHandler errHandler ) throws SAXException , IOException { jlogger . finer ( "Validating XML resource from " + doc . getDocumentURI ( ) ) ; Schema schema = SF . newSchema ( ) ; if ( null != xsdList && ! xsdList . isEmpty ( ) ) { Source [ ] schemaSources = new Source [ xsdList . size ( ) ] ; for ( int i = 0 ; i < xsdList . size ( ) ; i ++ ) { Object ref = xsdList . get ( i ) ; if ( ref instanceof File ) { schemaSources [ i ] = new StreamSource ( ( File ) ref ) ; } else if ( ref instanceof URL ) { schemaSources [ i ] = new StreamSource ( ref . toString ( ) ) ; } else if ( ref instanceof char [ ] ) { schemaSources [ i ] = new StreamSource ( new CharArrayReader ( ( char [ ] ) ref ) ) ; } else { throw new IllegalArgumentException ( "Unknown schema reference: " + ref . toString ( ) ) ; } } schema = SF . newSchema ( schemaSources ) ; } }
Validates an XML resource against a list of XML Schemas . Validation errors are reported to the given handler .
5,595
public static Node addDomAttr ( Document doc , String tagName , String tagNamespaceURI , String attrName , String attrValue ) { Document newDoc = null ; try { System . setProperty ( "javax.xml.parsers.DocumentBuilderFactory" , "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl" ) ; DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setNamespaceAware ( true ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; newDoc = db . newDocument ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } Transformer identity = null ; try { TransformerFactory TF = TransformerFactory . newInstance ( ) ; TF . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; identity = TF . newTransformer ( ) ; identity . transform ( new DOMSource ( doc ) , new DOMResult ( newDoc ) ) ; } catch ( Exception ex ) { System . out . println ( "ERROR: " + ex . getMessage ( ) ) ; } NodeList namedTags = newDoc . getElementsByTagNameNS ( tagNamespaceURI , tagName ) ; for ( int i = 0 ; i < namedTags . getLength ( ) ; i ++ ) { Element element = ( Element ) namedTags . item ( i ) ; element . setAttribute ( attrName , attrValue ) ; } return ( Node ) newDoc ; }
Adds the attribute to each node in the Document with the given name .
5,596
public static boolean checkCommentNodes ( Node node , String str ) { NodeList children = node . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node child = children . item ( i ) ; NodeList childChildren = child . getChildNodes ( ) ; if ( childChildren . getLength ( ) > 0 ) { boolean okDownThere = checkCommentNodes ( child , str ) ; if ( okDownThere == true ) { return true ; } } if ( child . getNodeType ( ) == Node . COMMENT_NODE ) { Comment comment = ( Comment ) child ; if ( comment . getNodeValue ( ) . contains ( str ) ) { return true ; } } } return false ; }
Determines if there is a comment Node that contains the given string .
5,597
public static String serializeNoNS ( Node node ) { StringBuffer buf = new StringBuffer ( ) ; buf . append ( "<" ) ; buf . append ( node . getLocalName ( ) ) ; for ( Entry < QName , String > entry : getAttributes ( node ) . entrySet ( ) ) { QName name = entry . getKey ( ) ; if ( name . getNamespaceURI ( ) != null ) { buf . append ( " " ) ; buf . append ( name . getLocalPart ( ) ) ; buf . append ( "=\"" ) ; buf . append ( entry . getValue ( ) ) ; buf . append ( "\"" ) ; } } boolean tagOpen = true ; NodeList children = node . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node n = children . item ( i ) ; short type = node . getNodeType ( ) ; if ( type == Node . TEXT_NODE ) { if ( tagOpen ) { buf . append ( ">\n" ) ; tagOpen = false ; } buf . append ( node . getTextContent ( ) ) ; } else if ( type == Node . ELEMENT_NODE ) { if ( tagOpen ) { buf . append ( ">\n" ) ; tagOpen = false ; } buf . append ( serializeNoNS ( n ) ) ; buf . append ( "\n" ) ; } } if ( tagOpen ) { buf . append ( "/>\n" ) ; } else { buf . append ( "</" ) ; buf . append ( node . getLocalName ( ) ) ; buf . append ( ">\n" ) ; } return buf . toString ( ) ; }
Serializes a Node to a String
5,598
static public void displayNode ( Node node ) { try { TransformerFactory TF = TransformerFactory . newInstance ( ) ; TF . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; Transformer identity = TF . newTransformer ( ) ; identity . transform ( new DOMSource ( node ) , new StreamResult ( System . out ) ) ; } catch ( Exception ex ) { System . out . println ( "ERROR: " + ex . getMessage ( ) ) ; } }
HELPER METHOD TO PRINT A DOM TO STDOUT
5,599
public static Document convertToElementNode ( String xmlString ) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setNamespaceAware ( true ) ; dbf . setExpandEntityReferences ( false ) ; Document doc = dbf . newDocumentBuilder ( ) . newDocument ( ) ; if ( xmlString != null ) { TransformerFactory tf = TransformerFactory . newInstance ( ) ; tf . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; Transformer t = tf . newTransformer ( ) ; t . transform ( new StreamSource ( new StringReader ( xmlString ) ) , new DOMResult ( doc ) ) ; } return doc ; }
Convert text node to element .