idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
129,200 | 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 . |
129,201 | public void beginSlice ( ) throws IOException { writer = createWriter ( sliceCount ++ ) ; writer . setContext ( getContext ( ) ) ; writer . beginShard ( ) ; writer . beginSlice ( ) ; } | Creates a new writer . |
129,202 | 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 . |
129,203 | 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 . |
129,204 | 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 . |
129,205 | 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 . |
129,206 | 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 . |
129,207 | 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 . |
129,208 | 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 . |
129,209 | 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 . |
129,210 | 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 . |
129,211 | private static String getHandler ( HttpServletRequest request ) { String pathInfo = request . getPathInfo ( ) ; return pathInfo == null ? "" : pathInfo . substring ( 1 ) ; } | Returns the handler portion of the URL path . |
129,212 | 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 . |
129,213 | 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 . |
129,214 | 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 . |
129,215 | 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 . |
129,216 | 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... |
129,217 | 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 . |
129,218 | 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 . |
129,219 | 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 . |
129,220 | 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 . |
129,221 | final ByteBuffer readPointer ( int index ) { int pointerOffset = computePointerOffset ( index ) ; return sliceOutRange ( pointerOffset , pointerOffset + POINTER_SIZE_BYTES ) ; } | Read a pointer from the specified index . |
129,222 | 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 |
129,223 | 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 . |
129,224 | 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 . |
129,225 | 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 . |
129,226 | 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 . |
129,227 | 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 . |
129,228 | 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 . |
129,229 | 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 . |
129,230 | 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 . |
129,231 | 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 . |
129,232 | 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 . |
129,233 | 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 |
129,234 | 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 . |
129,235 | 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 . |
129,236 | 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 . |
129,237 | 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 . |
129,238 | 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 |
129,239 | 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 . |
129,240 | 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 . |
129,241 | 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 |
129,242 | 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 . |
129,243 | 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 . |
129,244 | 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 . |
129,245 | 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 . |
129,246 | 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 . |
129,247 | 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 . |
129,248 | 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 . |
129,249 | 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 . |
129,250 | 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 . |
129,251 | 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 . |
129,252 | 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 . |
129,253 | 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 |
129,254 | 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 |
129,255 | static public String createMonitor ( String monitorUrl , TECore core ) { return createMonitor ( monitorUrl , null , "" , core ) ; } | Monitor without parser that doesn t trigger a test |
129,256 | 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 |
129,257 | 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 |
129,258 | 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 |
129,259 | 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 . |
129,260 | 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 . |
129,261 | 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 . |
129,262 | 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 . |
129,263 | 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 |
129,264 | 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 |
129,265 | 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 . |
129,266 | 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 . |
129,267 | 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 . |
129,268 | 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 . |
129,269 | 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 |
129,270 | 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 |
129,271 | 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 |
129,272 | 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 |
129,273 | 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 . |
129,274 | @ 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 . |
129,275 | 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 . |
129,276 | 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 . |
129,277 | 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 . |
129,278 | 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 . |
129,279 | 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 . |
129,280 | 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 . |
129,281 | 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 . |
129,282 | 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 . |
129,283 | 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 . |
129,284 | 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 . |
129,285 | 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 . |
129,286 | 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 . |
129,287 | 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 |
129,288 | 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 |
129,289 | 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 . |
129,290 | public void create ( File tebase ) throws TEException { try { create ( tebase . toString ( ) + File . separator ) ; } catch ( Exception e ) { throw e ; } } | Creates the main config file . |
129,291 | private List < File > getConfigFiles ( File dir ) { String [ ] extensions = { "xml" } ; List < File > configFiles = new ArrayList < File > ( ) ; Collection < File > files = FileUtils . listFiles ( dir , extensions , true ) ; for ( Iterator < File > iterator = files . iterator ( ) ; iterator . hasNext ( ) ; ) { File fil... | Returns the all config file found under a directory |
129,292 | public boolean checkSchematronRules ( Document doc , String schemaFile , String phase ) throws Exception { boolean isValid = false ; if ( doc == null || doc . getDocumentElement ( ) == null ) return isValid ; try { ClassLoader loader = this . getClass ( ) . getClassLoader ( ) ; URL url = loader . getResource ( schemaFi... | Checks the given schematron phase for the XML file and returns the validation status . |
129,293 | public boolean executeSchematronDriver ( InputSource inputDoc , File schemaFile , String phase ) { boolean isValid = false ; ValidationDriver driver = createSchematronDriver ( phase ) ; assert null != driver : "Unable to create Schematron ValidationDriver" ; InputSource is = null ; FileInputStream fis = null ; try { fi... | Runs the schematron file against the input source . |
129,294 | Document parse ( Document doc , Element instruction , PrintWriter logger ) throws Exception { this . outputLogger = logger ; if ( instruction != null ) { getFileType ( instruction ) ; if ( type . equals ( "url" ) ) { URL schemaURL = new URL ( this . schemaLocation ) ; this . schemaFile = new File ( schemaURL . toURI ( ... | Checks the given Document against a Schematron schema . A schema reference is conveyed by a DOM Element node as indicated below . |
129,295 | ValidationDriver createDriver ( PropertyMap configProps ) { SchemaReaderLoader loader = new SchemaReaderLoader ( ) ; SchemaReader schReader = loader . createSchemaReader ( SCHEMATRON_NS_URI ) ; ValidationDriver validator = new ValidationDriver ( configProps , schReader ) ; return validator ; } | Creates and initializes a ValidationDriver to perform Schematron validation . A schema must be loaded before an instance can be validated . |
129,296 | public static int getImageWidth ( String imageLoc ) { InputStream is = null ; try { URI imageUri = new URI ( imageLoc ) ; URL imageUrl = imageUri . toURL ( ) ; is = imageUrl . openStream ( ) ; } catch ( Exception e ) { jlogger . log ( Level . SEVERE , "getImageWidth" , e ) ; return - 1 ; } try { ImageInputStream iis = ... | Determines the width of the first image in an image file in pixels . |
129,297 | public static PrintWriter createLog ( File logDir , String callpath ) throws Exception { if ( logDir != null ) { File dir = new File ( logDir , callpath ) ; String path = logDir . toString ( ) + "/" + callpath . split ( "/" ) [ 0 ] ; System . setProperty ( "PATH" , path ) ; dir . mkdir ( ) ; File f = new File ( dir , "... | Creates a Writer used to write test results to the log . xml file . |
129,298 | public static Document readLog ( File logDir , String callpath ) throws Exception { File dir = new File ( logDir , callpath ) ; File f = new File ( dir , "log.xml" ) ; if ( f . exists ( ) ) { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setNamespaceAware ( true ) ; dbf . setExpandEntity... | Reads a log from disk |
129,299 | public static XdmNode getContextFromLog ( net . sf . saxon . s9api . DocumentBuilder builder , Document log ) throws Exception { Element starttest = ( Element ) log . getElementsByTagName ( "starttest" ) . item ( 0 ) ; NodeList nl = starttest . getElementsByTagName ( "context" ) ; if ( nl == null || nl . getLength ( ) ... | Returns the context node for a test from its log document |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.