idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
23,200
public static boolean equalsString ( final String thisStr , final String thatStr ) { if ( ( thisStr == null ) && ( thatStr == null ) ) { return true ; } if ( thisStr == null ) { return false ; } return thisStr . equals ( thatStr ) ; }
Return true if Strings are equal including possible null
61
10
23,201
public static int compareStrings ( final String s1 , final String s2 ) { if ( s1 == null ) { if ( s2 != null ) { return - 1 ; } return 0 ; } if ( s2 == null ) { return 1 ; } return s1 . compareTo ( s2 ) ; }
Compare two strings . null is less than any non - null string .
67
14
23,202
public static List < String > getList ( final String val , final boolean emptyOk ) throws Throwable { List < String > l = new LinkedList < String > ( ) ; if ( ( val == null ) || ( val . length ( ) == 0 ) ) { return l ; } StringTokenizer st = new StringTokenizer ( val , "," , false ) ; while ( st . hasMoreTokens ( ) ) { String token = st . nextToken ( ) . trim ( ) ; if ( ( token == null ) || ( token . length ( ) == 0 ) ) { if ( ! emptyOk ) { // No empty strings throw new Exception ( "List has an empty element." ) ; } l . add ( "" ) ; } else { // Got non-empty element l . add ( token ) ; } } return l ; }
Turn a comma separated list into a List . Throws exception for invalid list .
177
16
23,203
public static int compare ( final char [ ] thisone , final char [ ] thatone ) { if ( thisone == thatone ) { return 0 ; } if ( thisone == null ) { return - 1 ; } if ( thatone == null ) { return 1 ; } if ( thisone . length < thatone . length ) { return - 1 ; } if ( thisone . length > thatone . length ) { return - 1 ; } for ( int i = 0 ; i < thisone . length ; i ++ ) { char thisc = thisone [ i ] ; char thatc = thatone [ i ] ; if ( thisc < thatc ) { return - 1 ; } if ( thisc > thatc ) { return 1 ; } } return 0 ; }
Compare two char arrays
164
4
23,204
public Diff add ( final Diff paramChange ) { assert paramChange != null ; final ITreeData item = paramChange . getDiff ( ) == EDiff . DELETED ? paramChange . getOldNode ( ) : paramChange . getNewNode ( ) ; if ( mChangeByNode . containsKey ( item ) ) { return paramChange ; } mChanges . add ( paramChange ) ; return mChangeByNode . put ( item , paramChange ) ; }
Adds a change to the edit script .
98
8
23,205
public void startListening ( ) throws FileNotFoundException , ClassNotFoundException , IOException , ResourceNotExistingException , TTException { mProcessingThread = new Thread ( ) { public void run ( ) { try { processFileNotifications ( ) ; } catch ( InterruptedException | TTException | IOException e ) { } } } ; mProcessingThread . start ( ) ; initSessions ( ) ; }
Start listening to the defined folders .
90
7
23,206
private void initSessions ( ) throws FileNotFoundException , ClassNotFoundException , IOException , ResourceNotExistingException , TTException { Map < String , String > filelisteners = getFilelisteners ( ) ; mSessions = new HashMap < String , ISession > ( ) ; mTrx = new HashMap < String , IFilelistenerWriteTrx > ( ) ; if ( filelisteners . isEmpty ( ) ) { return ; } for ( Entry < String , String > e : filelisteners . entrySet ( ) ) { mSessions . put ( e . getKey ( ) , StorageManager . getSession ( e . getKey ( ) ) ) ; mTrx . put ( e . getKey ( ) , new FilelistenerWriteTrx ( mSessions . get ( e . getKey ( ) ) . beginBucketWtx ( ) , mSessions . get ( e . getKey ( ) ) ) ) ; mSubDirectories . put ( e . getValue ( ) , new ArrayList < String > ( ) ) ; mExecutorMap . put ( e . getValue ( ) , Executors . newSingleThreadExecutor ( ) ) ; List < String > subDirs = mSubDirectories . get ( e . getValue ( ) ) ; for ( String s : mTrx . get ( e . getKey ( ) ) . getFilePaths ( ) ) { String fullFilePath = new StringBuilder ( ) . append ( e . getValue ( ) ) . append ( File . separator ) . append ( s ) . toString ( ) ; subDirs . add ( fullFilePath ) ; Path p = Paths . get ( fullFilePath ) ; watchParents ( p , e . getValue ( ) ) ; } } }
This method is used to initialize a session with treetank for every storage configuration thats in the database .
386
21
23,207
private void watchParents ( Path p , String until ) throws IOException { if ( p . getParent ( ) != null && ! until . equals ( p . getParent ( ) . toString ( ) ) ) { watchDir ( p . getParent ( ) . toFile ( ) ) ; watchParents ( p . getParent ( ) , until ) ; } }
Watch parent folders of this file until the root listener path has been reached .
76
15
23,208
private void releaseSessions ( ) throws TTException { if ( mSessions == null ) { return ; } // Closing all transactions. try { for ( IFilelistenerWriteTrx trx : mTrx . values ( ) ) { trx . close ( ) ; } } catch ( IllegalStateException ise ) { ise . printStackTrace ( ) ; } // Closing all storages aswell. for ( ISession s : mSessions . values ( ) ) { s . close ( ) ; } }
Release transactions and session from treetank .
112
9
23,209
public void shutDownListener ( ) throws TTException , IOException { for ( ExecutorService s : mExecutorMap . values ( ) ) { s . shutdown ( ) ; while ( ! s . isTerminated ( ) ) { // Do nothing. try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { LOGGER . error ( e . getStackTrace ( ) . toString ( ) ) ; } } } Thread thr = mProcessingThread ; if ( thr != null ) { thr . interrupt ( ) ; } mWatcher . close ( ) ; releaseSessions ( ) ; }
Shutdown listening to the defined folders and release all bonds to Treetank .
131
16
23,210
private void processFileNotifications ( ) throws InterruptedException , TTException , IOException { while ( true ) { WatchKey key = mWatcher . take ( ) ; Path dir = mKeyPaths . get ( key ) ; for ( WatchEvent < ? > evt : key . pollEvents ( ) ) { WatchEvent . Kind < ? > eventType = evt . kind ( ) ; if ( eventType == OVERFLOW ) continue ; Object o = evt . context ( ) ; if ( o instanceof Path ) { Path path = dir . resolve ( ( Path ) evt . context ( ) ) ; process ( dir , path , eventType ) ; } } key . reset ( ) ; processFsnOnHold ( ) ; } }
In this method the notifications of the filesystem if anything changed in a folder that the system is listening to are being extracted and processed .
159
26
23,211
private void process ( Path dir , Path file , WatchEvent . Kind < ? > evtType ) throws TTException , IOException , InterruptedException { // LOGGER.info("Processing " + file.getFileName() + " with event " // + evtType); IFilelistenerWriteTrx trx = null ; String rootPath = getListenerRootPath ( dir ) ; String relativePath = file . toFile ( ) . getAbsolutePath ( ) ; relativePath = relativePath . substring ( getListenerRootPath ( dir ) . length ( ) , relativePath . length ( ) ) ; for ( Entry < String , String > e : mFilelistenerToPaths . entrySet ( ) ) { if ( e . getValue ( ) . equals ( getListenerRootPath ( dir ) ) ) { trx = mTrx . get ( e . getKey ( ) ) ; } } if ( file . toFile ( ) . isDirectory ( ) ) { if ( evtType == ENTRY_CREATE ) { addSubDirectory ( dir , file ) ; return ; } else if ( evtType == ENTRY_DELETE ) { for ( String s : trx . getFilePaths ( ) ) { if ( s . contains ( relativePath ) ) { trx . removeFile ( s ) ; } } } } else { // if (mLockedFiles.get(rootPath + File.separator // + file.toFile().getName()) != null) { // if (mLockedFiles.get( // rootPath + File.separator + file.toFile().getName()) // .isFinished()) { // ExecutorService s = mExecutorMap // .get(getListenerRootPath(dir)); // if (s != null && !s.isShutdown()) { // // FilesystemNotification n = new FilesystemNotification( // file.toFile(), relativePath, rootPath, evtType, // trx); // if (mObserver != null) { // n.addObserver(mObserver); // } // mFsnOnHold.remove(rootPath + File.separator // + file.toFile().getName()); // mLockedFiles.put(rootPath + File.separator // + file.toFile().getName(), n); // s.submit(n); // } // } else { // FilesystemNotification n = new FilesystemNotification( // file.toFile(), relativePath, rootPath, evtType, trx); // if (mObserver != null) { // n.addObserver(mObserver); // } // mFsnOnHold.put(rootPath + File.separator // + file.toFile().getName(), n); // } // } else { ExecutorService s = mExecutorMap . get ( getListenerRootPath ( dir ) ) ; if ( s != null && ! s . isShutdown ( ) ) { FilesystemNotification n = new FilesystemNotification ( file . toFile ( ) , relativePath , rootPath , evtType , trx ) ; if ( mObserver != null ) { n . addObserver ( mObserver ) ; } // mLockedFiles.put(rootPath + File.separator // + file.toFile().getName(), n); s . submit ( n ) ; // } } } }
This method is used to process the file system modifications .
730
11
23,212
private void addSubDirectory ( Path root , Path filePath ) throws IOException { String listener = getListenerRootPath ( root ) ; List < String > listeners = mSubDirectories . get ( listener ) ; if ( listeners != null ) { if ( mSubDirectories . get ( listener ) . contains ( filePath . toAbsolutePath ( ) ) ) { return ; } else { mSubDirectories . get ( listener ) . add ( filePath . toString ( ) ) ; } try { watchDir ( filePath . toFile ( ) ) ; } catch ( IOException e ) { throw new IOException ( "Could not watch the subdirectories." , e ) ; } } }
In this method a subdirectory is being added to the system and watched .
147
15
23,213
private String getListenerRootPath ( Path root ) { String listener = "" ; for ( String s : mFilelistenerToPaths . values ( ) ) { if ( root . toString ( ) . contains ( s ) ) { listener = s ; } } return listener ; }
This utility method allows you to get the root path for a subdirectory .
59
15
23,214
public static Map < String , String > getFilelisteners ( ) throws FileNotFoundException , IOException , ClassNotFoundException { mFilelistenerToPaths = new HashMap < String , String > ( ) ; File listenerFilePaths = new File ( StorageManager . ROOT_PATH + File . separator + "mapping.data" ) ; getFileListenersFromSystem ( listenerFilePaths ) ; return mFilelistenerToPaths ; }
A utility method to get all filelisteners that are already defined and stored .
100
16
23,215
public static boolean addFilelistener ( String pResourcename , String pListenerPath ) throws FileNotFoundException , IOException , ClassNotFoundException { mFilelistenerToPaths = new HashMap < String , String > ( ) ; File listenerFilePaths = new File ( StorageManager . ROOT_PATH + File . separator + "mapping.data" ) ; getFileListenersFromSystem ( listenerFilePaths ) ; mFilelistenerToPaths . put ( pResourcename , pListenerPath ) ; ByteArrayDataOutput output = ByteStreams . newDataOutput ( ) ; for ( Entry < String , String > e : mFilelistenerToPaths . entrySet ( ) ) { output . write ( ( e . getKey ( ) + "\n" ) . getBytes ( ) ) ; output . write ( ( e . getValue ( ) + "\n" ) . getBytes ( ) ) ; } java . nio . file . Files . write ( listenerFilePaths . toPath ( ) , output . toByteArray ( ) , StandardOpenOption . TRUNCATE_EXISTING ) ; return true ; }
Add a new filelistener to the system .
251
10
23,216
public boolean removeFilelistener ( String pResourcename ) throws IOException , TTException , ResourceNotExistingException { mFilelistenerToPaths = new HashMap < String , String > ( ) ; File listenerFilePaths = new File ( StorageManager . ROOT_PATH + File . separator + "mapping.data" ) ; getFileListenersFromSystem ( listenerFilePaths ) ; mFilelistenerToPaths . remove ( pResourcename ) ; StorageManager . removeResource ( pResourcename ) ; ByteArrayDataOutput output = ByteStreams . newDataOutput ( ) ; for ( Entry < String , String > e : mFilelistenerToPaths . entrySet ( ) ) { output . write ( ( e . getKey ( ) + "\n" ) . getBytes ( ) ) ; output . write ( ( e . getValue ( ) + "\n" ) . getBytes ( ) ) ; } java . nio . file . Files . write ( listenerFilePaths . toPath ( ) , output . toByteArray ( ) , StandardOpenOption . TRUNCATE_EXISTING ) ; return true ; }
You can remove a filelistener from the system identifying it with it s Storagename .
253
20
23,217
private static void getFileListenersFromSystem ( File pListenerFilePaths ) throws IOException { if ( ! pListenerFilePaths . exists ( ) ) { java . nio . file . Files . createFile ( pListenerFilePaths . toPath ( ) ) ; } else { byte [ ] bytes = java . nio . file . Files . readAllBytes ( pListenerFilePaths . toPath ( ) ) ; ByteArrayDataInput input = ByteStreams . newDataInput ( bytes ) ; String key ; while ( ( key = input . readLine ( ) ) != null ) { String val = input . readLine ( ) ; mFilelistenerToPaths . put ( key , val ) ; } } }
This is a helper method that let s you initialize mFilelistenerToPaths with all the filelisteners that have been stored in the filesystem .
156
31
23,218
public static < K , V extends Comparable < V > > List < Entry < K , V > > sortByValue ( Map < K , V > map ) { List < Entry < K , V > > entries = new ArrayList <> ( map . entrySet ( ) ) ; entries . sort ( new ByValue <> ( ) ) ; return entries ; }
Sorts the provided Map by the value instead of by key like TreeMap does .
77
17
23,219
public static < K extends Comparable < K > , V extends Comparable < V > > List < Map . Entry < K , V > > sortByValueAndKey ( Map < K , V > map ) { List < Map . Entry < K , V > > entries = new ArrayList <> ( map . entrySet ( ) ) ; entries . sort ( new ByValueAndKey <> ( ) ) ; return entries ; }
Sorts the provided Map by the value and then by key instead of by key like TreeMap does .
91
21
23,220
public String getReqPar ( final String name , final String def ) { final String s = Util . checkNull ( request . getParameter ( name ) ) ; if ( s != null ) { return s ; } return def ; }
Get a request parameter stripped of white space . Return default for null or zero length .
50
17
23,221
public Integer getIntReqPar ( final String name ) throws Throwable { String reqpar = getReqPar ( name ) ; if ( reqpar == null ) { return null ; } return Integer . valueOf ( reqpar ) ; }
Get an Integer request parameter or null .
51
8
23,222
public int getIntReqPar ( final String name , final int defaultVal ) throws Throwable { String reqpar = getReqPar ( name ) ; if ( reqpar == null ) { return defaultVal ; } try { return Integer . parseInt ( reqpar ) ; } catch ( Throwable t ) { return defaultVal ; // XXX exception? } }
Get an integer valued request parameter .
76
7
23,223
public Long getLongReqPar ( final String name ) throws Throwable { String reqpar = getReqPar ( name ) ; if ( reqpar == null ) { return null ; } return Long . valueOf ( reqpar ) ; }
Get a Long request parameter or null .
51
8
23,224
public long getLongReqPar ( final String name , final long defaultVal ) throws Throwable { String reqpar = getReqPar ( name ) ; if ( reqpar == null ) { return defaultVal ; } try { return Long . parseLong ( reqpar ) ; } catch ( Throwable t ) { return defaultVal ; // XXX exception? } }
Get an long valued request parameter .
76
7
23,225
public Boolean getBooleanReqPar ( final String name ) throws Throwable { String reqpar = getReqPar ( name ) ; if ( reqpar == null ) { return null ; } try { if ( reqpar . equalsIgnoreCase ( "yes" ) ) { reqpar = "true" ; } return Boolean . valueOf ( reqpar ) ; } catch ( Throwable t ) { return null ; // XXX exception? } }
Get a boolean valued request parameter .
94
7
23,226
public boolean getBooleanReqPar ( final String name , final boolean defVal ) throws Throwable { boolean val = defVal ; Boolean valB = getBooleanReqPar ( name ) ; if ( valB != null ) { val = valB ; } return val ; }
Get a boolean valued request parameter giving a default value .
60
11
23,227
public void setSessionAttr ( final String attrName , final Object val ) { final HttpSession sess = request . getSession ( false ) ; if ( sess == null ) { return ; } sess . setAttribute ( attrName , val ) ; }
Set the value of a named session attribute .
58
9
23,228
public void removeSessionAttr ( final String attrName ) { final HttpSession sess = request . getSession ( false ) ; if ( sess == null ) { return ; } sess . removeAttribute ( attrName ) ; }
Remove a named session attribute .
52
6
23,229
public Object getSessionAttr ( final String attrName ) { final HttpSession sess = request . getSession ( false ) ; if ( sess == null ) { return null ; } return sess . getAttribute ( attrName ) ; }
Return the value of a named session attribute .
54
9
23,230
@ SuppressWarnings ( "unchecked" ) public static void registerMBean ( final ManagementContext context , final Object object , final ObjectName objectName ) throws Exception { String mbeanName = object . getClass ( ) . getName ( ) + "MBean" ; for ( Class c : object . getClass ( ) . getInterfaces ( ) ) { if ( mbeanName . equals ( c . getName ( ) ) ) { context . registerMBean ( new AnnotatedMBean ( object , c ) , objectName ) ; return ; } } context . registerMBean ( object , objectName ) ; }
Register an mbean with the jmx context
139
9
23,231
private Method getMethod ( final MBeanOperationInfo op ) { final MBeanParameterInfo [ ] params = op . getSignature ( ) ; final String [ ] paramTypes = new String [ params . length ] ; for ( int i = 0 ; i < params . length ; i ++ ) { paramTypes [ i ] = params [ i ] . getType ( ) ; } return getMethod ( getMBeanInterface ( ) , op . getName ( ) , paramTypes ) ; }
Extracts the Method from the MBeanOperationInfo
105
12
23,232
private static Method getMethod ( final Class < ? > mbean , final String method , final String ... params ) { try { final ClassLoader loader = mbean . getClassLoader ( ) ; final Class < ? > [ ] paramClasses = new Class < ? > [ params . length ] ; for ( int i = 0 ; i < params . length ; i ++ ) { paramClasses [ i ] = primitives . get ( params [ i ] ) ; if ( paramClasses [ i ] == null ) { paramClasses [ i ] = Class . forName ( params [ i ] , false , loader ) ; } } return mbean . getMethod ( method , paramClasses ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { return null ; } }
Returns the Method with the specified name and parameter types for the given class null if it doesn t exist .
170
21
23,233
@ Around ( "@annotation(org.treetank.aspects.logging.Logging)" ) public Object advice ( ProceedingJoinPoint pjp ) throws Throwable { final Signature sig = pjp . getSignature ( ) ; final Logger logger = FACTORY . getLogger ( sig . getDeclaringTypeName ( ) ) ; logger . debug ( new StringBuilder ( "Entering " ) . append ( sig . getDeclaringTypeName ( ) ) . toString ( ) ) ; final Object returnVal = pjp . proceed ( ) ; logger . debug ( new StringBuilder ( "Exiting " ) . append ( sig . getDeclaringTypeName ( ) ) . toString ( ) ) ; return returnVal ; }
Injection point for logging aspect
158
6
23,234
private void doXPathRes ( final String resource , final Long revision , final OutputStream output , final boolean nodeid , final String xpath ) throws TTException { // Storage connection to treetank ISession session = null ; INodeReadTrx rtx = null ; try { if ( mDatabase . existsResource ( resource ) ) { session = mDatabase . getSession ( new SessionConfiguration ( resource , StandardSettings . KEY ) ) ; // Creating a transaction if ( revision == null ) { rtx = new NodeReadTrx ( session . beginBucketRtx ( session . getMostRecentVersion ( ) ) ) ; } else { rtx = new NodeReadTrx ( session . beginBucketRtx ( revision ) ) ; } final AbsAxis axis = new XPathAxis ( rtx , xpath ) ; for ( final long key : axis ) { WorkerHelper . serializeXML ( session , output , false , nodeid , key , revision ) . call ( ) ; } } } catch ( final Exception globExcep ) { throw new WebApplicationException ( globExcep , Response . Status . INTERNAL_SERVER_ERROR ) ; } finally { WorkerHelper . closeRTX ( rtx , session ) ; } }
This method performs an XPath evaluation and writes it to a given output stream .
266
16
23,235
@ Override public ConfigurationStore getStore ( final String name ) throws ConfigException { try { final File dir = new File ( dirPath ) ; final String newPath = dirPath + name ; final File [ ] files = dir . listFiles ( new DirsOnly ( ) ) ; for ( final File f : files ) { if ( f . getName ( ) . equals ( name ) ) { return new ConfigurationFileStore ( newPath ) ; } } final File newDir = new File ( newPath ) ; if ( ! newDir . mkdir ( ) ) { throw new ConfigException ( "Unable to create directory " + newPath ) ; } return new ConfigurationFileStore ( newPath ) ; } catch ( final Throwable t ) { throw new ConfigException ( t ) ; } }
Get the named store . Create it if it does not exist
166
12
23,236
public static String jsonNameVal ( final String indent , final String name , final String val ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( indent ) ; sb . append ( "\"" ) ; sb . append ( name ) ; sb . append ( "\": " ) ; if ( val != null ) { sb . append ( jsonEncode ( val ) ) ; } return sb . toString ( ) ; }
Encode a json name and value for output
98
9
23,237
private static Element createResultElement ( final Document document ) { return document . createElementNS ( JaxRxConstants . URL , JaxRxConstants . JAXRX + ":results" ) ; }
This method creates the response XML element .
47
8
23,238
public static StreamingOutput buildDOMResponse ( final List < String > availableResources ) { try { final Document document = createSurroundingXMLResp ( ) ; final Element resElement = createResultElement ( document ) ; final List < Element > resources = createCollectionElement ( availableResources , document ) ; for ( final Element resource : resources ) { resElement . appendChild ( resource ) ; } document . appendChild ( resElement ) ; return createStream ( document ) ; } catch ( final ParserConfigurationException exc ) { throw new JaxRxException ( exc ) ; } }
Builds a DOM response .
121
6
23,239
public static StreamingOutput createStream ( final Document doc ) { return new StreamingOutput ( ) { @ Override public void write ( final OutputStream output ) { synchronized ( output ) { final DOMSource domSource = new DOMSource ( doc ) ; final StreamResult streamResult = new StreamResult ( output ) ; Transformer transformer ; try { transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . transform ( domSource , streamResult ) ; } catch ( final TransformerException exc ) { exc . printStackTrace ( ) ; throw new JaxRxException ( exc ) ; } } } } ; }
Creates an output stream from the specified document .
133
10
23,240
private void writeFile ( final String fileName , final byte [ ] bs , final boolean append ) throws IOException { FileOutputStream fstr = null ; try { fstr = new FileOutputStream ( fileName , append ) ; fstr . write ( bs ) ; // Terminate key with newline fstr . write ( ' ' ) ; fstr . flush ( ) ; } finally { if ( fstr != null ) { fstr . close ( ) ; } } }
Write a single string to a file . Used to write keys
102
12
23,241
static String root ( final ResourcePath path ) { if ( path . getDepth ( ) == 1 ) return path . getResourcePath ( ) ; throw new JaxRxException ( 404 , "Resource not found: " + path ) ; }
Returns the root resource of the specified path .
51
9
23,242
public String getResourcePath ( ) { final StringBuilder sb = new StringBuilder ( ) ; for ( final String r : resource ) sb . append ( r + ' ' ) ; return sb . substring ( 0 , Math . max ( 0 , sb . length ( ) - 1 ) ) ; }
Returns the complete resource path string .
66
7
23,243
public String getResource ( final int level ) { if ( level < resource . length ) { return resource [ level ] ; } // offset is out of bounds... throw new IndexOutOfBoundsException ( "Index: " + level + ", Size: " + resource . length ) ; }
Returns the resource at the specified level .
60
8
23,244
public static String getHeaders ( final HttpServletRequest req ) { Enumeration en = req . getHeaderNames ( ) ; StringBuffer sb = new StringBuffer ( ) ; while ( en . hasMoreElements ( ) ) { String name = ( String ) en . nextElement ( ) ; sb . append ( name ) ; sb . append ( ": " ) ; sb . append ( req . getHeader ( name ) ) ; sb . append ( "\n" ) ; } return sb . toString ( ) ; }
Return a concatenated string of all the headers
118
10
23,245
public static void dumpHeaders ( final HttpServletRequest req ) { Enumeration en = req . getHeaderNames ( ) ; while ( en . hasMoreElements ( ) ) { String name = ( String ) en . nextElement ( ) ; logger . debug ( name + ": " + req . getHeader ( name ) ) ; } }
Print all the headers
75
4
23,246
public static Collection < Locale > getLocales ( final HttpServletRequest req ) { if ( req . getHeader ( "Accept-Language" ) == null ) { return null ; } @ SuppressWarnings ( "unchecked" ) Enumeration < Locale > lcs = req . getLocales ( ) ; ArrayList < Locale > locales = new ArrayList < Locale > ( ) ; while ( lcs . hasMoreElements ( ) ) { locales . add ( lcs . nextElement ( ) ) ; } return locales ; }
If there is no Accept - Language header returns null otherwise returns a collection of Locales ordered with preferred first .
123
22
23,247
public static void initTimezones ( final String serverUrl ) throws TimezonesException { try { if ( tzs == null ) { tzs = ( Timezones ) Class . forName ( "org.bedework.util.timezones.TimezonesImpl" ) . newInstance ( ) ; } tzs . init ( serverUrl ) ; } catch ( final TimezonesException te ) { throw te ; } catch ( final Throwable t ) { throw new TimezonesException ( t ) ; } }
Initialize the timezones system .
114
8
23,248
public static String getThreadDefaultTzid ( ) throws TimezonesException { final String id = threadTzid . get ( ) ; if ( id != null ) { return id ; } return getSystemDefaultTzid ( ) ; }
Get the default timezone id for this thread .
52
10
23,249
public static String getUtc ( final String time , final String tzid ) throws TimezonesException { return getTimezones ( ) . calculateUtc ( time , tzid ) ; }
Given a String time value and a possibly null tzid will return a UTC formatted value . The supplied time should be of the form yyyyMMdd or yyyyMMddThhmmss or yyyyMMddThhmmssZ
43
53
23,250
public static void rolloverLogfile ( ) { Logger logger = Logger . getRootLogger ( ) ; // NOSONAR - local logger used on purpose here @ SuppressWarnings ( "unchecked" ) Enumeration < Object > appenders = logger . getAllAppenders ( ) ; while ( appenders . hasMoreElements ( ) ) { Object obj = appenders . nextElement ( ) ; if ( obj instanceof RollingFileAppender ) { ( ( RollingFileAppender ) obj ) . rollOver ( ) ; } } }
Manually roll over logfiles to start with a new logfile
119
13
23,251
public static synchronized boolean createStorage ( final StorageConfiguration pStorageConfig ) throws TTIOException { boolean returnVal = true ; // if file is existing, skipping if ( ! pStorageConfig . mFile . exists ( ) && pStorageConfig . mFile . mkdirs ( ) ) { returnVal = IOUtils . createFolderStructure ( pStorageConfig . mFile , StorageConfiguration . Paths . values ( ) ) ; // serialization of the config StorageConfiguration . serialize ( pStorageConfig ) ; // if something was not correct, delete the partly created // substructure if ( ! returnVal ) { pStorageConfig . mFile . delete ( ) ; } return returnVal ; } else { return false ; } }
Creating a storage . This includes loading the storageconfiguration building up the structure and preparing everything for login .
153
21
23,252
public static synchronized void truncateStorage ( final StorageConfiguration pConf ) throws TTException { // check that database must be closed beforehand if ( ! STORAGEMAP . containsKey ( pConf . mFile ) ) { if ( existsStorage ( pConf . mFile ) ) { final IStorage storage = new Storage ( pConf ) ; final File [ ] resources = new File ( pConf . mFile , StorageConfiguration . Paths . Data . getFile ( ) . getName ( ) ) . listFiles ( ) ; for ( final File resource : resources ) { storage . truncateResource ( new SessionConfiguration ( resource . getName ( ) , null ) ) ; } storage . close ( ) ; // instantiate the database for deletion IOUtils . recursiveDelete ( pConf . mFile ) ; } } }
Truncate a storage . This deletes all relevant data . All running sessions must be closed beforehand .
171
21
23,253
public static synchronized boolean existsStorage ( final File pStoragePath ) { // if file is existing and folder is a tt-dataplace, delete it if ( pStoragePath . exists ( ) && IOUtils . compareStructure ( pStoragePath , StorageConfiguration . Paths . values ( ) ) == 0 ) { return true ; } else { return false ; } }
Check if Storage exists or not at a given path .
79
11
23,254
public static synchronized IStorage openStorage ( final File pFile ) throws TTException { checkState ( existsStorage ( pFile ) , "DB could not be opened (since it was not created?) at location %s" , pFile ) ; StorageConfiguration config = StorageConfiguration . deserialize ( pFile ) ; final Storage storage = new Storage ( config ) ; final IStorage returnVal = STORAGEMAP . putIfAbsent ( pFile , storage ) ; if ( returnVal == null ) { return storage ; } else { return returnVal ; } }
Open database . A database can be opened only once . Afterwards the singleton instance bound to the File is given back .
117
24
23,255
private static void bootstrap ( final Storage pStorage , final ResourceConfiguration pResourceConf ) throws TTException { final IBackend storage = pResourceConf . mBackend ; storage . initialize ( ) ; final IBackendWriter writer = storage . getWriter ( ) ; final UberBucket uberBucket = new UberBucket ( 1 , 0 , 1 ) ; long newBucketKey = uberBucket . incrementBucketCounter ( ) ; uberBucket . setReferenceKey ( IReferenceBucket . GUARANTEED_INDIRECT_OFFSET , newBucketKey ) ; uberBucket . setReferenceHash ( IReferenceBucket . GUARANTEED_INDIRECT_OFFSET , IConstants . BOOTSTRAP_HASHED ) ; writer . write ( uberBucket ) ; // --- Create revision tree // ------------------------------------------------ // Initialize revision tree to guarantee that there is a revision root // bucket. IReferenceBucket bucket ; for ( int i = 0 ; i < IConstants . INDIRECT_BUCKET_COUNT . length ; i ++ ) { bucket = new IndirectBucket ( newBucketKey ) ; newBucketKey = uberBucket . incrementBucketCounter ( ) ; bucket . setReferenceKey ( 0 , newBucketKey ) ; bucket . setReferenceHash ( 0 , IConstants . BOOTSTRAP_HASHED ) ; writer . write ( bucket ) ; } RevisionRootBucket revBucket = new RevisionRootBucket ( newBucketKey , 0 , 0 ) ; newBucketKey = uberBucket . incrementBucketCounter ( ) ; // establishing fresh MetaBucket MetaBucket metaBucker = new MetaBucket ( newBucketKey ) ; revBucket . setReferenceKey ( RevisionRootBucket . META_REFERENCE_OFFSET , newBucketKey ) ; revBucket . setReferenceHash ( RevisionRootBucket . META_REFERENCE_OFFSET , IConstants . BOOTSTRAP_HASHED ) ; newBucketKey = uberBucket . incrementBucketCounter ( ) ; bucket = new IndirectBucket ( newBucketKey ) ; revBucket . setReferenceKey ( IReferenceBucket . GUARANTEED_INDIRECT_OFFSET , newBucketKey ) ; revBucket . setReferenceHash ( IReferenceBucket . GUARANTEED_INDIRECT_OFFSET , IConstants . BOOTSTRAP_HASHED ) ; writer . write ( revBucket ) ; writer . write ( metaBucker ) ; // --- Create data tree // ---------------------------------------------------- // Initialize revision tree to guarantee that there is a revision root // bucket. for ( int i = 0 ; i < IConstants . INDIRECT_BUCKET_COUNT . length ; i ++ ) { newBucketKey = uberBucket . incrementBucketCounter ( ) ; bucket . setReferenceKey ( 0 , newBucketKey ) ; bucket . setReferenceHash ( 0 , IConstants . BOOTSTRAP_HASHED ) ; writer . write ( bucket ) ; bucket = new IndirectBucket ( newBucketKey ) ; } final DataBucket ndp = new DataBucket ( newBucketKey , IConstants . NULLDATA ) ; writer . write ( ndp ) ; writer . writeUberBucket ( uberBucket ) ; writer . close ( ) ; storage . close ( ) ; }
Boostraping a resource within this storage .
740
9
23,256
public IXPathToken nextToken ( ) { // some tokens start in another state than the START state mState = mStartState ; // reset startState mStartState = State . START ; mOutput = new StringBuilder ( ) ; mFinnished = false ; mType = TokenType . INVALID ; mLastPos = mPos ; do { mInput = mQuery . charAt ( mPos ) ; switch ( mState ) { case START : // specify token type according to first char scanStart ( ) ; break ; case NUMBER : // number scanNumber ( ) ; break ; case TEXT : // some text, could be a name scanText ( ) ; break ; case SPECIAL2 : // special character that could have 2 digits scanTwoDigitSpecial ( ) ; break ; case COMMENT : scanComment ( ) ; break ; case E_NUM : scanENum ( ) ; break ; default : mPos ++ ; mFinnished = true ; } } while ( ! mFinnished || mPos >= mQuery . length ( ) ) ; if ( mCommentCount > 0 ) { throw new IllegalStateException ( "Error in Query. Comment does not end." ) ; } return new VariableXPathToken ( mOutput . toString ( ) , mType ) ; }
Reads the string char by char and returns one token by call . The scanning starts in the start state if not further specified before and specifies the next scanner state and the type of the future token according to its first char . As soon as the current char does not fit the conditions for the current token type the token is generated and returned .
270
68
23,257
private void scanStart ( ) { if ( isNumber ( mInput ) ) { mState = State . NUMBER ; mOutput . append ( mInput ) ; mType = TokenType . VALUE ; // number } else if ( isFirstLetter ( mInput ) ) { mState = State . TEXT ; // word mOutput . append ( mInput ) ; mType = TokenType . TEXT ; } else if ( isSpecial ( mInput ) ) { mState = State . SPECIAL ; // special character with only one digit mOutput . append ( mInput ) ; mType = retrieveType ( mInput ) ; mFinnished = true ; } else if ( isTwoDigistSpecial ( mInput ) ) { mState = State . SPECIAL2 ; // 2 digit special character mOutput . append ( mInput ) ; mType = retrieveType ( mInput ) ; } else if ( ( mInput == ' ' ) || ( mInput == ' ' ) ) { mState = State . START ; mOutput . append ( mInput ) ; mFinnished = true ; mType = TokenType . SPACE ; } else if ( mInput == ' ' ) { mType = TokenType . END ; // end of query mFinnished = true ; mPos -- ; } else { mState = State . UNKNOWN ; // unknown character mOutput . append ( mInput ) ; mFinnished = true ; } mPos ++ ; }
Scans the first character of a token and decides what type it is .
305
15
23,258
private TokenType retrieveType ( final char paramInput ) { TokenType type ; switch ( paramInput ) { case ' ' : type = TokenType . COMMA ; break ; case ' ' : type = TokenType . OPEN_BR ; break ; case ' ' : type = TokenType . CLOSE_BR ; break ; case ' ' : type = TokenType . OPEN_SQP ; break ; case ' ' : type = TokenType . CLOSE_SQP ; break ; case ' ' : type = TokenType . AT ; break ; case ' ' : type = TokenType . EQ ; break ; case ' ' : case ' ' : type = TokenType . COMP ; break ; case ' ' : type = TokenType . N_EQ ; break ; case ' ' : type = TokenType . SLASH ; break ; case ' ' : type = TokenType . COLON ; break ; case ' ' : type = TokenType . POINT ; break ; case ' ' : type = TokenType . PLUS ; break ; case ' ' : type = TokenType . MINUS ; break ; case ' ' : type = TokenType . SINGLE_QUOTE ; break ; case ' ' : type = TokenType . DBL_QUOTE ; break ; case ' ' : type = TokenType . DOLLAR ; break ; case ' ' : type = TokenType . INTERROGATION ; break ; case ' ' : type = TokenType . STAR ; break ; case ' ' : type = TokenType . OR ; break ; default : type = TokenType . INVALID ; } return type ; }
Returns the type of the given character .
338
8
23,259
private boolean isSpecial ( final char paramInput ) { return ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) ; }
Checks if the given character is a special character .
141
11
23,260
private void scanNumber ( ) { if ( mInput >= ' ' && mInput <= ' ' ) { mOutput . append ( mInput ) ; mPos ++ ; } else { // could be an e-number if ( mInput == ' ' || mInput == ' ' ) { mStartState = State . E_NUM ; } mFinnished = true ; } }
Scans a number token . A number only consists of digits .
80
13
23,261
private void scanText ( ) { if ( isLetter ( mInput ) ) { mOutput . append ( mInput ) ; mPos ++ ; } else { mType = TokenType . TEXT ; mFinnished = true ; } }
Scans text token . A text is everything that with a character . It can contain numbers all letters in upper or lower case and underscores .
50
28
23,262
private void scanENum ( ) { if ( mInput == ' ' || mInput == ' ' ) { mOutput . append ( mInput ) ; mState = State . START ; mType = TokenType . E_NUMBER ; mFinnished = true ; mPos ++ ; } else { mFinnished = true ; mState = State . START ; mType = TokenType . INVALID ; } }
Scans all numbers that contain an e .
90
9
23,263
private void scanComment ( ) { final char input = mQuery . charAt ( mPos + 1 ) ; if ( mInput == ' ' ) { // check if is end of comment, indicated by ':)' if ( input == ' ' ) { mCommentCount -- ; if ( mCommentCount == 0 ) { mState = State . START ; // increment position, because next digit has already been // processed mPos ++ ; } } } else if ( mInput == ' ' ) { // check if start of new nested comment, indicated by '(:' if ( input == ' ' ) { mCommentCount ++ ; } } mPos ++ ; }
Scans comments .
136
4
23,264
private boolean isLetter ( final char paramInput ) { return ( paramInput >= ' ' && paramInput <= ' ' ) || ( paramInput >= ' ' && paramInput <= ' ' ) || ( paramInput >= ' ' && paramInput <= ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) || ( paramInput == ' ' ) ; }
Checks if the given character is a letter .
79
10
23,265
public StreamingOutput getResource ( final String resourceName , final long nodeId , final Map < QueryParameter , String > queryParams ) throws JaxRxException { final StreamingOutput sOutput = new StreamingOutput ( ) { @ Override public void write ( final OutputStream output ) throws IOException , JaxRxException { // final String xPath = queryParams.get(QueryParameter.QUERY); final String revision = queryParams . get ( QueryParameter . REVISION ) ; final String wrap = queryParams . get ( QueryParameter . WRAP ) ; final String doNodeId = queryParams . get ( QueryParameter . OUTPUT ) ; final boolean wrapResult = ( wrap == null ) ? false : wrap . equalsIgnoreCase ( YESSTRING ) ; final boolean nodeid = ( doNodeId == null ) ? false : doNodeId . equalsIgnoreCase ( YESSTRING ) ; final Long rev = revision == null ? null : Long . valueOf ( revision ) ; serialize ( resourceName , nodeId , rev , nodeid , output , wrapResult ) ; } } ; return sOutput ; }
This method is responsible to deliver the whole XML resource addressed by a unique node id .
241
17
23,266
public StreamingOutput performQueryOnResource ( final String resourceName , final long nodeId , final String query , final Map < QueryParameter , String > queryParams ) { final StreamingOutput sOutput = new StreamingOutput ( ) { @ Override public void write ( final OutputStream output ) throws IOException , JaxRxException { final String revision = queryParams . get ( QueryParameter . REVISION ) ; final String wrap = queryParams . get ( QueryParameter . WRAP ) ; final String doNodeId = queryParams . get ( QueryParameter . OUTPUT ) ; final boolean wrapResult = ( wrap == null ) ? true : wrap . equalsIgnoreCase ( YESSTRING ) ; final boolean nodeid = ( doNodeId == null ) ? false : doNodeId . equalsIgnoreCase ( YESSTRING ) ; final Long rev = revision == null ? null : Long . valueOf ( revision ) ; final RestXPathProcessor xpathProcessor = new RestXPathProcessor ( mDatabase ) ; try { xpathProcessor . getXpathResource ( resourceName , nodeId , query , nodeid , rev , output , wrapResult ) ; } catch ( final TTException exce ) { throw new JaxRxException ( exce ) ; } } } ; return sOutput ; }
This method is responsible to perform a XPath query expression on the XML resource which is addressed through a unique node id .
277
24
23,267
public void modifyResource ( final String resourceName , final long nodeId , final InputStream newValue ) throws JaxRxException { synchronized ( resourceName ) { ISession session = null ; INodeWriteTrx wtx = null ; boolean abort = false ; if ( mDatabase . existsResource ( resourceName ) ) { try { // Creating a new session session = mDatabase . getSession ( new SessionConfiguration ( resourceName , StandardSettings . KEY ) ) ; // Creating a write transaction wtx = new NodeWriteTrx ( session , session . beginBucketWtx ( ) , HashKind . Rolling ) ; if ( wtx . moveTo ( nodeId ) ) { final long parentKey = wtx . getNode ( ) . getParentKey ( ) ; wtx . remove ( ) ; wtx . moveTo ( parentKey ) ; WorkerHelper . shredInputStream ( wtx , newValue , EShredderInsert . ADDASFIRSTCHILD ) ; } else { // workerHelper.closeWTX(abort, wtx, session, database); throw new JaxRxException ( 404 , NOTFOUND ) ; } } catch ( final TTException exc ) { abort = true ; throw new JaxRxException ( exc ) ; } finally { try { WorkerHelper . closeWTX ( abort , wtx , session ) ; } catch ( final TTException exce ) { throw new JaxRxException ( exce ) ; } } } else { throw new JaxRxException ( 404 , "Requested resource not found" ) ; } } }
This method is responsible to modify the XML resource which is addressed through a unique node id .
333
18
23,268
public void addSubResource ( final String resourceName , final long nodeId , final InputStream input , final EIdAccessType type ) throws JaxRxException { ISession session = null ; INodeWriteTrx wtx = null ; synchronized ( resourceName ) { boolean abort ; if ( mDatabase . existsResource ( resourceName ) ) { abort = false ; try { // Creating a new session session = mDatabase . getSession ( new SessionConfiguration ( resourceName , StandardSettings . KEY ) ) ; // Creating a write transaction wtx = new NodeWriteTrx ( session , session . beginBucketWtx ( ) , HashKind . Rolling ) ; final boolean exist = wtx . moveTo ( nodeId ) ; if ( exist ) { if ( type == EIdAccessType . FIRSTCHILD ) { WorkerHelper . shredInputStream ( wtx , input , EShredderInsert . ADDASFIRSTCHILD ) ; } else if ( type == EIdAccessType . RIGHTSIBLING ) { WorkerHelper . shredInputStream ( wtx , input , EShredderInsert . ADDASRIGHTSIBLING ) ; } else if ( type == EIdAccessType . LASTCHILD ) { if ( wtx . moveTo ( ( ( ITreeStructData ) wtx . getNode ( ) ) . getFirstChildKey ( ) ) ) { long last = wtx . getNode ( ) . getDataKey ( ) ; while ( wtx . moveTo ( ( ( ITreeStructData ) wtx . getNode ( ) ) . getRightSiblingKey ( ) ) ) { last = wtx . getNode ( ) . getDataKey ( ) ; } wtx . moveTo ( last ) ; WorkerHelper . shredInputStream ( wtx , input , EShredderInsert . ADDASRIGHTSIBLING ) ; } else { throw new JaxRxException ( 404 , NOTFOUND ) ; } } else if ( type == EIdAccessType . LEFTSIBLING && wtx . moveTo ( ( ( ITreeStructData ) wtx . getNode ( ) ) . getLeftSiblingKey ( ) ) ) { WorkerHelper . shredInputStream ( wtx , input , EShredderInsert . ADDASRIGHTSIBLING ) ; } } else { throw new JaxRxException ( 404 , NOTFOUND ) ; } } catch ( final JaxRxException exce ) { abort = true ; throw exce ; } catch ( final Exception exce ) { abort = true ; throw new JaxRxException ( exce ) ; } finally { try { WorkerHelper . closeWTX ( abort , wtx , session ) ; } catch ( final TTException exce ) { throw new JaxRxException ( exce ) ; } } } } }
This method is responsible to perform a POST request to a node id . This method adds a new XML subtree as first child or as right sibling to the node which is addressed through a node id .
598
40
23,269
private void serialize ( final String resource , final long nodeId , final Long revision , final boolean doNodeId , final OutputStream output , final boolean wrapResult ) { if ( mDatabase . existsResource ( resource ) ) { ISession session = null ; try { session = mDatabase . getSession ( new SessionConfiguration ( resource , StandardSettings . KEY ) ) ; if ( wrapResult ) { output . write ( BEGINRESULT ) ; final XMLSerializerProperties props = new XMLSerializerProperties ( ) ; final XMLSerializerBuilder builder = new XMLSerializerBuilder ( session , nodeId , output , props ) ; builder . setREST ( doNodeId ) ; builder . setID ( doNodeId ) ; builder . setDeclaration ( false ) ; final XMLSerializer serializer = builder . build ( ) ; serializer . call ( ) ; output . write ( ENDRESULT ) ; } else { final XMLSerializerProperties props = new XMLSerializerProperties ( ) ; final XMLSerializerBuilder builder = new XMLSerializerBuilder ( session , nodeId , output , props ) ; builder . setREST ( doNodeId ) ; builder . setID ( doNodeId ) ; builder . setDeclaration ( false ) ; final XMLSerializer serializer = builder . build ( ) ; serializer . call ( ) ; } } catch ( final TTException ttExcep ) { throw new JaxRxException ( ttExcep ) ; } catch ( final IOException ioExcep ) { throw new JaxRxException ( ioExcep ) ; } catch ( final Exception globExcep ) { if ( globExcep instanceof JaxRxException ) { // NOPMD due // to // different // exception // types throw ( JaxRxException ) globExcep ; } else { throw new JaxRxException ( globExcep ) ; } } finally { try { WorkerHelper . closeRTX ( null , session ) ; } catch ( final TTException exce ) { throw new JaxRxException ( exce ) ; } } } else { throw new JaxRxException ( 404 , "Resource does not exist" ) ; } }
This method serializes requested resource
472
6
23,270
public static final AbsComparator getComparator ( final INodeReadTrx paramRtx , final AbsAxis paramOperandOne , final AbsAxis paramOperandTwo , final CompKind paramKind , final String paramVal ) { if ( "eq" . equals ( paramVal ) || "lt" . equals ( paramVal ) || "le" . equals ( paramVal ) || "gt" . equals ( paramVal ) || "ge" . equals ( paramVal ) ) { return new ValueComp ( paramRtx , paramOperandOne , paramOperandTwo , paramKind ) ; } else if ( "=" . equals ( paramVal ) || "!=" . equals ( paramVal ) || "<" . equals ( paramVal ) || "<=" . equals ( paramVal ) || ">" . equals ( paramVal ) || ">=" . equals ( paramVal ) ) { return new GeneralComp ( paramRtx , paramOperandOne , paramOperandTwo , paramKind ) ; } else if ( "is" . equals ( paramVal ) || "<<" . equals ( paramVal ) || ">>" . equals ( paramVal ) ) { return new NodeComp ( paramRtx , paramOperandOne , paramOperandTwo , paramKind ) ; } throw new IllegalStateException ( paramVal + " is not a valid comparison." ) ; }
Factory method to implement the comparator .
288
8
23,271
public Integer getIntReqPar ( final String name , final String errProp ) throws Throwable { try { return super . getIntReqPar ( name ) ; } catch ( final Throwable t ) { getErr ( ) . emit ( errProp , getReqPar ( name ) ) ; return null ; } }
Get an Integer request parameter or null . Emit error for non - null and non integer
69
18
23,272
public static String retrieveData ( String sUrl , int timeout ) throws IOException { return retrieveData ( sUrl , null , timeout ) ; }
Download data from an URL .
30
6
23,273
public static String retrieveData ( String sUrl , String encoding , int timeout , SSLSocketFactory sslFactory ) throws IOException { byte [ ] rawData = retrieveRawData ( sUrl , timeout , sslFactory ) ; if ( encoding == null ) { return new String ( rawData ) ; // NOSONAR } return new String ( rawData , encoding ) ; }
Download data from an URL if necessary converting from a character encoding .
80
13
23,274
public static byte [ ] retrieveRawData ( String sUrl , int timeout , SSLSocketFactory sslFactory ) throws IOException { URL url = new URL ( sUrl ) ; LOGGER . fine ( "Using the following URL for retrieving the data: " + url . toString ( ) ) ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; // set specified timeout if non-zero if ( timeout != 0 ) { conn . setConnectTimeout ( timeout ) ; conn . setReadTimeout ( timeout ) ; } try { conn . setDoOutput ( false ) ; conn . setDoInput ( true ) ; if ( conn instanceof HttpsURLConnection && sslFactory != null ) { ( ( HttpsURLConnection ) conn ) . setSSLSocketFactory ( sslFactory ) ; } conn . connect ( ) ; int code = conn . getResponseCode ( ) ; if ( code != HttpURLConnection . HTTP_OK && code != HttpURLConnection . HTTP_CREATED && code != HttpURLConnection . HTTP_ACCEPTED ) { String msg = "Error " + code + " returned while retrieving response for url '" + url + "' message from client: " + conn . getResponseMessage ( ) ; LOGGER . warning ( msg ) ; throw new IOException ( msg ) ; } try ( InputStream strm = conn . getInputStream ( ) ) { return IOUtils . toByteArray ( strm ) ; } // actually read the contents, even if we are not using it to simulate a full download of the data /*ByteArrayOutputStream memStream = new ByteArrayOutputStream(conn.getContentLength() == -1 ? 40000 : conn.getContentLength()); try { byte b[] = new byte[4096]; int len; while ((len = strm.read(b)) > 0) { memStream.write(b, 0, len); } } finally { memStream.close(); } if(LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Received data, size: " + memStream.size() + "(" + conn.getContentLength() + ") first bytes: " + replaceInvalidChar(memStream.toString().substring(0, Math.min(memStream.size(), REPORT_PEEK_COUNT)))); } return memStream.toByteArray();*/ } finally { conn . disconnect ( ) ; } }
Download data from an URL and return the raw bytes .
527
11
23,275
private AtomicValue atomize ( final AbsAxis mOperand ) { int type = getNode ( ) . getTypeKey ( ) ; AtomicValue atom ; if ( XPATH_10_COMP ) { atom = new AtomicValue ( ( ( ITreeValData ) getNode ( ) ) . getRawValue ( ) , getNode ( ) . getTypeKey ( ) ) ; } else { // unatomicType is cast to double if ( type == NamePageHash . generateHashForString ( "xs:untypedAtomic" ) ) { type = NamePageHash . generateHashForString ( "xs:double" ) ; // TODO: throw error, of cast fails } atom = new AtomicValue ( ( ( ITreeValData ) getNode ( ) ) . getRawValue ( ) , getNode ( ) . getTypeKey ( ) ) ; } // if (!XPATH_10_COMP && operand.hasNext()) { // throw new XPathError(ErrorType.XPTY0004); // } return atom ; }
Atomizes an operand according to the rules specified in the XPath specification .
223
17
23,276
public String checkProp ( final Properties pr , final String name , final String defaultVal ) { String val = pr . getProperty ( name ) ; if ( val == null ) { pr . put ( name , defaultVal ) ; val = defaultVal ; } return val ; }
If the named property is present and has a value use that . Otherwise set the value to the given default and use that .
57
25
23,277
public void finishExpr ( final INodeReadTrx mTransaction , final int mNum ) { // all singleExpression that are on the stack will be combined in the // sequence, so the number of singleExpressions in the sequence and the // size // of the stack containing these SingleExpressions have to be the same. if ( getPipeStack ( ) . size ( ) != mNum ) { // this should never happen throw new IllegalStateException ( "The query has not been processed correctly" ) ; } int no = mNum ; AbsAxis [ ] axis ; if ( no > 1 ) { axis = new AbsAxis [ no ] ; // add all SingleExpression to a list while ( no -- > 0 ) { axis [ no ] = getPipeStack ( ) . pop ( ) . getExpr ( ) ; } if ( mExprStack . size ( ) > 1 ) { assert mExprStack . peek ( ) . empty ( ) ; mExprStack . pop ( ) ; } if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( new SequenceAxis ( mTransaction , axis ) ) ; } else if ( no == 1 ) { // only one expression does not need to be capsled by a seq axis = new AbsAxis [ 1 ] ; axis [ 0 ] = getPipeStack ( ) . pop ( ) . getExpr ( ) ; if ( mExprStack . size ( ) > 1 ) { assert mExprStack . peek ( ) . empty ( ) ; mExprStack . pop ( ) ; } if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } final AbsAxis iAxis ; if ( mExprStack . size ( ) == 1 && getPipeStack ( ) . size ( ) == 1 && getExpression ( ) . getSize ( ) == 0 ) { iAxis = new SequenceAxis ( mTransaction , axis ) ; } else { iAxis = axis [ 0 ] ; } getExpression ( ) . add ( iAxis ) ; } else { mExprStack . pop ( ) ; } }
Ends an expression . This means that the currently used pipeline stack will be emptied and the singleExpressions that were on the stack are combined by a sequence expression which is lated added to the next pipeline stack .
502
43
23,278
public void addIfExpression ( final INodeReadTrx mTransaction ) { assert getPipeStack ( ) . size ( ) >= 3 ; final INodeReadTrx rtx = mTransaction ; final AbsAxis elseExpr = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis thenExpr = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis ifExpr = getPipeStack ( ) . pop ( ) . getExpr ( ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( new IfAxis ( rtx , ifExpr , thenExpr , elseExpr ) ) ; }
Adds a if expression to the pipeline .
184
8
23,279
public void addCompExpression ( final INodeReadTrx mTransaction , final String mComp ) { assert getPipeStack ( ) . size ( ) >= 2 ; final INodeReadTrx rtx = mTransaction ; final AbsAxis paramOperandTwo = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis paramOperandOne = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final CompKind kind = CompKind . fromString ( mComp ) ; final AbsAxis axis = AbsComparator . getComparator ( rtx , paramOperandOne , paramOperandTwo , kind , mComp ) ; // // TODO: use typeswitch of JAVA 7 // if (mComp.equals("eq")) { // // axis = new ValueComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals("ne")) { // // axis = new ValueComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals("lt")) { // // axis = new ValueComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals("le")) { // // axis = new ValueComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals("gt")) { // // axis = new ValueComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals("ge")) { // // axis = new ValueComp(rtx, paramOperandOne, paramOperandTwo, kind); // // } else if (mComp.equals("=")) { // // axis = new GeneralComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals("!=")) { // // axis = new GeneralComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals("<")) { // // axis = new GeneralComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals("<=")) { // // axis = new GeneralComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals(">")) { // // axis = new GeneralComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals(">=")) { // // axis = new GeneralComp(rtx, paramOperandOne, paramOperandTwo, kind); // // } else if (mComp.equals("is")) { // // axis = new NodeComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals("<<")) { // // axis = new NodeComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else if (mComp.equals(">>")) { // // axis = new NodeComp(rtx, paramOperandOne, paramOperandTwo, kind); // } else { // throw new IllegalStateException(mComp + // " is not a valid comparison."); // // } if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( axis ) ; }
Adds a comparison expression to the pipeline .
792
8
23,280
public void addOperatorExpression ( final INodeReadTrx mTransaction , final String mOperator ) { assert getPipeStack ( ) . size ( ) >= 1 ; final INodeReadTrx rtx = mTransaction ; final AbsAxis mOperand2 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; // the unary operation only has one operator final AbsAxis mOperand1 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } final AbsAxis axis ; // TODO: use typeswitch of JAVA 7 if ( mOperator . equals ( "+" ) ) { axis = new AddOpAxis ( rtx , mOperand1 , mOperand2 ) ; } else if ( mOperator . equals ( "-" ) ) { axis = new SubOpAxis ( rtx , mOperand1 , mOperand2 ) ; } else if ( mOperator . equals ( "*" ) ) { axis = new MulOpAxis ( rtx , mOperand1 , mOperand2 ) ; } else if ( mOperator . equals ( "div" ) ) { axis = new DivOpAxis ( rtx , mOperand1 , mOperand2 ) ; } else if ( mOperator . equals ( "idiv" ) ) { axis = new IDivOpAxis ( rtx , mOperand1 , mOperand2 ) ; } else if ( mOperator . equals ( "mod" ) ) { axis = new ModOpAxis ( rtx , mOperand1 , mOperand2 ) ; } else { // TODO: unary operator throw new IllegalStateException ( mOperator + " is not a valid operator." ) ; } getExpression ( ) . add ( axis ) ; }
Adds an operator expression to the pipeline .
432
8
23,281
public void addUnionExpression ( final INodeReadTrx mTransaction ) { assert getPipeStack ( ) . size ( ) >= 2 ; final AbsAxis mOperand2 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis mOperand1 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( new DupFilterAxis ( mTransaction , new UnionAxis ( mTransaction , mOperand1 , mOperand2 ) ) ) ; }
Adds a union expression to the pipeline .
157
8
23,282
public void addAndExpression ( final INodeReadTrx mTransaction ) { assert getPipeStack ( ) . size ( ) >= 2 ; final AbsAxis mOperand2 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis operand1 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( new AndExpr ( mTransaction , operand1 , mOperand2 ) ) ; }
Adds a and expression to the pipeline .
145
8
23,283
public void addOrExpression ( final INodeReadTrx mTransaction ) { assert getPipeStack ( ) . size ( ) >= 2 ; final AbsAxis mOperand2 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis mOperand1 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( new OrExpr ( mTransaction , mOperand1 , mOperand2 ) ) ; }
Adds a or expression to the pipeline .
147
8
23,284
public void addIntExcExpression ( final INodeReadTrx mTransaction , final boolean mIsIntersect ) { assert getPipeStack ( ) . size ( ) >= 2 ; final INodeReadTrx rtx = mTransaction ; final AbsAxis mOperand2 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis mOperand1 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis axis = mIsIntersect ? new IntersectAxis ( rtx , mOperand1 , mOperand2 ) : new ExceptAxis ( rtx , mOperand1 , mOperand2 ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( axis ) ; }
Adds a intersect or a exception expression to the pipeline .
200
11
23,285
public void addLiteral ( final INodeReadTrx pTrans , final AtomicValue pVal ) { getExpression ( ) . add ( new LiteralExpr ( pTrans , AbsAxis . addAtomicToItemList ( pTrans , pVal ) ) ) ; }
Adds a literal expression to the pipeline .
61
8
23,286
public void addStep ( final AbsAxis axis , final AbsFilter mFilter ) { getExpression ( ) . add ( new FilterAxis ( axis , mRtx , mFilter ) ) ; }
Adds a step to the pipeline .
43
7
23,287
public AbsAxis getPipeline ( ) { assert getPipeStack ( ) . size ( ) <= 1 ; if ( getPipeStack ( ) . size ( ) == 1 && mExprStack . size ( ) == 1 ) { return getPipeStack ( ) . pop ( ) . getExpr ( ) ; } else { throw new IllegalStateException ( "Query was not build correctly." ) ; } }
Returns a queue of all pipelines build so far and empties the pipeline stack .
90
16
23,288
public void addPredicate ( final INodeReadTrx mTransaction ) { assert getPipeStack ( ) . size ( ) >= 2 ; final AbsAxis mPredicate = getPipeStack ( ) . pop ( ) . getExpr ( ) ; if ( mPredicate instanceof LiteralExpr ) { mPredicate . hasNext ( ) ; // if is numeric literal -> abbrev for position() final int type = mTransaction . getNode ( ) . getTypeKey ( ) ; if ( type == NamePageHash . generateHashForString ( "xs:integer" ) || type == NamePageHash . generateHashForString ( "xs:double" ) || type == NamePageHash . generateHashForString ( "xs:float" ) || type == NamePageHash . generateHashForString ( "xs:decimal" ) ) { throw new IllegalStateException ( "function fn:position() is not implemented yet." ) ; // getExpression().add( // new PosFilter(transaction, (int) // Double.parseDouble(transaction // .getValue()))); // return; // TODO: YES! it is dirty! // AtomicValue pos = // new AtomicValue(mTransaction.getNode().getRawValue(), // mTransaction // .keyForName("xs:integer")); // long position = mTransaction.getItemList().addItem(pos); // mPredicate.reset(mTransaction.getNode().getNodeKey()); // IAxis function = // new FNPosition(mTransaction, new ArrayList<IAxis>(), // FuncDef.POS.getMin(), FuncDef.POS // .getMax(), // mTransaction.keyForName(FuncDef.POS.getReturnType())); // IAxis expectedPos = new LiteralExpr(mTransaction, position); // // mPredicate = new ValueComp(mTransaction, function, // expectedPos, CompKind.EQ); } } getExpression ( ) . add ( new PredicateFilterAxis ( mTransaction , mPredicate ) ) ; }
Adds a predicate to the pipeline .
447
7
23,289
public void addQuantifierExpr ( final INodeReadTrx mTransaction , final boolean mIsSome , final int mVarNum ) { assert getPipeStack ( ) . size ( ) >= ( mVarNum + 1 ) ; final AbsAxis satisfy = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final List < AbsAxis > vars = new ArrayList < AbsAxis > ( ) ; int num = mVarNum ; while ( num -- > 0 ) { // invert current order of variables to get original variable order vars . add ( num , getPipeStack ( ) . pop ( ) . getExpr ( ) ) ; } final AbsAxis mAxis = mIsSome ? new SomeExpr ( mTransaction , vars , satisfy ) : new EveryExpr ( mTransaction , vars , satisfy ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( mAxis ) ; }
Adds a SomeExpression or an EveryExpression to the pipeline depending on the parameter isSome .
236
20
23,290
public void addCastableExpr ( final INodeReadTrx mTransaction , final SingleType mSingleType ) { assert getPipeStack ( ) . size ( ) >= 1 ; final AbsAxis candidate = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis axis = new CastableExpr ( mTransaction , candidate , mSingleType ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( axis ) ; }
Adds a castable expression to the pipeline .
131
9
23,291
public void addRangeExpr ( final INodeReadTrx mTransaction ) { assert getPipeStack ( ) . size ( ) >= 2 ; final AbsAxis mOperand2 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis mOperand1 = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis axis = new RangeAxis ( mTransaction , mOperand1 , mOperand2 ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( axis ) ; }
Adds a range expression to the pipeline .
155
8
23,292
public void addInstanceOfExpr ( final INodeReadTrx mTransaction , final SequenceType mSequenceType ) { assert getPipeStack ( ) . size ( ) >= 1 ; final AbsAxis candidate = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis axis = new InstanceOfExpr ( mTransaction , candidate , mSequenceType ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( axis ) ; }
Adds a instance of expression to the pipeline .
134
9
23,293
public void addVariableExpr ( final INodeReadTrx mTransaction , final String mVarName ) { assert getPipeStack ( ) . size ( ) >= 1 ; final AbsAxis bindingSeq = getPipeStack ( ) . pop ( ) . getExpr ( ) ; final AbsAxis axis = new VariableAxis ( mTransaction , bindingSeq ) ; mVarRefMap . put ( mVarName , axis ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( axis ) ; }
Adds a variable expression to the pipeline . Adds the expression that will evaluate the results the variable holds .
142
20
23,294
public void addFunction ( final INodeReadTrx mTransaction , final String mFuncName , final int mNum ) throws TTXPathException { assert getPipeStack ( ) . size ( ) >= mNum ; final List < AbsAxis > args = new ArrayList < AbsAxis > ( mNum ) ; // arguments are stored on the stack in reverse order -> invert arg // order for ( int i = 0 ; i < mNum ; i ++ ) { args . add ( getPipeStack ( ) . pop ( ) . getExpr ( ) ) ; } // get right function type final FuncDef func ; try { func = FuncDef . fromString ( mFuncName ) ; } catch ( final NullPointerException e ) { throw EXPathError . XPST0017 . getEncapsulatedException ( ) ; } // get function class final Class < ? extends AbsFunction > function = func . getFunc ( ) ; final Integer min = func . getMin ( ) ; final Integer max = func . getMax ( ) ; final Integer returnType = NamePageHash . generateHashForString ( func . getReturnType ( ) ) ; // parameter types of the function's constructor final Class < ? > [ ] paramTypes = { INodeReadTrx . class , List . class , Integer . TYPE , Integer . TYPE , Integer . TYPE } ; try { // instantiate function class with right constructor final Constructor < ? > cons = function . getConstructor ( paramTypes ) ; final AbsAxis axis = ( AbsAxis ) cons . newInstance ( mTransaction , args , min , max , returnType ) ; if ( getPipeStack ( ) . empty ( ) || getExpression ( ) . getSize ( ) != 0 ) { addExpressionSingle ( ) ; } getExpression ( ) . add ( axis ) ; } catch ( final NoSuchMethodException e ) { throw EXPathError . XPST0017 . getEncapsulatedException ( ) ; } catch ( final IllegalArgumentException e ) { throw EXPathError . XPST0017 . getEncapsulatedException ( ) ; } catch ( final InstantiationException e ) { throw new IllegalStateException ( "Function not implemented yet." ) ; } catch ( final IllegalAccessException e ) { throw EXPathError . XPST0017 . getEncapsulatedException ( ) ; } catch ( final InvocationTargetException e ) { throw EXPathError . XPST0017 . getEncapsulatedException ( ) ; } }
Adds a function to the pipeline .
537
7
23,295
public void addVarRefExpr ( final INodeReadTrx mTransaction , final String mVarName ) { final VariableAxis axis = ( VariableAxis ) mVarRefMap . get ( mVarName ) ; if ( axis != null ) { getExpression ( ) . add ( new VarRefExpr ( mTransaction , axis ) ) ; } else { throw new IllegalStateException ( "Variable " + mVarName + " unkown." ) ; } }
Adds a VarRefExpr to the pipeline . This Expression holds a reference to the current context item of the specified variable .
101
25
23,296
public static boolean stopProcess ( final AbstractProcessorThread proc ) { proc . info ( "************************************************************" ) ; proc . info ( " * Stopping " + proc . getName ( ) ) ; proc . info ( "************************************************************" ) ; proc . setRunning ( false ) ; proc . interrupt ( ) ; boolean ok = true ; try { proc . join ( 20 * 1000 ) ; } catch ( final InterruptedException ignored ) { } catch ( final Throwable t ) { proc . error ( "Error waiting for processor termination" ) ; proc . error ( t ) ; ok = false ; } proc . info ( "************************************************************" ) ; proc . info ( " * " + proc . getName ( ) + " terminated" ) ; proc . info ( "************************************************************" ) ; return ok ; }
Shut down a running process .
174
6
23,297
public void reset ( final long paramNodeKey ) { mStartKey = paramNodeKey ; mKey = paramNodeKey ; mNext = false ; lastPointer . remove ( mRTX ) ; }
Resetting the nodekey of this axis to a given nodekey .
43
14
23,298
public boolean moveTo ( final long pKey ) { try { if ( pKey < 0 || mRTX . moveTo ( pKey ) ) { lastPointer . put ( mRTX , pKey ) ; return true ; } else { return false ; } } catch ( TTIOException exc ) { throw new RuntimeException ( exc ) ; } }
Move cursor to a node by its node key .
75
10
23,299
public void close ( ) throws TTException { atomics . remove ( mRTX ) ; lastPointer . remove ( mRTX ) ; mRTX . close ( ) ; }
Closing the Transaction
39
4