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 ( basedi...
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 sourceDirectorie...
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 ( "-boot...
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 (...
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 (...
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 ...
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 . getCallb...
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 . getFil...
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 ( ) . lockedSinc...
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 ...
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 ) { retValu...
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 ...
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_PAT...
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 ( checkNotN...
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 . s...
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 ( HttpSer...
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 ...
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 = ...
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 do...
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 keyPo...
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 )...
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...
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 ...
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...
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 ( ) ; fo...
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 ( writ...
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 (...
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...
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...
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 = ...
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 = ( SizeSegmentingGoogleCloudStora...
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 ( param...
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...
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"...
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 ...
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_...
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 ...
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 . lastIndex...
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 (...
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 ) ...
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 ) ; att...
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 . newIns...
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 && chil...
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 ( backI...
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 ( "" )...
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 . setModi...
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 ) ...
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 =...
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 . newInsta...
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 ( ) {...
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 io...
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 . ...
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: " + ...
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 ) ;...
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 ( ) ...
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 = DocumentBu...
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 = ne...
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 )...
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 ( CannotPerformOp...
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 . S...
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 ( sr...
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 ++ ) { Eleme...
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 ...
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 = nul...
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 . ad...
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 ) ; r...
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...
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 = Document...
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 okDow...
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 ) { bu...
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 ) ) ;...
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 != nul...
Convert text node to element .