idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
23,200
private boolean tryPath ( StringBuilder prefix , String el , boolean dir ) { String path = prefix + "/" + el ; if ( dir && directoryBrowsingDisallowed ) { path += "/" + xsltdirMarkerName ; } if ( debug ( ) ) { debug ( "trypath: " + path ) ; } try { URL u = new URL ( path ) ; URLConnection uc = u . openConnection ( ) ; if ( ! ( uc instanceof HttpURLConnection ) ) { return false ; } HttpURLConnection huc = ( HttpURLConnection ) uc ; if ( huc . getResponseCode ( ) != 200 ) { return false ; } prefix . append ( "/" ) ; prefix . append ( el ) ; return true ; } catch ( final Throwable t ) { if ( debug ( ) ) { debug ( "trypath exception: " ) ; error ( t ) ; } } return false ; }
Try a path and see if it exists . If so append the element
23,201
public static final DumbData [ ] [ ] createDatas ( final int [ ] pDatasPerRevision ) { final DumbData [ ] [ ] returnVal = new DumbData [ pDatasPerRevision . length ] [ ] ; for ( int i = 0 ; i < pDatasPerRevision . length ; i ++ ) { returnVal [ i ] = new DumbData [ pDatasPerRevision [ i ] ] ; for ( int j = 0 ; j < pDatasPerRevision [ i ] ; j ++ ) { returnVal [ i ] [ j ] = generateOne ( ) ; } } return returnVal ; }
Generating new data - elements passed on a given number of datas within a revision
23,202
public Void call ( ) throws TTException { emitStartDocument ( ) ; long [ ] versionsToUse ; if ( mVersions . length == 0 ) { if ( mSession . getMostRecentVersion ( ) > 0 ) { versionsToUse = new long [ ] { mSession . getMostRecentVersion ( ) } ; } else { versionsToUse = new long [ 0 ] ; } } else { Arrays . sort ( mVersions ) ; if ( mVersions [ 0 ] < 0 ) { versionsToUse = new long [ ( int ) mSession . getMostRecentVersion ( ) - 1 ] ; for ( int i = 0 ; i < versionsToUse . length ; i ++ ) { versionsToUse [ i ] = i + 1 ; } } else { int index = Arrays . binarySearch ( mVersions , 1 ) ; versionsToUse = Arrays . copyOfRange ( mVersions , index , mVersions . length ) ; } } for ( int i = 0 ; i < versionsToUse . length ; i ++ ) { INodeReadTrx rtx = new NodeReadTrx ( mSession . beginBucketRtx ( versionsToUse [ i ] ) ) ; if ( versionsToUse == null || mVersions . length > 1 ) { emitStartManualElement ( i ) ; } rtx . moveTo ( mNodeKey ) ; final AbsAxis descAxis = new DescendantAxis ( rtx , true ) ; boolean closeElements = false ; long key = rtx . getNode ( ) . getDataKey ( ) ; while ( descAxis . hasNext ( ) ) { key = descAxis . next ( ) ; ITreeStructData currentStruc = ( ITreeStructData ) rtx . getNode ( ) ; if ( closeElements ) { while ( ! mStack . empty ( ) && mStack . peek ( ) != currentStruc . getLeftSiblingKey ( ) ) { rtx . moveTo ( mStack . pop ( ) ) ; emitEndElement ( rtx ) ; rtx . moveTo ( key ) ; } if ( ! mStack . empty ( ) ) { rtx . moveTo ( mStack . pop ( ) ) ; emitEndElement ( rtx ) ; } rtx . moveTo ( key ) ; closeElements = false ; } emitStartElement ( rtx ) ; if ( currentStruc . getKind ( ) == IConstants . ELEMENT && currentStruc . hasFirstChild ( ) ) { mStack . push ( rtx . getNode ( ) . getDataKey ( ) ) ; } if ( ! currentStruc . hasFirstChild ( ) && ! currentStruc . hasRightSibling ( ) ) { closeElements = true ; } } while ( ! mStack . empty ( ) ) { rtx . moveTo ( mStack . pop ( ) ) ; emitEndElement ( rtx ) ; } if ( versionsToUse == null || mVersions . length > 1 ) { emitEndManualElement ( i ) ; } } emitEndDocument ( ) ; return null ; }
Serialize the storage .
23,203
public static Node getOneTaggedNode ( final Node el , final String name ) throws SAXException { if ( ! el . hasChildNodes ( ) ) { return null ; } final NodeList children = el . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { final Node n = children . item ( i ) ; if ( name . equals ( n . getNodeName ( ) ) ) { return n ; } } return null ; }
Get the single named element .
23,204
public static String getOneNodeVal ( final Node el , final String name ) throws SAXException { if ( ! el . hasChildNodes ( ) ) { return null ; } NodeList children = el . getChildNodes ( ) ; if ( children . getLength ( ) > 1 ) { throw new SAXException ( "Multiple property values: " + name ) ; } Node child = children . item ( 0 ) ; return child . getNodeValue ( ) ; }
Get the value of an element . We expect 0 or 1 child nodes . For no child node we return null for more than one we raise an exception .
23,205
public static String getReqOneNodeVal ( final Node el , final String name ) throws SAXException { String str = getOneNodeVal ( el , name ) ; if ( ( str == null ) || ( str . length ( ) == 0 ) ) { throw new SAXException ( "Missing property value: " + name ) ; } return str ; }
Get the value of an element . We expect 1 child node otherwise we raise an exception .
23,206
public static String getAttrVal ( final Element el , final String name ) throws SAXException { Attr at = el . getAttributeNode ( name ) ; if ( at == null ) { return null ; } return at . getValue ( ) ; }
Return the value of the named attribute of the given element .
23,207
public static String getReqAttrVal ( final Element el , final String name ) throws SAXException { String str = getAttrVal ( el , name ) ; if ( ( str == null ) || ( str . length ( ) == 0 ) ) { throw new SAXException ( "Missing attribute value: " + name ) ; } return str ; }
Return the required value of the named attribute of the given element .
23,208
public static String getAttrVal ( final NamedNodeMap nnm , final String name ) { Node nmAttr = nnm . getNamedItem ( name ) ; if ( ( nmAttr == null ) || ( absent ( nmAttr . getNodeValue ( ) ) ) ) { return null ; } return nmAttr . getNodeValue ( ) ; }
Return the attribute value of the named attribute from the given map .
23,209
public static Boolean getYesNoAttrVal ( final NamedNodeMap nnm , final String name ) throws SAXException { String val = getAttrVal ( nnm , name ) ; if ( val == null ) { return null ; } if ( ( ! "yes" . equals ( val ) ) && ( ! "no" . equals ( val ) ) ) { throw new SAXException ( "Invalid attribute value: " + val ) ; } return new Boolean ( "yes" . equals ( val ) ) ; }
The attribute value of the named attribute in the given map must be absent or yes or no .
23,210
public static List < Element > getElements ( final Node nd ) throws SAXException { final List < Element > al = new ArrayList < > ( ) ; NodeList children = nd . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node curnode = children . item ( i ) ; if ( curnode . getNodeType ( ) == Node . TEXT_NODE ) { String val = curnode . getNodeValue ( ) ; if ( val != null ) { for ( int vi = 0 ; vi < val . length ( ) ; vi ++ ) { if ( ! Character . isWhitespace ( val . charAt ( vi ) ) ) { throw new SAXException ( "Non-whitespace text in element body for " + nd . getLocalName ( ) + "\n text=" + val ) ; } } } } else if ( curnode . getNodeType ( ) == Node . COMMENT_NODE ) { } else if ( curnode . getNodeType ( ) == Node . ELEMENT_NODE ) { al . add ( ( Element ) curnode ) ; } else { throw new SAXException ( "Unexpected child node " + curnode . getLocalName ( ) + " for " + nd . getLocalName ( ) ) ; } } return al ; }
All the children must be elements or white space text nodes .
23,211
public static String getElementContent ( final Element el , final boolean trim ) throws SAXException { StringBuilder sb = new StringBuilder ( ) ; NodeList children = el . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node curnode = children . item ( i ) ; if ( curnode . getNodeType ( ) == Node . TEXT_NODE ) { sb . append ( curnode . getNodeValue ( ) ) ; } else if ( curnode . getNodeType ( ) == Node . CDATA_SECTION_NODE ) { sb . append ( curnode . getNodeValue ( ) ) ; } else if ( curnode . getNodeType ( ) == Node . COMMENT_NODE ) { } else { throw new SAXException ( "Unexpected child node " + curnode . getLocalName ( ) + " for " + el . getLocalName ( ) ) ; } } if ( ! trim ) { return sb . toString ( ) ; } return sb . toString ( ) . trim ( ) ; }
Return the content for the current element . All leading and trailing whitespace and embedded comments will be removed .
23,212
public static void setElementContent ( final Node n , final String s ) throws SAXException { NodeList children = n . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node curnode = children . item ( i ) ; n . removeChild ( curnode ) ; } Document d = n . getOwnerDocument ( ) ; final Node textNode = d . createTextNode ( s ) ; n . appendChild ( textNode ) ; }
Replace the content for the current element .
23,213
public static boolean hasContent ( final Element el ) throws SAXException { String s = getElementContent ( el ) ; return ( s != null ) && ( s . length ( ) > 0 ) ; }
Return true if the current element has non zero length content .
23,214
public static boolean hasChildren ( final Element el ) throws SAXException { NodeList children = el . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node curnode = children . item ( i ) ; short ntype = curnode . getNodeType ( ) ; if ( ( ntype != Node . TEXT_NODE ) && ( ntype != Node . CDATA_SECTION_NODE ) && ( ntype != Node . COMMENT_NODE ) ) { return true ; } } return false ; }
See if this node has any children
23,215
public static boolean nodeMatches ( final Node nd , final QName tag ) { if ( tag == null ) { return false ; } String ns = nd . getNamespaceURI ( ) ; if ( ns == null ) { if ( ( tag . getNamespaceURI ( ) != null ) && ( ! "" . equals ( tag . getNamespaceURI ( ) ) ) ) { return false ; } } else if ( ! ns . equals ( tag . getNamespaceURI ( ) ) ) { return false ; } String ln = nd . getLocalName ( ) ; if ( ln == null ) { if ( tag . getLocalPart ( ) != null ) { return false ; } } else if ( ! ln . equals ( tag . getLocalPart ( ) ) ) { return false ; } return true ; }
See if node matches tag
23,216
public static QName fromNode ( final Node nd ) { String ns = nd . getNamespaceURI ( ) ; if ( ns == null ) { ns = "" ; } return new QName ( ns , nd . getLocalName ( ) ) ; }
Return a QName for the node
23,217
public static SSLSocketFactory getSslSocketFactory ( ) { if ( ! sslDisabled ) { return SSLSocketFactory . getSocketFactory ( ) ; } try { final X509Certificate [ ] _AcceptedIssuers = new X509Certificate [ ] { } ; final SSLContext ctx = SSLContext . getInstance ( "TLS" ) ; final X509TrustManager tm = new X509TrustManager ( ) { public X509Certificate [ ] getAcceptedIssuers ( ) { return _AcceptedIssuers ; } public void checkServerTrusted ( final X509Certificate [ ] chain , final String authType ) throws CertificateException { } public void checkClientTrusted ( final X509Certificate [ ] chain , final String authType ) throws CertificateException { } } ; ctx . init ( null , new TrustManager [ ] { tm } , new SecureRandom ( ) ) ; return new SSLSocketFactory ( ctx , SSLSocketFactory . ALLOW_ALL_HOSTNAME_VERIFIER ) ; } catch ( final Throwable t ) { throw new RuntimeException ( t ) ; } }
Allow testing of features when we don t have any valid certs .
23,218
public void setCredentials ( final String user , final String pw ) { if ( user == null ) { credentials = null ; } else { credentials = new UsernamePasswordCredentials ( user , pw ) ; } }
Set the credentials . user == null for unauthenticated .
23,219
public int sendRequest ( final String methodName , final String url , final List < Header > hdrs , final String contentType , final int contentLen , final byte [ ] content ) throws HttpException { int sz = 0 ; if ( content != null ) { sz = content . length ; } if ( debug ( ) ) { debug ( "About to send request: method=" + methodName + " url=" + url + " contentLen=" + contentLen + " content.length=" + sz + " contentType=" + contentType ) ; } try { URI u = new URI ( url ) ; if ( ! hostSpecified && ( u . getHost ( ) == null ) ) { if ( ( baseURI == null ) && ( baseURIValue != null ) ) { baseURI = new URI ( baseURIValue ) ; } if ( baseURI == null ) { throw new HttpException ( "No base URI specified for non-absolute URI " + url ) ; } if ( baseURI . getHost ( ) == null ) { throw new HttpException ( "Base URI must be absolute: " + baseURI ) ; } u = baseURI . resolve ( u ) ; } if ( debug ( ) ) { debug ( " url resolves to " + u ) ; } method = findMethod ( methodName , u ) ; if ( credentials != null ) { getCredentialsProvider ( ) . setCredentials ( new AuthScope ( u . getHost ( ) , u . getPort ( ) ) , credentials ) ; } if ( ! Util . isEmpty ( hdrs ) ) { for ( final Header hdr : hdrs ) { method . addHeader ( hdr ) ; } } if ( method instanceof HttpEntityEnclosingRequestBase ) { if ( content != null ) { if ( contentType == null ) { setContent ( content , "text/xml" ) ; } else { setContent ( content , contentType ) ; } } } response = execute ( method ) ; } catch ( final HttpException he ) { throw he ; } catch ( final Throwable t ) { throw new HttpException ( t . getLocalizedMessage ( ) , t ) ; } status = response . getStatusLine ( ) . getStatusCode ( ) ; return status ; }
Send a request to the server
23,220
protected HttpRequestBase findMethod ( final String name , final URI uri ) throws HttpException { String nm = name . toUpperCase ( ) ; if ( "PUT" . equals ( nm ) ) { return new HttpPut ( uri ) ; } if ( "GET" . equals ( nm ) ) { return new HttpGet ( uri ) ; } if ( "DELETE" . equals ( nm ) ) { return new HttpDelete ( uri ) ; } if ( "POST" . equals ( nm ) ) { return new HttpPost ( uri ) ; } if ( "PROPFIND" . equals ( nm ) ) { return new HttpPropfind ( uri ) ; } if ( "MKCALENDAR" . equals ( nm ) ) { return new HttpMkcalendar ( uri ) ; } if ( "MKCOL" . equals ( nm ) ) { return new HttpMkcol ( uri ) ; } if ( "OPTIONS" . equals ( nm ) ) { return new HttpOptions ( uri ) ; } if ( "REPORT" . equals ( nm ) ) { return new HttpReport ( uri ) ; } if ( "HEAD" . equals ( nm ) ) { return new HttpHead ( uri ) ; } throw new HttpException ( "Illegal method: " + name ) ; }
Specify the next method by name .
23,221
public void release ( ) throws HttpException { try { HttpEntity ent = getResponseEntity ( ) ; if ( ent != null ) { InputStream is = ent . getContent ( ) ; is . close ( ) ; } } catch ( Throwable t ) { throw new HttpException ( t . getLocalizedMessage ( ) , t ) ; } }
Release the connection
23,222
public int addItem ( final AtomicValue pItem ) { final int key = mList . size ( ) ; pItem . setNodeKey ( key ) ; final int itemKey = ( key + 2 ) * ( - 1 ) ; pItem . setNodeKey ( itemKey ) ; mList . add ( pItem ) ; return itemKey ; }
Adding to this list .
23,223
static void release ( BufferPool . Buffer buff ) throws IOException { if ( buff . buf . length == staticConf . getSmallBufferSize ( ) ) { smallBufferPool . put ( buff ) ; } else if ( buff . buf . length == staticConf . getMediumBufferSize ( ) ) { mediumBufferPool . put ( buff ) ; } else if ( buff . buf . length == staticConf . getLargeBufferSize ( ) ) { largeBufferPool . put ( buff ) ; } }
Release a buffer back to the pool . MUST be called to gain the benefit of pooling .
23,224
private static NotificationsHandler getHandler ( final String queueName , final Properties pr ) throws NotificationException { if ( handler != null ) { return handler ; } synchronized ( synchit ) { handler = new JmsNotificationsHandlerImpl ( queueName , pr ) ; } return handler ; }
Return a handler for the system event
23,225
public static void post ( final SysEvent ev , final String queueName , final Properties pr ) throws NotificationException { getHandler ( queueName , pr ) . post ( ev ) ; }
Called to notify container that an event occurred . In general this should not be called directly as consumers may receive the messages immediately perhaps before the referenced data has been written .
23,226
public static < T > AdjustCollectionResult < T > adjustCollection ( final Collection < T > newCol , final Collection < T > toAdjust ) { final AdjustCollectionResult < T > acr = new AdjustCollectionResult < > ( ) ; acr . removed = new ArrayList < > ( ) ; acr . added = new ArrayList < > ( ) ; acr . added . addAll ( newCol ) ; if ( toAdjust != null ) { for ( final T ent : toAdjust ) { if ( newCol . contains ( ent ) ) { acr . added . remove ( ent ) ; continue ; } acr . removed . add ( ent ) ; } for ( final T ent : acr . added ) { toAdjust . add ( ent ) ; acr . numAdded ++ ; } for ( final T ent : acr . removed ) { if ( toAdjust . remove ( ent ) ) { acr . numRemoved ++ ; } } } return acr ; }
Used to adjust a collection toAdjust so that it looks like the collection newCol . The collection newCol will be unchanged but the result object will contain a list of added and removed values .
23,227
public static String pathElement ( final int index , final String path ) { final String [ ] paths = path . split ( "/" ) ; int idx = index ; if ( ( paths [ 0 ] == null ) || ( paths [ 0 ] . length ( ) == 0 ) ) { idx ++ ; } if ( idx >= paths . length ) { return null ; } return paths [ idx ] ; }
get the nth element from the path - first is 0 .
23,228
public static Locale makeLocale ( final String val ) throws Throwable { String lang = null ; String country = "" ; String variant = "" ; if ( val == null ) { throw new Exception ( "Bad Locale: NULL" ) ; } if ( val . length ( ) == 2 ) { lang = val ; } else { int pos = val . indexOf ( '_' ) ; if ( pos != 2 ) { throw new Exception ( "Bad Locale: " + val ) ; } lang = val . substring ( 0 , 2 ) ; pos = val . indexOf ( "_" , 3 ) ; if ( pos < 0 ) { if ( val . length ( ) != 5 ) { throw new Exception ( "Bad Locale: " + val ) ; } country = val . substring ( 3 ) ; } else { country = val . substring ( 3 , 5 ) ; if ( val . length ( ) > 6 ) { variant = val . substring ( 6 ) ; } } } return new Locale ( lang , country , variant ) ; }
make a locale from the standard underscore separated parts - no idea why this isn t in Locale
23,229
public static Properties getPropertiesFromResource ( final String name ) throws Throwable { Properties pr = new Properties ( ) ; InputStream is = null ; try { try { ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; is = cl . getResourceAsStream ( name ) ; } catch ( Throwable clt ) { } if ( is == null ) { is = Util . class . getResourceAsStream ( name ) ; } if ( is == null ) { throw new Exception ( "Unable to load properties file" + name ) ; } pr . load ( is ) ; return pr ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( Throwable t1 ) { } } } }
Load a named resource as a Properties object
23,230
public static Object getObject ( final String className , final Class cl ) throws Exception { try { Object o = Class . forName ( className ) . newInstance ( ) ; if ( o == null ) { throw new Exception ( "Class " + className + " not found" ) ; } if ( ! cl . isInstance ( o ) ) { throw new Exception ( "Class " + className + " is not a subclass of " + cl . getName ( ) ) ; } return o ; } catch ( Exception e ) { throw e ; } catch ( Throwable t ) { throw new Exception ( t ) ; } }
Given a class name return an object of that class . The class parameter is used to check that the named class is an instance of that class .
23,231
public static String fmtMsg ( final String fmt , final String arg1 , final String arg2 ) { Object [ ] o = new Object [ 2 ] ; o [ 0 ] = arg1 ; o [ 1 ] = arg2 ; return MessageFormat . format ( fmt , o ) ; }
Format a message consisting of a format string plus two string parameters
23,232
public static String fmtMsg ( final String fmt , final int arg ) { Object [ ] o = new Object [ 1 ] ; o [ 0 ] = new Integer ( arg ) ; return MessageFormat . format ( fmt , o ) ; }
Format a message consisting of a format string plus one integer parameter
23,233
public static String makeRandomString ( int length , int maxVal ) { if ( length < 0 ) { return null ; } length = Math . min ( length , 1025 ) ; if ( maxVal < 0 ) { return null ; } maxVal = Math . min ( maxVal , 35 ) ; StringBuffer res = new StringBuffer ( ) ; Random rand = new Random ( ) ; for ( int i = 0 ; i <= length ; i ++ ) { res . append ( randChars [ rand . nextInt ( maxVal + 1 ) ] ) ; } return res . toString ( ) ; }
Creates a string of given length where each character comes from a set of values 0 - 9 followed by A - Z .
23,234
public static String [ ] appendTextToArray ( String [ ] sarray , final String val , final int maxEntries ) { if ( sarray == null ) { if ( maxEntries > 0 ) { sarray = new String [ 1 ] ; sarray [ 0 ] = val ; } return sarray ; } if ( sarray . length > maxEntries ) { String [ ] neb = new String [ maxEntries ] ; System . arraycopy ( sarray , sarray . length - maxEntries , neb , 0 , maxEntries ) ; sarray = neb ; sarray [ sarray . length - 1 ] = val ; neb = null ; return sarray ; } if ( sarray . length < maxEntries ) { int newLen = sarray . length + 1 ; String [ ] neb = new String [ newLen ] ; System . arraycopy ( sarray , 0 , neb , 0 , sarray . length ) ; sarray = neb ; sarray [ sarray . length - 1 ] = val ; neb = null ; return sarray ; } if ( maxEntries > 1 ) { System . arraycopy ( sarray , 1 , sarray , 0 , sarray . length - 1 ) ; } sarray [ sarray . length - 1 ] = val ; return sarray ; }
Add a string to a string array of a given maximum length . Truncates the string array if required .
23,235
public static String encodeArray ( final String [ ] val ) { if ( val == null ) { return null ; } int len = val . length ; if ( len == 0 ) { return "" ; } StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( i > 0 ) { sb . append ( " " ) ; } String s = val [ i ] ; try { if ( s == null ) { sb . append ( "\t" ) ; } else { sb . append ( URLEncoder . encode ( s , "UTF-8" ) ) ; } } catch ( Throwable t ) { throw new RuntimeException ( t ) ; } } return sb . toString ( ) ; }
Return a String representing the given String array achieved by URLEncoding the individual String elements then concatenating with intervening blanks .
23,236
public static String [ ] decodeArray ( final String val ) { if ( val == null ) { return null ; } int len = val . length ( ) ; if ( len == 0 ) { return new String [ 0 ] ; } ArrayList < String > al = new ArrayList < String > ( ) ; int i = 0 ; while ( i < len ) { int end = val . indexOf ( " " , i ) ; String s ; if ( end < 0 ) { s = val . substring ( i ) ; i = len ; } else { s = val . substring ( i , end ) ; i = end + 1 ; } try { if ( s . equals ( "\t" ) ) { al . add ( null ) ; } else { al . add ( URLDecoder . decode ( s , "UTF-8" ) ) ; } } catch ( Throwable t ) { throw new RuntimeException ( t ) ; } } return al . toArray ( new String [ al . size ( ) ] ) ; }
Return a StringArray resulting from decoding the given String which should have been encoded by encodeArray
23,237
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
23,238
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 .
23,239
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 ) { throw new Exception ( "List has an empty element." ) ; } l . add ( "" ) ; } else { l . add ( token ) ; } } return l ; }
Turn a comma separated list into a List . Throws exception for invalid list .
23,240
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
23,241
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 .
23,242
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 .
23,243
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 .
23,244
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 .
23,245
private void releaseSessions ( ) throws TTException { if ( mSessions == null ) { return ; } try { for ( IFilelistenerWriteTrx trx : mTrx . values ( ) ) { trx . close ( ) ; } } catch ( IllegalStateException ise ) { ise . printStackTrace ( ) ; } for ( ISession s : mSessions . values ( ) ) { s . close ( ) ; } }
Release transactions and session from treetank .
23,246
public void shutDownListener ( ) throws TTException , IOException { for ( ExecutorService s : mExecutorMap . values ( ) ) { s . shutdown ( ) ; while ( ! s . isTerminated ( ) ) { 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 .
23,247
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 .
23,248
private void process ( Path dir , Path file , WatchEvent . Kind < ? > evtType ) throws TTException , IOException , InterruptedException { 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 { 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 ) ; } s . submit ( n ) ; } } }
This method is used to process the file system modifications .
23,249
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 .
23,250
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 .
23,251
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 .
23,252
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 .
23,253
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 .
23,254
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 .
23,255
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 .
23,256
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 .
23,257
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 .
23,258
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 .
23,259
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 ; } }
Get an integer valued request parameter .
23,260
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 .
23,261
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 ; } }
Get an long valued request parameter .
23,262
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 ; } }
Get a boolean valued request parameter .
23,263
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 .
23,264
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 .
23,265
public void removeSessionAttr ( final String attrName ) { final HttpSession sess = request . getSession ( false ) ; if ( sess == null ) { return ; } sess . removeAttribute ( attrName ) ; }
Remove a named session attribute .
23,266
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 .
23,267
@ 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
23,268
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
23,269
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 .
23,270
@ 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
23,271
private void doXPathRes ( final String resource , final Long revision , final OutputStream output , final boolean nodeid , final String xpath ) throws TTException { ISession session = null ; INodeReadTrx rtx = null ; try { if ( mDatabase . existsResource ( resource ) ) { session = mDatabase . getSession ( new SessionConfiguration ( resource , StandardSettings . KEY ) ) ; 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 .
23,272
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
23,273
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
23,274
private static Element createResultElement ( final Document document ) { return document . createElementNS ( JaxRxConstants . URL , JaxRxConstants . JAXRX + ":results" ) ; }
This method creates the response XML element .
23,275
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 .
23,276
public static StreamingOutput createStream ( final Document doc ) { return new StreamingOutput ( ) { 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 .
23,277
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 ) ; fstr . write ( '\n' ) ; fstr . flush ( ) ; } finally { if ( fstr != null ) { fstr . close ( ) ; } } }
Write a single string to a file . Used to write keys
23,278
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 .
23,279
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 .
23,280
public String getResource ( final int level ) { if ( level < resource . length ) { return resource [ level ] ; } throw new IndexOutOfBoundsException ( "Index: " + level + ", Size: " + resource . length ) ; }
Returns the resource at the specified level .
23,281
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
23,282
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
23,283
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 .
23,284
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 .
23,285
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 .
23,286
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
23,287
public static void rolloverLogfile ( ) { Logger logger = Logger . getRootLogger ( ) ; @ 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
23,288
public static synchronized boolean createStorage ( final StorageConfiguration pStorageConfig ) throws TTIOException { boolean returnVal = true ; if ( ! pStorageConfig . mFile . exists ( ) && pStorageConfig . mFile . mkdirs ( ) ) { returnVal = IOUtils . createFolderStructure ( pStorageConfig . mFile , StorageConfiguration . Paths . values ( ) ) ; StorageConfiguration . serialize ( pStorageConfig ) ; 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 .
23,289
public static synchronized void truncateStorage ( final StorageConfiguration pConf ) throws TTException { 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 ( ) ; IOUtils . recursiveDelete ( pConf . mFile ) ; } } }
Truncate a storage . This deletes all relevant data . All running sessions must be closed beforehand .
23,290
public static synchronized boolean existsStorage ( final File pStoragePath ) { 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 .
23,291
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 .
23,292
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 ) ; 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 ( ) ; 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 ) ; 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 .
23,293
public IXPathToken nextToken ( ) { mState = mStartState ; mStartState = State . START ; mOutput = new StringBuilder ( ) ; mFinnished = false ; mType = TokenType . INVALID ; mLastPos = mPos ; do { mInput = mQuery . charAt ( mPos ) ; switch ( mState ) { case START : scanStart ( ) ; break ; case NUMBER : scanNumber ( ) ; break ; case TEXT : scanText ( ) ; break ; case SPECIAL2 : 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 .
23,294
private void scanStart ( ) { if ( isNumber ( mInput ) ) { mState = State . NUMBER ; mOutput . append ( mInput ) ; mType = TokenType . VALUE ; } else if ( isFirstLetter ( mInput ) ) { mState = State . TEXT ; mOutput . append ( mInput ) ; mType = TokenType . TEXT ; } else if ( isSpecial ( mInput ) ) { mState = State . SPECIAL ; mOutput . append ( mInput ) ; mType = retrieveType ( mInput ) ; mFinnished = true ; } else if ( isTwoDigistSpecial ( mInput ) ) { mState = State . SPECIAL2 ; mOutput . append ( mInput ) ; mType = retrieveType ( mInput ) ; } else if ( ( mInput == ' ' ) || ( mInput == '\n' ) ) { mState = State . START ; mOutput . append ( mInput ) ; mFinnished = true ; mType = TokenType . SPACE ; } else if ( mInput == '#' ) { mType = TokenType . END ; mFinnished = true ; mPos -- ; } else { mState = State . UNKNOWN ; mOutput . append ( mInput ) ; mFinnished = true ; } mPos ++ ; }
Scans the first character of a token and decides what type it is .
23,295
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 .
23,296
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 .
23,297
private void scanNumber ( ) { if ( mInput >= '0' && mInput <= '9' ) { mOutput . append ( mInput ) ; mPos ++ ; } else { if ( mInput == 'E' || mInput == 'e' ) { mStartState = State . E_NUM ; } mFinnished = true ; } }
Scans a number token . A number only consists of digits .
23,298
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 .
23,299
private void scanENum ( ) { if ( mInput == 'E' || mInput == 'e' ) { 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 .