idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
23,400 | public static StringBuilder concat ( final String ... message ) { final StringBuilder builder = new StringBuilder ( ) ; for ( final String mess : message ) { builder . append ( mess ) ; builder . append ( " " ) ; } return builder ; } | Util method to provide StringBuilder functionality . |
23,401 | public IMetaEntry put ( final IMetaEntry pKey , final IMetaEntry pVal ) { return mMetaMap . put ( pKey , pVal ) ; } | Putting an entry to the map . |
23,402 | public Void call ( ) throws TTException { updateOnly ( ) ; if ( mCommit == EShredderCommit . COMMIT ) { mWtx . commit ( ) ; } return null ; } | Invoking the shredder . |
23,403 | private void updateOnly ( ) throws TTException { try { mLevelInToShredder = 0 ; mMovedToRightSibling = false ; boolean firstEvent = true ; if ( mWtx . getNode ( ) . getKind ( ) == IConstants . ROOT ) { long startkey = ROOT_NODE + 1 ; while ( ! mWtx . moveTo ( startkey ) ) { startkey ++ ; } } XMLEvent event = null ; StringBuilder sBuilder = new StringBuilder ( ) ; final XMLEventFactory fac = XMLEventFactory . newInstance ( ) ; while ( mReader . hasNext ( ) ) { if ( mDelete == EDelete . ATSTARTMIDDLE ) { mDelete = EDelete . NODELETE ; } else { event = mReader . nextEvent ( ) ; if ( event . isCharacters ( ) && event . asCharacters ( ) . isWhiteSpace ( ) ) { continue ; } assert event != null ; if ( firstEvent ) { firstEvent = false ; if ( event . getEventType ( ) == XMLStreamConstants . START_DOCUMENT ) { while ( mReader . hasNext ( ) && event . getEventType ( ) != XMLStreamConstants . START_ELEMENT ) { event = mReader . nextEvent ( ) ; } assert event . getEventType ( ) == XMLStreamConstants . START_ELEMENT ; } checkState ( event . getEventType ( ) == XMLStreamConstants . START_ELEMENT , "StAX parser has to be on START_DOCUMENT or START_ELEMENT event!" ) ; mRootElem = event . asStartElement ( ) . getName ( ) ; } else if ( event != null && event . isEndElement ( ) && mRootElem . equals ( event . asEndElement ( ) . getName ( ) ) && mLevelInToShredder == 1 ) { break ; } } assert event != null ; switch ( event . getEventType ( ) ) { case XMLStreamConstants . START_ELEMENT : processStartTag ( event . asStartElement ( ) ) ; break ; case XMLStreamConstants . CHARACTERS : sBuilder . append ( event . asCharacters ( ) . getData ( ) ) ; while ( mReader . peek ( ) . getEventType ( ) == XMLStreamConstants . CHARACTERS ) { sBuilder . append ( mReader . nextEvent ( ) . asCharacters ( ) . getData ( ) ) ; } final Characters text = fac . createCharacters ( sBuilder . toString ( ) . trim ( ) ) ; processCharacters ( text ) ; sBuilder = new StringBuilder ( ) ; break ; case XMLStreamConstants . END_ELEMENT : processEndTag ( ) ; break ; default : } mReader . close ( ) ; } } catch ( final XMLStreamException e ) { throw new TTIOException ( e ) ; } catch ( final IOException e ) { throw new TTIOException ( e ) ; } } | Update a shreddered file . |
23,404 | private void processStartTag ( final StartElement paramElem ) throws IOException , XMLStreamException , TTException { assert paramElem != null ; initializeVars ( ) ; algorithm ( paramElem ) ; if ( mFound && mIsRightSibling ) { mDelete = EDelete . ATSTARTMIDDLE ; deleteNode ( ) ; } else if ( ! mFound ) { mLevelInToShredder ++ ; insertElementNode ( paramElem ) ; } else if ( mFound ) { mLevelInToShredder ++ ; sameElementNode ( ) ; } } | Process start tag . |
23,405 | private void processCharacters ( final Characters paramText ) throws IOException , XMLStreamException , TTException { assert paramText != null ; initializeVars ( ) ; final String text = paramText . getData ( ) . toString ( ) ; if ( ! text . isEmpty ( ) ) { algorithm ( paramText ) ; if ( mFound && mIsRightSibling ) { throw new AssertionError ( "" ) ; } else if ( ! mFound ) { insertTextNode ( paramText ) ; } else if ( mFound ) { sameTextNode ( ) ; } } } | Process characters . |
23,406 | private void processEndTag ( ) throws XMLStreamException , TTException { mLevelInToShredder -- ; if ( mInserted ) { mInsertedEndTag = true ; } if ( mRemovedNode ) { mRemovedNode = false ; } else { if ( mWtx . getNode ( ) . getDataKey ( ) == mLastNodeKey ) { assert mWtx . getNode ( ) . hasParent ( ) && mWtx . getNode ( ) . getKind ( ) == IConstants . ELEMENT ; mWtx . moveTo ( mWtx . getNode ( ) . getParentKey ( ) ) ; } else { if ( mWtx . getNode ( ) . getKind ( ) == IConstants . ELEMENT ) { final ElementNode element = ( ElementNode ) mWtx . getNode ( ) ; if ( element . hasFirstChild ( ) && element . hasParent ( ) ) { mWtx . moveTo ( mWtx . getNode ( ) . getParentKey ( ) ) ; } } else if ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . hasParent ( ) ) { if ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . hasRightSibling ( ) ) { mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getRightSiblingKey ( ) ) ; mKeyMatches = - 1 ; mDelete = EDelete . ATBOTTOM ; deleteNode ( ) ; } mWtx . moveTo ( mWtx . getNode ( ) . getParentKey ( ) ) ; } } mLastNodeKey = mWtx . getNode ( ) . getDataKey ( ) ; if ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . hasRightSibling ( ) ) { mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getRightSiblingKey ( ) ) ; mMovedToRightSibling = true ; skipWhitespaces ( mReader ) ; if ( mReader . peek ( ) . getEventType ( ) == XMLStreamConstants . END_ELEMENT ) { mKeyMatches = - 1 ; mDelete = EDelete . ATBOTTOM ; deleteNode ( ) ; } } else { mMovedToRightSibling = false ; } } } | Process end tag . |
23,407 | private void algorithm ( final XMLEvent paramEvent ) throws IOException , XMLStreamException , TTIOException { assert paramEvent != null ; do { if ( paramEvent . isStartElement ( ) ) { mFound = checkElement ( paramEvent . asStartElement ( ) ) ; } else if ( paramEvent . isCharacters ( ) ) { mFound = checkText ( paramEvent . asCharacters ( ) ) ; } if ( mWtx . getNode ( ) . getDataKey ( ) != mNodeKey ) { mIsRightSibling = true ; } mKeyMatches = mWtx . getNode ( ) . getDataKey ( ) ; } while ( ! mFound && mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getRightSiblingKey ( ) ) ) ; mWtx . moveTo ( mNodeKey ) ; } | Main algorithm to determine if nodes are equal have to be inserted or have to be removed . |
23,408 | private boolean checkText ( final Characters paramEvent ) { assert paramEvent != null ; final String text = paramEvent . getData ( ) . trim ( ) ; return mWtx . getNode ( ) . getKind ( ) == IConstants . TEXT && mWtx . getValueOfCurrentNode ( ) . equals ( text ) ; } | Check if text event and text in Treetank storage match . |
23,409 | private void sameTextNode ( ) throws TTIOException , XMLStreamException { mInsert = EInsert . NOINSERT ; mDelete = EDelete . NODELETE ; mInserted = false ; mInsertedEndTag = false ; mRemovedNode = false ; skipWhitespaces ( mReader ) ; if ( mReader . peek ( ) . getEventType ( ) != XMLStreamConstants . END_ELEMENT ) { if ( mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getRightSiblingKey ( ) ) ) { mMovedToRightSibling = true ; } else { mMovedToRightSibling = false ; } } mInsert = EInsert . ATMIDDLEBOTTOM ; } | In case they are the same nodes move cursor to next node and update stack . |
23,410 | private void sameElementNode ( ) throws XMLStreamException , TTException { mInsert = EInsert . NOINSERT ; mDelete = EDelete . NODELETE ; mInserted = false ; mInsertedEndTag = false ; mRemovedNode = false ; skipWhitespaces ( mReader ) ; final ElementNode element = ( ElementNode ) mWtx . getNode ( ) ; if ( element . hasFirstChild ( ) ) { mInsert = EInsert . ATTOP ; mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getFirstChildKey ( ) ) ; if ( mReader . peek ( ) . getEventType ( ) == XMLStreamConstants . END_ELEMENT ) { mKeyMatches = - 1 ; mDelete = EDelete . ATBOTTOM ; deleteNode ( ) ; } } else if ( mReader . peek ( ) . getEventType ( ) != XMLStreamConstants . END_ELEMENT ) { mInsert = EInsert . ATTOP ; mEmptyElement = true ; } else { mInsert = EInsert . ATMIDDLEBOTTOM ; } } | Nodes match thus update stack and move cursor to first child if it is not a leaf node . |
23,411 | private void skipWhitespaces ( final XMLEventReader paramReader ) throws XMLStreamException { while ( paramReader . peek ( ) . getEventType ( ) == XMLStreamConstants . CHARACTERS && paramReader . peek ( ) . asCharacters ( ) . isWhiteSpace ( ) ) { paramReader . nextEvent ( ) ; } } | Skip any whitespace event . |
23,412 | private void insertElementNode ( final StartElement paramElement ) throws TTException , XMLStreamException { assert paramElement != null ; mDelete = EDelete . NODELETE ; mRemovedNode = false ; switch ( mInsert ) { case ATTOP : if ( ! mEmptyElement ) { mWtx . moveTo ( mWtx . getNode ( ) . getParentKey ( ) ) ; } addNewElement ( EAdd . ASFIRSTCHILD , paramElement ) ; mInsert = EInsert . INTERMEDIATE ; break ; case INTERMEDIATE : EAdd insertNode = EAdd . ASFIRSTCHILD ; if ( mInsertedEndTag ) { mInsertedEndTag = false ; insertNode = EAdd . ASRIGHTSIBLING ; } if ( mMovedToRightSibling ) { mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getLeftSiblingKey ( ) ) ; } if ( mWtx . getNode ( ) . getKind ( ) == IConstants . TEXT ) { insertNode = EAdd . ASRIGHTSIBLING ; } addNewElement ( insertNode , paramElement ) ; break ; case ATMIDDLEBOTTOM : if ( mMovedToRightSibling ) { mMovedToRightSibling = false ; mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getLeftSiblingKey ( ) ) ; } addNewElement ( EAdd . ASRIGHTSIBLING , paramElement ) ; mInsert = EInsert . INTERMEDIATE ; break ; default : throw new AssertionError ( "Enum value not known!" ) ; } mInserted = true ; } | Insert an element node . |
23,413 | private void insertTextNode ( final Characters paramText ) throws TTException , XMLStreamException { assert paramText != null ; mDelete = EDelete . NODELETE ; mRemovedNode = false ; switch ( mInsert ) { case ATTOP : mWtx . moveTo ( mWtx . getNode ( ) . getParentKey ( ) ) ; addNewText ( EAdd . ASFIRSTCHILD , paramText ) ; if ( mReader . peek ( ) . getEventType ( ) != XMLStreamConstants . END_ELEMENT ) { if ( mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getRightSiblingKey ( ) ) ) { mMovedToRightSibling = true ; } else { mMovedToRightSibling = false ; } } else if ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . hasRightSibling ( ) ) { mMovedToRightSibling = false ; mInserted = true ; mKeyMatches = - 1 ; mDelete = EDelete . ATBOTTOM ; deleteNode ( ) ; } mInsert = EInsert . INTERMEDIATE ; break ; case INTERMEDIATE : EAdd addNode = EAdd . ASFIRSTCHILD ; if ( mInsertedEndTag ) { if ( mMovedToRightSibling ) { mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getLeftSiblingKey ( ) ) ; } addNode = EAdd . ASRIGHTSIBLING ; mInsertedEndTag = false ; } addNewText ( addNode , paramText ) ; if ( mReader . peek ( ) . getEventType ( ) != XMLStreamConstants . END_ELEMENT ) { if ( mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getRightSiblingKey ( ) ) ) { mMovedToRightSibling = true ; } else { mMovedToRightSibling = false ; } } break ; case ATMIDDLEBOTTOM : if ( mMovedToRightSibling ) { mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getLeftSiblingKey ( ) ) ; } addNewText ( EAdd . ASRIGHTSIBLING , paramText ) ; mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getRightSiblingKey ( ) ) ; mInsert = EInsert . INTERMEDIATE ; break ; default : throw new AssertionError ( "Enum value not known!" ) ; } mInserted = true ; } | Insert a text node . |
23,414 | private void deleteNode ( ) throws TTException { if ( mInserted && ! mMovedToRightSibling ) { mInserted = false ; if ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . hasRightSibling ( ) ) { mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getRightSiblingKey ( ) ) ; } } boolean movedToParent = false ; boolean isLast = false ; do { if ( mWtx . getNode ( ) . getDataKey ( ) != mKeyMatches ) { final ITreeStructData node = ( ITreeStructData ) mWtx . getNode ( ) ; if ( ! node . hasRightSibling ( ) && ! node . hasLeftSibling ( ) ) { movedToParent = true ; } else if ( ! node . hasRightSibling ( ) ) { isLast = true ; } mWtx . remove ( ) ; } } while ( mWtx . getNode ( ) . getDataKey ( ) != mKeyMatches && ! movedToParent && ! isLast ) ; if ( movedToParent ) { if ( mDelete == EDelete . ATBOTTOM ) { mRemovedNode = true ; } mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getRightSiblingKey ( ) ) ; } else { if ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . hasFirstChild ( ) ) { if ( mDelete == EDelete . ATBOTTOM && isLast ) { mRemovedNode = true ; } if ( isLast ) { mWtx . moveTo ( mWtx . getNode ( ) . getParentKey ( ) ) ; mWtx . moveTo ( ( ( ITreeStructData ) mWtx . getNode ( ) ) . getRightSiblingKey ( ) ) ; } } } mInsert = EInsert . NOINSERT ; } | Delete node . |
23,415 | private void initializeVars ( ) { mNodeKey = mWtx . getNode ( ) . getDataKey ( ) ; mFound = false ; mIsRightSibling = false ; mKeyMatches = - 1 ; } | Initialize variables needed for the main algorithm . |
23,416 | private boolean checkElement ( final StartElement mEvent ) throws TTIOException { assert mEvent != null ; boolean retVal = false ; if ( mWtx . getNode ( ) . getKind ( ) == IConstants . ELEMENT && mWtx . getQNameOfCurrentNode ( ) . equals ( mEvent . getName ( ) ) ) { final long nodeKey = mWtx . getNode ( ) . getDataKey ( ) ; boolean foundAtts = false ; boolean hasAtts = false ; for ( final Iterator < ? > it = mEvent . getAttributes ( ) ; it . hasNext ( ) ; ) { hasAtts = true ; final Attribute attribute = ( Attribute ) it . next ( ) ; for ( int i = 0 , attCount = ( ( ElementNode ) mWtx . getNode ( ) ) . getAttributeCount ( ) ; i < attCount ; i ++ ) { mWtx . moveToAttribute ( i ) ; if ( attribute . getName ( ) . equals ( mWtx . getQNameOfCurrentNode ( ) ) && attribute . getValue ( ) . equals ( mWtx . getValueOfCurrentNode ( ) ) ) { foundAtts = true ; mWtx . moveTo ( nodeKey ) ; break ; } mWtx . moveTo ( nodeKey ) ; } if ( ! foundAtts ) { break ; } } if ( ! hasAtts && ( ( ElementNode ) mWtx . getNode ( ) ) . getAttributeCount ( ) == 0 ) { foundAtts = true ; } boolean foundNamesps = false ; boolean hasNamesps = false ; for ( final Iterator < ? > namespIt = mEvent . getNamespaces ( ) ; namespIt . hasNext ( ) ; ) { hasNamesps = true ; final Namespace namespace = ( Namespace ) namespIt . next ( ) ; for ( int i = 0 , namespCount = ( ( ElementNode ) mWtx . getNode ( ) ) . getNamespaceCount ( ) ; i < namespCount ; i ++ ) { mWtx . moveToNamespace ( i ) ; final ITreeNameData namenode = ( ITreeNameData ) mWtx . getNode ( ) ; if ( namespace . getNamespaceURI ( ) . equals ( mWtx . nameForKey ( namenode . getURIKey ( ) ) ) && namespace . getPrefix ( ) . equals ( mWtx . nameForKey ( namenode . getNameKey ( ) ) ) ) { foundNamesps = true ; mWtx . moveTo ( nodeKey ) ; break ; } mWtx . moveTo ( nodeKey ) ; } if ( ! foundNamesps ) { break ; } } if ( ! hasNamesps && ( ( ElementNode ) mWtx . getNode ( ) ) . getNamespaceCount ( ) == 0 ) { foundNamesps = true ; } if ( foundAtts && foundNamesps ) { retVal = true ; } else { retVal = false ; } } return retVal ; } | Check if current element matches the element in the shreddered file . |
23,417 | @ SuppressWarnings ( { "unchecked" } ) public synchronized Enumeration < Object > keys ( ) { Enumeration < Object > keysEnum = super . keys ( ) ; @ SuppressWarnings ( "rawtypes" ) Vector keyList = new Vector < > ( ) ; while ( keysEnum . hasMoreElements ( ) ) { keyList . add ( keysEnum . nextElement ( ) ) ; } Collections . sort ( keyList ) ; Collections . reverse ( keyList ) ; return keyList . elements ( ) ; } | Overrides called by the store method . |
23,418 | public void setException ( Throwable t ) { if ( err == null ) { t . printStackTrace ( ) ; } else { err . emit ( t ) ; } } | Can be called by a page to signal an exceptiuon |
23,419 | public boolean processErrors ( MessageEmit err ) { if ( valErrors . size ( ) == 0 ) { return false ; } for ( ValError ve : valErrors ) { processError ( err , ve ) ; } valErrors . clear ( ) ; return true ; } | processErrors is called to determine if there were any errors . If so processError is called for each error adn the errors vector is cleared . Override the processError method to emit custom messages . |
23,420 | public static boolean createResource ( String name , AbstractModule module ) throws StorageAlreadyExistsException , TTException { File file = new File ( ROOT_PATH ) ; File storageFile = new File ( STORAGE_PATH ) ; if ( ! file . exists ( ) || ! storageFile . exists ( ) ) { file . mkdirs ( ) ; StorageConfiguration configuration = new StorageConfiguration ( storageFile ) ; Storage . truncateStorage ( configuration ) ; Storage . createStorage ( configuration ) ; } IStorage storage = Storage . openStorage ( storageFile ) ; Injector injector = Guice . createInjector ( module ) ; IBackendFactory backend = injector . getInstance ( IBackendFactory . class ) ; IRevisioning revision = injector . getInstance ( IRevisioning . class ) ; Properties props = StandardSettings . getProps ( storageFile . getAbsolutePath ( ) , name ) ; ResourceConfiguration mResourceConfig = new ResourceConfiguration ( props , backend , revision , new FileDataFactory ( ) , new FilelistenerMetaDataFactory ( ) ) ; storage . createResource ( mResourceConfig ) ; return true ; } | Create a new storage with the given name and backend . |
23,421 | public static List < String > getResources ( ) { File resources = new File ( STORAGE_PATH + File . separator + "/resources" ) ; File [ ] children = resources . listFiles ( ) ; if ( children == null ) { return new ArrayList < String > ( ) ; } List < String > storages = new ArrayList < String > ( ) ; for ( int i = 0 ; i < children . length ; i ++ ) { if ( children [ i ] . isDirectory ( ) ) storages . add ( children [ i ] . getName ( ) ) ; } return storages ; } | Retrieve a list of all storages . |
23,422 | public static ISession getSession ( String resourceName ) throws ResourceNotExistingException , TTException { File storageFile = new File ( STORAGE_PATH ) ; ISession session = null ; if ( ! storageFile . exists ( ) ) { throw new ResourceNotExistingException ( ) ; } else { new StorageConfiguration ( storageFile ) ; IStorage storage = Storage . openStorage ( storageFile ) ; session = storage . getSession ( new SessionConfiguration ( resourceName , null ) ) ; } return session ; } | Retrieve a session from the system for the given Storagename |
23,423 | public static void removeResource ( String pResourceName ) throws TTException , ResourceNotExistingException { ISession session = getSession ( pResourceName ) ; session . truncate ( ) ; } | Via this method you can remove a storage from the system . |
23,424 | private void generateElement ( final INodeReadTrx paramRtx ) throws TTIOException { final AttributesImpl atts = new AttributesImpl ( ) ; final long key = paramRtx . getNode ( ) . getDataKey ( ) ; try { for ( int i = 0 , namesCount = ( ( ElementNode ) paramRtx . getNode ( ) ) . getNamespaceCount ( ) ; i < namesCount ; i ++ ) { paramRtx . moveToNamespace ( i ) ; final QName qName = paramRtx . getQNameOfCurrentNode ( ) ; mContHandler . startPrefixMapping ( qName . getPrefix ( ) , qName . getNamespaceURI ( ) ) ; final String mURI = qName . getNamespaceURI ( ) ; if ( qName . getLocalPart ( ) . length ( ) == 0 ) { atts . addAttribute ( mURI , "xmlns" , "xmlns" , "CDATA" , mURI ) ; } else { atts . addAttribute ( mURI , "xmlns" , "xmlns:" + paramRtx . getQNameOfCurrentNode ( ) . getLocalPart ( ) , "CDATA" , mURI ) ; } paramRtx . moveTo ( key ) ; } for ( int i = 0 , attCount = ( ( ElementNode ) paramRtx . getNode ( ) ) . getAttributeCount ( ) ; i < attCount ; i ++ ) { paramRtx . moveToAttribute ( i ) ; final QName qName = paramRtx . getQNameOfCurrentNode ( ) ; final String mURI = qName . getNamespaceURI ( ) ; atts . addAttribute ( mURI , qName . getLocalPart ( ) , NodeWriteTrx . buildName ( qName ) , paramRtx . getTypeOfCurrentNode ( ) , paramRtx . getValueOfCurrentNode ( ) ) ; paramRtx . moveTo ( key ) ; } final QName qName = paramRtx . getQNameOfCurrentNode ( ) ; mContHandler . startElement ( qName . getNamespaceURI ( ) , qName . getLocalPart ( ) , NodeWriteTrx . buildName ( qName ) , atts ) ; if ( ! ( ( ElementNode ) paramRtx . getNode ( ) ) . hasFirstChild ( ) ) { mContHandler . endElement ( qName . getNamespaceURI ( ) , qName . getLocalPart ( ) , NodeWriteTrx . buildName ( qName ) ) ; } } catch ( final SAXException exc ) { exc . printStackTrace ( ) ; } } | Generate a start element event . |
23,425 | private void generateText ( final INodeReadTrx paramRtx ) { try { mContHandler . characters ( paramRtx . getValueOfCurrentNode ( ) . toCharArray ( ) , 0 , paramRtx . getValueOfCurrentNode ( ) . length ( ) ) ; } catch ( final SAXException exc ) { exc . printStackTrace ( ) ; } } | Generate a text event . |
23,426 | @ SuppressWarnings ( "unchecked" ) public static Object getMBean ( final Class c , final String name ) throws Throwable { final MBeanServer server = getMbeanServer ( ) ; return JMX . newMBeanProxy ( server , new ObjectName ( name ) , c ) ; } | Create a proxy to the given mbean |
23,427 | public static void register ( final Server s ) { final ServletHolder sh = new ServletHolder ( ServletContainer . class ) ; sh . setInitParameter ( "com.sun.jersey.config.property.resourceConfigClass" , "com.sun.jersey.api.core.PackagesResourceConfig" ) ; sh . setInitParameter ( "com.sun.jersey.config.property.packages" , "org.jaxrx.resource" ) ; new Context ( s , "/" , Context . SESSIONS ) . addServlet ( sh , "/" ) ; } | Constructor attaching JAX - RX to the specified server . |
23,428 | public IData getData ( final long pDataKey ) throws TTIOException { checkArgument ( pDataKey >= 0 ) ; checkState ( ! mClose , "Transaction already closed" ) ; final long seqBucketKey = pDataKey >> IConstants . INDIRECT_BUCKET_COUNT [ 3 ] ; final int dataBucketOffset = dataBucketOffset ( pDataKey ) ; DataBucket bucket = mCache . getIfPresent ( seqBucketKey ) ; if ( bucket == null ) { final List < DataBucket > listRevs = getSnapshotBuckets ( seqBucketKey ) ; final DataBucket [ ] revs = listRevs . toArray ( new DataBucket [ listRevs . size ( ) ] ) ; checkState ( revs . length > 0 , "Number of Buckets to reconstruct must be larger than 0" ) ; final IRevisioning revision = mSession . getConfig ( ) . mRevision ; bucket = revision . combineBuckets ( revs ) ; mCache . put ( seqBucketKey , bucket ) ; } final IData returnVal = bucket . getData ( dataBucketOffset ) ; if ( pDataKey == 0 ) { return returnVal ; } else { return checkItemIfDeleted ( returnVal ) ; } } | Getting the data related to the given data key . |
23,429 | public boolean close ( ) throws TTIOException { if ( ! mClose ) { mSession . deregisterBucketTrx ( this ) ; mBucketReader . close ( ) ; mClose = true ; return true ; } else { return false ; } } | Closing this Readtransaction . |
23,430 | protected final List < DataBucket > getSnapshotBuckets ( final long pSeqDataBucketKey ) throws TTIOException { final List < DataBucket > dataBuckets = new ArrayList < DataBucket > ( ) ; final long [ ] pathToRoot = BucketReadTrx . dereferenceLeafOfTree ( mBucketReader , mUberBucket . getReferenceKeys ( ) [ IReferenceBucket . GUARANTEED_INDIRECT_OFFSET ] , mRootBucket . getRevision ( ) ) ; final RevisionRootBucket rootBucket = ( RevisionRootBucket ) mBucketReader . read ( pathToRoot [ IConstants . INDIRECT_BUCKET_COUNT . length ] ) ; final int numbersToRestore = Integer . parseInt ( mSession . getConfig ( ) . mProperties . getProperty ( ConstructorProps . NUMBERTORESTORE ) ) ; final long [ ] pathToRecentBucket = dereferenceLeafOfTree ( mBucketReader , rootBucket . getReferenceKeys ( ) [ IReferenceBucket . GUARANTEED_INDIRECT_OFFSET ] , pSeqDataBucketKey ) ; DataBucket bucket ; long bucketKey = pathToRecentBucket [ IConstants . INDIRECT_BUCKET_COUNT . length ] ; while ( dataBuckets . size ( ) < numbersToRestore && bucketKey > - 1 ) { bucket = ( DataBucket ) mBucketReader . read ( bucketKey ) ; dataBuckets . add ( bucket ) ; bucketKey = bucket . getLastBucketPointer ( ) ; } if ( bucketKey > - 1 ) { checkStructure ( mBucketReader , pathToRecentBucket , rootBucket , pSeqDataBucketKey ) ; checkStructure ( mBucketReader , pathToRoot , mUberBucket , mRootBucket . getRevision ( ) ) ; } return dataBuckets ; } | Dereference data bucket reference . |
23,431 | protected static final int dataBucketOffset ( final long pDataKey ) { final long dataBucketOffset = ( pDataKey - ( ( pDataKey >> IConstants . INDIRECT_BUCKET_COUNT [ 3 ] ) << IConstants . INDIRECT_BUCKET_COUNT [ 3 ] ) ) ; return ( int ) dataBucketOffset ; } | Calculate data bucket offset for a given data key . |
23,432 | protected static final long [ ] dereferenceLeafOfTree ( final IBackendReader pReader , final long pStartKey , final long pSeqBucketKey ) throws TTIOException { final long [ ] orderNumber = getOrderNumbers ( pSeqBucketKey ) ; final long [ ] keys = new long [ IConstants . INDIRECT_BUCKET_COUNT . length + 1 ] ; IndirectBucket bucket = null ; keys [ 0 ] = pStartKey ; for ( int level = 0 ; level < orderNumber . length ; level ++ ) { bucket = ( IndirectBucket ) pReader . read ( keys [ level ] ) ; keys [ level + 1 ] = bucket . getReferenceKeys ( ) [ dataBucketOffset ( orderNumber [ level ] ) ] ; if ( keys [ level + 1 ] == 0 ) { Arrays . fill ( keys , - 1 ) ; return keys ; } } return keys ; } | Find reference pointing to leaf bucket of an indirect tree . |
23,433 | public static OptionsI getOptions ( final String globalPrefix , final String appPrefix , final String optionsFile , final String outerTagName ) throws OptionsException { try { Object o = Class . forName ( envclass ) . newInstance ( ) ; if ( o == null ) { throw new OptionsException ( "Class " + envclass + " not found" ) ; } if ( ! ( o instanceof OptionsI ) ) { throw new OptionsException ( "Class " + envclass + " is not a subclass of " + OptionsI . class . getName ( ) ) ; } OptionsI options = ( OptionsI ) o ; options . init ( globalPrefix , appPrefix , optionsFile , outerTagName ) ; return options ; } catch ( OptionsException ce ) { throw ce ; } catch ( Throwable t ) { throw new OptionsException ( t ) ; } } | Obtain and initialise an options object . |
23,434 | public static Options fromStream ( final String globalPrefix , final String appPrefix , final String outerTagName , final InputStream is ) throws OptionsException { Options opts = new Options ( ) ; opts . init ( globalPrefix , appPrefix , is , outerTagName ) ; return opts ; } | Return an object that uses a local set of options parsed from the input stream . |
23,435 | private void addLeafLabel ( ) { final int nodeKind = mRtx . getNode ( ) . getKind ( ) ; if ( ! mLeafLabels . containsKey ( nodeKind ) ) { mLeafLabels . put ( nodeKind , new ArrayList < ITreeData > ( ) ) ; } mLeafLabels . get ( nodeKind ) . add ( mRtx . getNode ( ) ) ; } | Add leaf node label . |
23,436 | public FilterGlobals getGlobals ( final HttpServletRequest req ) { HttpSession sess = req . getSession ( ) ; if ( sess == null ) { return null ; } Object o = sess . getAttribute ( globalsName ) ; FilterGlobals fg ; if ( o == null ) { fg = newFilterGlobals ( ) ; sess . setAttribute ( globalsName , fg ) ; if ( debug ( ) ) { debug ( "Created new FilterGlobals from session " + sess . getId ( ) ) ; } } else { fg = ( FilterGlobals ) o ; } return fg ; } | Get the globals from the session |
23,437 | @ Consumes ( { MediaType . TEXT_XML , MediaType . APPLICATION_XML } ) public Response putResource ( @ PathParam ( JaxRxConstants . SYSTEM ) final String system , @ PathParam ( JaxRxConstants . RESOURCE ) final String resource , final HttpHeaders headers , final InputStream xml ) { final JaxRx impl = Systems . getInstance ( system ) ; final String info = impl . update ( xml , new ResourcePath ( resource , headers ) ) ; return Response . created ( null ) . entity ( info ) . build ( ) ; } | This method will be called when a new XML file has to be stored within the database . The user request will be forwarded to this method . Afterwards it creates a response message with the created HTTP status code if the storing has been successful . |
23,438 | public Response deleteResource ( @ PathParam ( JaxRxConstants . SYSTEM ) final String system , @ PathParam ( JaxRxConstants . RESOURCE ) final String resource , final HttpHeaders headers ) { final JaxRx impl = Systems . getInstance ( system ) ; final String info = impl . delete ( new ResourcePath ( resource , headers ) ) ; return Response . ok ( ) . entity ( info ) . build ( ) ; } | This method will be called when an HTTP client sends a DELETE request to delete an existing resource . |
23,439 | public static InputStream getCommandResult ( CommandLine cmdLine , File dir , int expectedExit , long timeout , InputStream input ) throws IOException { DefaultExecutor executor = getDefaultExecutor ( dir , expectedExit , timeout ) ; try ( ByteArrayOutputStream outStr = new ByteArrayOutputStream ( ) ) { executor . setStreamHandler ( new PumpStreamHandler ( outStr , outStr , input ) ) ; try { execute ( cmdLine , dir , executor , null ) ; return new ByteArrayInputStream ( outStr . toByteArray ( ) ) ; } catch ( IOException e ) { log . warning ( "Had output before error: " + new String ( outStr . toByteArray ( ) ) ) ; throw new IOException ( e ) ; } } } | Run the given commandline in the given directory and provide the given input to the command . Also verify that the tool has the expected exit code and does finish in the timeout . |
23,440 | public IMetaEntry deserializeEntry ( final DataInput pData ) throws TTIOException { try { final int kind = pData . readInt ( ) ; switch ( kind ) { case KEY : return new MetaKey ( pData . readInt ( ) ) ; case VALUE : final int valSize = pData . readInt ( ) ; final byte [ ] bytes = new byte [ valSize ] ; pData . readFully ( bytes ) ; return new MetaValue ( new String ( bytes ) ) ; default : throw new IllegalStateException ( "Kind not defined." ) ; } } catch ( final IOException exc ) { throw new TTIOException ( exc ) ; } } | Create a meta - entry out of a serialized byte - representation . |
23,441 | public static boolean isZip ( String fileName ) { if ( fileName == null ) { return false ; } String tl = fileName . toLowerCase ( ) ; for ( String element : ZIP_EXTENSIONS ) { if ( tl . endsWith ( element ) ) { return true ; } } return false ; } | Determines if the file has an extension known to be a ZIP file currently this includes . zip . jar . war . ear . aar |
23,442 | public static void findZip ( String zipName , InputStream zipInput , FileFilter searchFilter , List < String > results ) throws IOException { ZipInputStream zin = new ZipInputStream ( zipInput ) ; while ( true ) { final ZipEntry en ; try { en = zin . getNextEntry ( ) ; } catch ( IOException | IllegalArgumentException e ) { throw new IOException ( "While handling file " + zipName , e ) ; } if ( en == null ) { break ; } if ( searchFilter . accept ( new File ( en . getName ( ) ) ) ) { results . add ( zipName + ZIP_DELIMITER + en ) ; } if ( ZipUtils . isZip ( en . getName ( ) ) ) { findZip ( zipName + ZIP_DELIMITER + en , zin , searchFilter , results ) ; } } } | Looks in the ZIP file available via zipInput for files matching the provided file - filter recursing into sub - ZIP files . |
23,443 | @ SuppressWarnings ( "resource" ) public static InputStream getZipContentsRecursive ( final String file ) throws IOException { int pos = file . indexOf ( '!' ) ; if ( pos == - 1 ) { if ( ! new File ( file ) . exists ( ) ) { throw new IOException ( "File " + file + " does not exist" ) ; } try { return new FileInputStream ( file ) ; } catch ( IOException e ) { if ( e . getMessage ( ) . contains ( "because another process has locked" ) ) { logger . warning ( "Could not read file: " + file + " because it is locked." ) ; return new ByteArrayInputStream ( new byte [ ] { } ) ; } throw e ; } } String zip = file . substring ( 0 , pos ) ; String subfile = file . substring ( pos + 1 ) ; if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "Trying to read zipfile: " + zip + " subfile: " + subfile ) ; } if ( ! new File ( zip ) . exists ( ) || ! new File ( zip ) . isFile ( ) || ! new File ( zip ) . canRead ( ) || new File ( zip ) . length ( ) == 0 ) { throw new IOException ( "ZIP file: " + zip + " does not exist or is empty or not a readable file." ) ; } ZipFile zipfile = new ZipFile ( zip ) ; pos = subfile . indexOf ( '!' ) ; if ( pos != - 1 ) { String remainder = subfile . substring ( pos + 1 ) ; File subzipfile = File . createTempFile ( "ZipUtils" , ".zip" ) ; try { readToTemporaryFile ( pos , zip , subfile , zipfile , subzipfile ) ; return new DeleteOnCloseInputStream ( new ZipFileCloseInputStream ( getZipContentsRecursive ( subzipfile . getAbsolutePath ( ) + ZIP_DELIMITER + remainder ) , zipfile ) , subzipfile ) ; } catch ( IOException e ) { zipfile . close ( ) ; throw e ; } finally { if ( ! subzipfile . delete ( ) ) { logger . warning ( "Could not delete file " + subzipfile ) ; } } } ZipEntry entry = zipfile . getEntry ( subfile ) ; return new ZipFileCloseInputStream ( zipfile . getInputStream ( entry ) , zipfile ) ; } | Get a stream of the noted file which potentially resides inside ZIP files . An exclamation mark ! denotes a zip - entry . ZIP files can be nested inside one another . |
23,444 | public static String getZipStringContentsRecursive ( final String file ) throws IOException { int pos = file . indexOf ( '!' ) ; if ( pos == - 1 ) { if ( ! new File ( file ) . exists ( ) ) { throw new IOException ( "File " + file + " does not exist" ) ; } try { try ( InputStream str = new FileInputStream ( file ) ) { if ( str . available ( ) > 0 ) { return IOUtils . toString ( str , "UTF-8" ) ; } return "" ; } } catch ( IOException e ) { if ( e . getMessage ( ) . contains ( "because another process has locked" ) ) { logger . warning ( "Could not read file: " + file + " because it is locked." ) ; return "" ; } throw e ; } } String zip = file . substring ( 0 , pos ) ; String subfile = file . substring ( pos + 1 ) ; if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "Trying to read zipfile: " + zip + " subfile: " + subfile ) ; } if ( ! new File ( zip ) . exists ( ) || ! new File ( zip ) . isFile ( ) || ! new File ( zip ) . canRead ( ) || new File ( zip ) . length ( ) == 0 ) { throw new IOException ( "ZIP file: " + zip + " does not exist or is empty or not a readable file." ) ; } try ( ZipFile zipfile = new ZipFile ( zip ) ) { pos = subfile . indexOf ( '!' ) ; if ( pos != - 1 ) { String remainder = subfile . substring ( pos + 1 ) ; File subzipfile = File . createTempFile ( "SearchZip" , ".zip" ) ; try { readToTemporaryFile ( pos , zip , subfile , zipfile , subzipfile ) ; return getZipStringContentsRecursive ( subzipfile . getAbsolutePath ( ) + ZIP_DELIMITER + remainder ) ; } finally { if ( ! subzipfile . delete ( ) ) { logger . warning ( "Could not delete file " + subzipfile ) ; } } } ZipEntry entry = zipfile . getEntry ( subfile ) ; try ( InputStream str = zipfile . getInputStream ( entry ) ) { if ( str . available ( ) > 0 ) { return IOUtils . toString ( str , "UTF-8" ) ; } return "" ; } } } | Get the text - contents of the noted file . An exclamation mark ! denotes a zip - entry . ZIP files can be nested inside one another . |
23,445 | public static void extractZip ( File zip , File toDir ) throws IOException { if ( ! toDir . exists ( ) ) { throw new IOException ( "Directory '" + toDir + "' does not exist." ) ; } try ( ZipFile zipFile = new ZipFile ( zip ) ) { Enumeration < ? extends ZipEntry > entries = zipFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry entry = entries . nextElement ( ) ; File target = new File ( toDir , entry . getName ( ) ) ; if ( entry . isDirectory ( ) ) { if ( ! target . mkdirs ( ) ) { logger . warning ( "Could not create directory " + target ) ; } continue ; } if ( ! target . getParentFile ( ) . exists ( ) && ! target . getParentFile ( ) . mkdirs ( ) ) { logger . warning ( "Could not create directory " + target . getParentFile ( ) ) ; } try ( InputStream inputStream = zipFile . getInputStream ( entry ) ) { try ( BufferedOutputStream outputStream = new BufferedOutputStream ( new FileOutputStream ( target ) ) ) { IOUtils . copy ( inputStream , outputStream ) ; } } } } catch ( FileNotFoundException | NoSuchFileException e ) { throw e ; } catch ( IOException e ) { throw new IOException ( "While extracting file " + zip + " to " + toDir , e ) ; } } | Extracts all files in the specified ZIP file and stores them in the denoted directory . The directory needs to exist before running this method . |
23,446 | public static void extractZip ( InputStream zip , final File toDir ) throws IOException { if ( ! toDir . exists ( ) ) { throw new IOException ( "Directory '" + toDir + "' does not exist." ) ; } new ZipFileVisitor ( ) { public void visit ( ZipEntry entry , InputStream data ) throws IOException { File target = new File ( toDir , entry . getName ( ) ) ; if ( entry . isDirectory ( ) ) { if ( ! target . mkdirs ( ) ) { logger . warning ( "Could not create directory " + target ) ; } return ; } if ( ! target . getParentFile ( ) . exists ( ) && ! target . getParentFile ( ) . mkdirs ( ) ) { logger . warning ( "Could not create directory " + target . getParentFile ( ) ) ; } int size ; byte [ ] buffer = new byte [ 2048 ] ; try ( OutputStream fout = new BufferedOutputStream ( new FileOutputStream ( target ) , buffer . length ) ) { while ( ( size = data . read ( buffer , 0 , buffer . length ) ) != - 1 ) { fout . write ( buffer , 0 , size ) ; } } } } . walk ( zip ) ; } | Extracts all files in the ZIP file passed as InputStream and stores them in the denoted directory . The directory needs to exist before running this method . |
23,447 | public static void replaceInZip ( String zipFile , String data , String encoding ) throws IOException { if ( ! isFileInZip ( zipFile ) ) { throw new IOException ( "Parameter should specify a file inside a ZIP file, but had: " + zipFile ) ; } File zip = new File ( zipFile . substring ( 0 , zipFile . indexOf ( ZIP_DELIMITER ) ) ) ; String zipOut = zipFile . substring ( zipFile . indexOf ( ZIP_DELIMITER ) + 1 ) ; logger . info ( "Updating containing Zip " + zip + " to " + zipOut ) ; ZipUtils . replaceInZip ( zip , zipOut , data , encoding ) ; } | Replace the file denoted by the zipFile with the provided data . The zipFile specifies both the zip and the file inside the zip using ! as separator . |
23,448 | public static void replaceInZip ( File zip , String file , String data , String encoding ) throws IOException { File zipOutFile = File . createTempFile ( "ZipReplace" , ".zip" ) ; try { FileOutputStream fos = new FileOutputStream ( zipOutFile ) ; try ( ZipOutputStream zos = new ZipOutputStream ( fos ) ) { try ( ZipFile zipFile = new ZipFile ( zip ) ) { boolean found = false ; Enumeration < ? extends ZipEntry > entries = zipFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry entry = entries . nextElement ( ) ; try { if ( entry . getName ( ) . equals ( file ) ) { zos . putNextEntry ( new ZipEntry ( entry . getName ( ) ) ) ; IOUtils . write ( data , zos , encoding ) ; found = true ; } else { zos . putNextEntry ( entry ) ; IOUtils . copy ( zipFile . getInputStream ( entry ) , zos ) ; } } finally { zos . closeEntry ( ) ; } } if ( ! found ) { zos . putNextEntry ( new ZipEntry ( file ) ) ; try { IOUtils . write ( data , zos , "UTF-8" ) ; } finally { zos . closeEntry ( ) ; } } } } FileUtils . copyFile ( zipOutFile , zip ) ; } finally { if ( ! zipOutFile . delete ( ) ) { throw new IOException ( "Error deleting file: " + zipOutFile ) ; } } } | Replaces the specified file in the provided ZIP file with the provided content . |
23,449 | public static GeoPosition getPosition ( Point2D pixelCoordinate , int zoom , TileFactoryInfo info ) { double wx = pixelCoordinate . getX ( ) ; double wy = pixelCoordinate . getY ( ) ; double flon = ( wx - info . getMapCenterInPixelsAtZoom ( zoom ) . getX ( ) ) / info . getLongitudeDegreeWidthInPixels ( zoom ) ; double e1 = ( wy - info . getMapCenterInPixelsAtZoom ( zoom ) . getY ( ) ) / ( - 1 * info . getLongitudeRadianWidthInPixels ( zoom ) ) ; double e2 = ( 2 * Math . atan ( Math . exp ( e1 ) ) - Math . PI / 2 ) / ( Math . PI / 180.0 ) ; double flat = e2 ; GeoPosition wc = new GeoPosition ( flat , flon ) ; return wc ; } | Convert an on screen pixel coordinate and a zoom level to a geo position |
23,450 | public GeoPosition pixelToGeo ( Point2D pixelCoordinate , int zoom ) { return GeoUtil . getPosition ( pixelCoordinate , zoom , getInfo ( ) ) ; } | Convert a pixel in the world bitmap at the specified zoom level into a GeoPosition |
23,451 | public Point2D geoToPixel ( GeoPosition c , int zoomLevel ) { return GeoUtil . getBitmapCoordinate ( c , zoomLevel , getInfo ( ) ) ; } | Convert a GeoPosition to a pixel position in the world bitmap a the specified zoom level . |
23,452 | private void doPaintComponent ( Graphics g ) { if ( isDesignTime ( ) ) { } else { int z = getZoom ( ) ; Rectangle viewportBounds = getViewportBounds ( ) ; drawMapTiles ( g , z , viewportBounds ) ; drawOverlays ( z , g , viewportBounds ) ; } super . paintBorder ( g ) ; } | the method that does the actual painting |
23,453 | public void setZoom ( int zoom ) { if ( zoom == this . zoomLevel ) { return ; } TileFactoryInfo info = getTileFactory ( ) . getInfo ( ) ; if ( info != null && ( zoom < info . getMinimumZoomLevel ( ) || zoom > info . getMaximumZoomLevel ( ) ) ) { return ; } int oldzoom = this . zoomLevel ; Point2D oldCenter = getCenter ( ) ; Dimension oldMapSize = getTileFactory ( ) . getMapSize ( oldzoom ) ; this . zoomLevel = zoom ; this . firePropertyChange ( "zoom" , oldzoom , zoom ) ; Dimension mapSize = getTileFactory ( ) . getMapSize ( zoom ) ; setCenter ( new Point2D . Double ( oldCenter . getX ( ) * ( mapSize . getWidth ( ) / oldMapSize . getWidth ( ) ) , oldCenter . getY ( ) * ( mapSize . getHeight ( ) / oldMapSize . getHeight ( ) ) ) ) ; repaint ( ) ; } | Set the current zoom level |
23,454 | public void setAddressLocation ( GeoPosition addressLocation ) { GeoPosition old = getAddressLocation ( ) ; this . addressLocation = addressLocation ; setCenter ( getTileFactory ( ) . geoToPixel ( addressLocation , getZoom ( ) ) ) ; firePropertyChange ( "addressLocation" , old , getAddressLocation ( ) ) ; repaint ( ) ; } | Gets the current address location of the map |
23,455 | public void setDrawTileBorders ( boolean drawTileBorders ) { boolean old = isDrawTileBorders ( ) ; this . drawTileBorders = drawTileBorders ; firePropertyChange ( "drawTileBorders" , old , isDrawTileBorders ( ) ) ; repaint ( ) ; } | Set if the tile borders should be drawn . Mainly used for debugging . |
23,456 | public void setCenterPosition ( GeoPosition geoPosition ) { GeoPosition oldVal = getCenterPosition ( ) ; setCenter ( getTileFactory ( ) . geoToPixel ( geoPosition , zoomLevel ) ) ; repaint ( ) ; GeoPosition newVal = getCenterPosition ( ) ; firePropertyChange ( "centerPosition" , oldVal , newVal ) ; } | A property indicating the center position of the map |
23,457 | public void setCenter ( Point2D center ) { Point2D old = this . getCenter ( ) ; double centerX = center . getX ( ) ; double centerY = center . getY ( ) ; Dimension mapSize = getTileFactory ( ) . getMapSize ( getZoom ( ) ) ; int mapHeight = ( int ) mapSize . getHeight ( ) * getTileFactory ( ) . getTileSize ( getZoom ( ) ) ; int mapWidth = ( int ) mapSize . getWidth ( ) * getTileFactory ( ) . getTileSize ( getZoom ( ) ) ; if ( isRestrictOutsidePanning ( ) ) { Insets insets = getInsets ( ) ; int viewportHeight = getHeight ( ) - insets . top - insets . bottom ; int viewportWidth = getWidth ( ) - insets . left - insets . right ; Rectangle newVP = calculateViewportBounds ( center ) ; if ( newVP . getY ( ) < 0 ) { centerY = viewportHeight / 2 ; } if ( ! isHorizontalWrapped ( ) && newVP . getX ( ) < 0 ) { centerX = viewportWidth / 2 ; } if ( newVP . getY ( ) + newVP . getHeight ( ) > mapHeight ) { centerY = mapHeight - viewportHeight / 2 ; } if ( ! isHorizontalWrapped ( ) && ( newVP . getX ( ) + newVP . getWidth ( ) > mapWidth ) ) { centerX = mapWidth - viewportWidth / 2 ; } if ( mapHeight < newVP . getHeight ( ) ) { centerY = mapHeight / 2 ; } if ( ! isHorizontalWrapped ( ) && mapWidth < newVP . getWidth ( ) ) { centerX = mapWidth / 2 ; } } { centerX = centerX % mapWidth ; centerY = centerY % mapHeight ; if ( centerX < 0 ) centerX += mapWidth ; if ( centerY < 0 ) centerY += mapHeight ; } GeoPosition oldGP = this . getCenterPosition ( ) ; this . center = new Point2D . Double ( centerX , centerY ) ; firePropertyChange ( "center" , old , this . center ) ; firePropertyChange ( "centerPosition" , oldGP , this . getCenterPosition ( ) ) ; repaint ( ) ; } | Sets the new center of the map in pixel coordinates . |
23,458 | public void calculateZoomFrom ( Set < GeoPosition > positions ) { if ( positions . size ( ) < 2 ) { return ; } int zoom = getZoom ( ) ; Rectangle2D rect = generateBoundingRect ( positions , zoom ) ; int count = 0 ; while ( ! getViewportBounds ( ) . contains ( rect ) ) { Point2D centr = new Point2D . Double ( rect . getX ( ) + rect . getWidth ( ) / 2 , rect . getY ( ) + rect . getHeight ( ) / 2 ) ; GeoPosition px = getTileFactory ( ) . pixelToGeo ( centr , zoom ) ; setCenterPosition ( px ) ; count ++ ; if ( count > 30 ) break ; if ( getViewportBounds ( ) . contains ( rect ) ) { break ; } zoom = zoom + 1 ; if ( zoom > 15 ) { break ; } setZoom ( zoom ) ; rect = generateBoundingRect ( positions , zoom ) ; } } | Calculates a zoom level so that all points in the specified set will be visible on screen . This is useful if you have a bunch of points in an area like a city and you want to zoom out so that the entire city and it s points are visible without panning . |
23,459 | public void zoomToBestFit ( Set < GeoPosition > positions , double maxFraction ) { if ( positions . isEmpty ( ) ) return ; if ( maxFraction <= 0 || maxFraction > 1 ) throw new IllegalArgumentException ( "maxFraction must be between 0 and 1" ) ; TileFactory tileFactory = getTileFactory ( ) ; TileFactoryInfo info = tileFactory . getInfo ( ) ; if ( info == null ) return ; GeoPosition centre = computeGeoCenter ( positions ) ; setCenterPosition ( centre ) ; if ( positions . size ( ) == 1 ) return ; int bestZoom = info . getMaximumZoomLevel ( ) ; Rectangle2D viewport = getViewportBounds ( ) ; Rectangle2D bounds = generateBoundingRect ( positions , bestZoom ) ; while ( bestZoom >= info . getMinimumZoomLevel ( ) && bounds . getWidth ( ) < viewport . getWidth ( ) * maxFraction && bounds . getHeight ( ) < viewport . getHeight ( ) * maxFraction ) { bestZoom -- ; bounds = generateBoundingRect ( positions , bestZoom ) ; } setZoom ( bestZoom + 1 ) ; } | Zoom and center the map to a best fit around the input GeoPositions . Best fit is defined as the most zoomed - in possible view where both the width and height of a bounding box around the positions take up no more than maxFraction of the viewport width or height respectively . |
23,460 | public GeoPosition convertPointToGeoPosition ( Point2D pt ) { Rectangle bounds = getViewportBounds ( ) ; Point2D pt2 = new Point2D . Double ( pt . getX ( ) + bounds . getX ( ) , pt . getY ( ) + bounds . getY ( ) ) ; GeoPosition pos = getTileFactory ( ) . pixelToGeo ( pt2 , getZoom ( ) ) ; return pos ; } | Converts the specified Point2D in the JXMapViewer s local coordinate space to a GeoPosition on the map . This method is especially useful for determining the GeoPosition under the mouse cursor . |
23,461 | public void put ( URI uri , byte [ ] bimg , BufferedImage img ) { synchronized ( bytemap ) { while ( bytesize > 1000 * 1000 * 50 ) { URI olduri = bytemapAccessQueue . removeFirst ( ) ; byte [ ] oldbimg = bytemap . remove ( olduri ) ; bytesize -= oldbimg . length ; log ( "removed 1 img from byte cache" ) ; } bytemap . put ( uri , bimg ) ; bytesize += bimg . length ; bytemapAccessQueue . addLast ( uri ) ; } addToImageCache ( uri , img ) ; } | Put a tile image into the cache . This puts both a buffered image and array of bytes that make up the compressed image . |
23,462 | protected synchronized ExecutorService getService ( ) { if ( service == null ) { service = Executors . newFixedThreadPool ( threadPoolSize , new ThreadFactory ( ) { private int count = 0 ; public Thread newThread ( Runnable r ) { Thread t = new Thread ( r , "tile-pool-" + count ++ ) ; t . setPriority ( Thread . MIN_PRIORITY ) ; t . setDaemon ( true ) ; return t ; } } ) ; } return service ; } | Subclasses may override this method to provide their own executor services . This method will be called each time a tile needs to be loaded . Implementations should cache the ExecutorService when possible . |
23,463 | public void setUserAgent ( String userAgent ) { if ( userAgent == null || userAgent . isEmpty ( ) ) { throw new IllegalArgumentException ( "User agent can't be null or empty." ) ; } this . userAgent = userAgent ; } | Set the User agent that will be used when making a tile request . |
23,464 | public synchronized void promote ( Tile tile ) { if ( tileQueue . contains ( tile ) ) { try { tileQueue . remove ( tile ) ; tile . setPriority ( Tile . Priority . High ) ; tileQueue . put ( tile ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } } | Increase the priority of this tile so it will be loaded sooner . |
23,465 | public final BufferedImageOp [ ] getFilters ( ) { BufferedImageOp [ ] results = new BufferedImageOp [ filters . length ] ; System . arraycopy ( filters , 0 , results , 0 , results . length ) ; return results ; } | A defensive copy of the Effects to apply to the results of the AbstractPainter s painting operation . The array may be empty but it will never be null . |
23,466 | public void setAntialiasing ( boolean value ) { boolean old = isAntialiasing ( ) ; antialiasing = value ; if ( old != value ) setDirty ( true ) ; firePropertyChange ( "antialiasing" , old , isAntialiasing ( ) ) ; } | Sets the antialiasing setting . This is a bound property . |
23,467 | public void setInterpolation ( Interpolation value ) { Object old = getInterpolation ( ) ; this . interpolation = value == null ? Interpolation . NearestNeighbor : value ; if ( old != value ) setDirty ( true ) ; firePropertyChange ( "interpolation" , old , getInterpolation ( ) ) ; } | Sets a new value for the interpolation setting . This setting determines if interpolation should be used when drawing scaled images . |
23,468 | protected void setDirty ( boolean d ) { boolean old = isDirty ( ) ; this . dirty = d ; firePropertyChange ( "dirty" , old , isDirty ( ) ) ; if ( isDirty ( ) ) { clearCache ( ) ; } } | Sets the dirty bit . If true then the painter is considered dirty and the cache will be cleared . This property is bound . |
23,469 | public void addPainter ( Painter < T > painter ) { Collection < Painter < T > > old = new ArrayList < Painter < T > > ( getPainters ( ) ) ; this . painters . add ( painter ) ; if ( painter instanceof AbstractPainter ) { ( ( AbstractPainter < ? > ) painter ) . addPropertyChangeListener ( handler ) ; } setDirty ( true ) ; firePropertyChange ( "painters" , old , getPainters ( ) ) ; } | Adds a painter to the queue of painters |
23,470 | public void removePainter ( Painter < T > painter ) { Collection < Painter < T > > old = new ArrayList < Painter < T > > ( getPainters ( ) ) ; this . painters . remove ( painter ) ; if ( painter instanceof AbstractPainter ) { ( ( AbstractPainter < ? > ) painter ) . removePropertyChangeListener ( handler ) ; } setDirty ( true ) ; firePropertyChange ( "painters" , old , getPainters ( ) ) ; } | Removes a painter from the queue of painters |
23,471 | public void setClipPreserved ( boolean shouldRestoreState ) { boolean oldShouldRestoreState = isClipPreserved ( ) ; this . clipPreserved = shouldRestoreState ; setDirty ( true ) ; firePropertyChange ( "clipPreserved" , oldShouldRestoreState , shouldRestoreState ) ; } | Sets if the clip should be preserved . Normally the clip will be reset between each painter . Setting clipPreserved to true can be used to let one painter mask other painters that come after it . |
23,472 | public void setTransform ( AffineTransform transform ) { AffineTransform old = getTransform ( ) ; this . transform = transform ; setDirty ( true ) ; firePropertyChange ( "transform" , old , transform ) ; } | Set a transform to be applied to all painters contained in this CompoundPainter |
23,473 | public Tile getTile ( int x , int y , int zoom ) { return new Tile ( x , y , zoom ) { public synchronized boolean isLoaded ( ) { return true ; } public BufferedImage getImage ( ) { return emptyTile ; } } ; } | Gets an instance of an empty tile for the given tile position and zoom on the world map . |
23,474 | public static void installResponseCache ( String baseURL , File cacheDir , boolean checkForUpdates ) { ResponseCache . setDefault ( new LocalResponseCache ( baseURL , cacheDir , checkForUpdates ) ) ; } | Sets this cache as default response cache |
23,475 | public void setZoom ( int zoom ) { zoomChanging = true ; mainMap . setZoom ( zoom ) ; miniMap . setZoom ( mainMap . getZoom ( ) + 4 ) ; if ( sliderReversed ) { zoomSlider . setValue ( zoomSlider . getMaximum ( ) - zoom ) ; } else { zoomSlider . setValue ( zoom ) ; } zoomChanging = false ; } | Set the current zoomlevel for the main map . The minimap will be updated accordingly |
23,476 | public Action getZoomOutAction ( ) { Action act = new AbstractAction ( ) { private static final long serialVersionUID = 5525706163434375107L ; public void actionPerformed ( ActionEvent e ) { setZoom ( mainMap . getZoom ( ) - 1 ) ; } } ; act . putValue ( Action . NAME , "-" ) ; return act ; } | Returns an action which can be attached to buttons or menu items to make the map zoom out |
23,477 | public void setMiniMapVisible ( boolean miniMapVisible ) { boolean old = this . isMiniMapVisible ( ) ; this . miniMapVisible = miniMapVisible ; miniMap . setVisible ( miniMapVisible ) ; firePropertyChange ( "miniMapVisible" , old , this . isMiniMapVisible ( ) ) ; } | Sets if the mini - map should be visible |
23,478 | public void setZoomSliderVisible ( boolean zoomSliderVisible ) { boolean old = this . isZoomSliderVisible ( ) ; this . zoomSliderVisible = zoomSliderVisible ; zoomSlider . setVisible ( zoomSliderVisible ) ; firePropertyChange ( "zoomSliderVisible" , old , this . isZoomSliderVisible ( ) ) ; } | Sets if the zoom slider should be visible |
23,479 | public void setZoomButtonsVisible ( boolean zoomButtonsVisible ) { boolean old = this . isZoomButtonsVisible ( ) ; this . zoomButtonsVisible = zoomButtonsVisible ; zoomInButton . setVisible ( zoomButtonsVisible ) ; zoomOutButton . setVisible ( zoomButtonsVisible ) ; firePropertyChange ( "zoomButtonsVisible" , old , this . isZoomButtonsVisible ( ) ) ; } | Sets if the zoom buttons should be visible . This ia bound property . Changes can be listened for using a PropertyChaneListener |
23,480 | public void setTileFactory ( TileFactory fact ) { mainMap . setTileFactory ( fact ) ; mainMap . setZoom ( fact . getInfo ( ) . getDefaultZoomLevel ( ) ) ; mainMap . setCenterPosition ( new GeoPosition ( 0 , 0 ) ) ; miniMap . setTileFactory ( fact ) ; miniMap . setZoom ( fact . getInfo ( ) . getDefaultZoomLevel ( ) + 3 ) ; miniMap . setCenterPosition ( new GeoPosition ( 0 , 0 ) ) ; zoomSlider . setMinimum ( fact . getInfo ( ) . getMinimumZoomLevel ( ) ) ; zoomSlider . setMaximum ( fact . getInfo ( ) . getMaximumZoomLevel ( ) ) ; } | Sets the tile factory for both embedded JXMapViewer components . Calling this method will also reset the center and zoom levels of both maps as well as the bounds of the zoom slider . |
23,481 | public File getLocalFile ( URL remoteUri ) { StringBuilder sb = new StringBuilder ( ) ; String host = remoteUri . getHost ( ) ; String query = remoteUri . getQuery ( ) ; String path = remoteUri . getPath ( ) ; if ( host != null ) { sb . append ( host ) ; } if ( path != null ) { sb . append ( path ) ; } if ( query != null ) { sb . append ( '?' ) ; sb . append ( query ) ; } String name ; final int maxLen = 250 ; if ( sb . length ( ) < maxLen ) { name = sb . toString ( ) ; } else { name = sb . substring ( 0 , maxLen ) ; } name = name . replace ( '?' , '$' ) ; name = name . replace ( '*' , '$' ) ; name = name . replace ( ':' , '$' ) ; name = name . replace ( '<' , '$' ) ; name = name . replace ( '>' , '$' ) ; name = name . replace ( '"' , '$' ) ; File f = new File ( cacheDir , name ) ; return f ; } | Returns the local File corresponding to the given remote URI . |
23,482 | public void setPosition ( GeoPosition coordinate ) { GeoPosition old = getPosition ( ) ; this . position = coordinate ; firePropertyChange ( "position" , old , getPosition ( ) ) ; } | Set a new GeoPosition for this Waypoint |
23,483 | public String toWMSURL ( int x , int y , int zoom , int tileSize ) { String format = "image/jpeg" ; String styles = "" ; String srs = "EPSG:4326" ; int ts = tileSize ; int circumference = widthOfWorldInPixels ( zoom , tileSize ) ; double radius = circumference / ( 2 * Math . PI ) ; double ulx = MercatorUtils . xToLong ( x * ts , radius ) ; double uly = MercatorUtils . yToLat ( y * ts , radius ) ; double lrx = MercatorUtils . xToLong ( ( x + 1 ) * ts , radius ) ; double lry = MercatorUtils . yToLat ( ( y + 1 ) * ts , radius ) ; String bbox = ulx + "," + uly + "," + lrx + "," + lry ; String url = getBaseUrl ( ) + "version=1.1.1&request=" + "GetMap&Layers=" + layer + "&format=" + format + "&BBOX=" + bbox + "&width=" + ts + "&height=" + ts + "&SRS=" + srs + "&Styles=" + styles + "" ; return url ; } | Convertes to a WMS URL |
23,484 | public static BufferedImage convertToBufferedImage ( Image img ) { BufferedImage buff = createCompatibleTranslucentImage ( img . getWidth ( null ) , img . getHeight ( null ) ) ; Graphics2D g2 = buff . createGraphics ( ) ; try { g2 . drawImage ( img , 0 , 0 , null ) ; } finally { g2 . dispose ( ) ; } return buff ; } | Converts the specified image into a compatible buffered image . |
23,485 | public static void clear ( Image img ) { Graphics g = img . getGraphics ( ) ; try { if ( g instanceof Graphics2D ) { ( ( Graphics2D ) g ) . setComposite ( AlphaComposite . Clear ) ; } else { g . setColor ( new Color ( 0 , 0 , 0 , 0 ) ) ; } g . fillRect ( 0 , 0 , img . getWidth ( null ) , img . getHeight ( null ) ) ; } finally { g . dispose ( ) ; } } | Clears the data from the image . |
23,486 | public static void tileStretchPaint ( Graphics g , JComponent comp , BufferedImage img , Insets ins ) { int left = ins . left ; int right = ins . right ; int top = ins . top ; int bottom = ins . bottom ; g . drawImage ( img , 0 , 0 , left , top , 0 , 0 , left , top , null ) ; g . drawImage ( img , left , 0 , comp . getWidth ( ) - right , top , left , 0 , img . getWidth ( ) - right , top , null ) ; g . drawImage ( img , comp . getWidth ( ) - right , 0 , comp . getWidth ( ) , top , img . getWidth ( ) - right , 0 , img . getWidth ( ) , top , null ) ; g . drawImage ( img , 0 , top , left , comp . getHeight ( ) - bottom , 0 , top , left , img . getHeight ( ) - bottom , null ) ; g . drawImage ( img , left , top , comp . getWidth ( ) - right , comp . getHeight ( ) - bottom , left , top , img . getWidth ( ) - right , img . getHeight ( ) - bottom , null ) ; g . drawImage ( img , comp . getWidth ( ) - right , top , comp . getWidth ( ) , comp . getHeight ( ) - bottom , img . getWidth ( ) - right , top , img . getWidth ( ) , img . getHeight ( ) - bottom , null ) ; g . drawImage ( img , 0 , comp . getHeight ( ) - bottom , left , comp . getHeight ( ) , 0 , img . getHeight ( ) - bottom , left , img . getHeight ( ) , null ) ; g . drawImage ( img , left , comp . getHeight ( ) - bottom , comp . getWidth ( ) - right , comp . getHeight ( ) , left , img . getHeight ( ) - bottom , img . getWidth ( ) - right , img . getHeight ( ) , null ) ; g . drawImage ( img , comp . getWidth ( ) - right , comp . getHeight ( ) - bottom , comp . getWidth ( ) , comp . getHeight ( ) , img . getWidth ( ) - right , img . getHeight ( ) - bottom , img . getWidth ( ) , img . getHeight ( ) , null ) ; } | Draws an image on top of a component by doing a 3x3 grid stretch of the image using the specified insets . |
23,487 | public void mouseClicked ( MouseEvent evt ) { final boolean left = SwingUtilities . isLeftMouseButton ( evt ) ; final boolean singleClick = ( evt . getClickCount ( ) == 1 ) ; if ( ( left && singleClick ) ) { Rectangle bounds = viewer . getViewportBounds ( ) ; int x = bounds . x + evt . getX ( ) ; int y = bounds . y + evt . getY ( ) ; Point pixelCoordinates = new Point ( x , y ) ; mapClicked ( viewer . getTileFactory ( ) . pixelToGeo ( pixelCoordinates , viewer . getZoom ( ) ) ) ; } } | Gets called on mouseClicked events calculates the GeoPosition and fires the mapClicked method that the extending class needs to implement . |
23,488 | private void setRect ( double minLat , double minLng , double maxLat , double maxLng ) { if ( ! ( minLat < maxLat ) ) { throw new IllegalArgumentException ( "GeoBounds is not valid - minLat must be less that maxLat." ) ; } if ( ! ( minLng < maxLng ) ) { if ( minLng > 0 && minLng < 180 && maxLng < 0 ) { rects = new Rectangle2D [ ] { new Rectangle2D . Double ( minLng , minLat , 180 - minLng , maxLat - minLat ) , new Rectangle2D . Double ( - 180 , minLat , maxLng + 180 , maxLat - minLat ) } ; } else { rects = new Rectangle2D [ ] { new Rectangle2D . Double ( minLng , minLat , maxLng - minLng , maxLat - minLat ) } ; throw new IllegalArgumentException ( "GeoBounds is not valid - minLng must be less that maxLng or " + "minLng must be greater than 0 and maxLng must be less than 0." ) ; } } else { rects = new Rectangle2D [ ] { new Rectangle2D . Double ( minLng , minLat , maxLng - minLng , maxLat - minLat ) } ; } } | Sets the internal rectangle representation . |
23,489 | public boolean intersects ( GeoBounds other ) { boolean rv = false ; for ( Rectangle2D r1 : rects ) { for ( Rectangle2D r2 : other . rects ) { rv = r1 . intersects ( r2 ) ; if ( rv ) { break ; } } if ( rv ) { break ; } } return rv ; } | Determines if this bounds intersects the other bounds . |
23,490 | public GeoPosition getSouthEast ( ) { Rectangle2D r = rects [ 0 ] ; if ( rects . length > 1 ) { r = rects [ 1 ] ; } return new GeoPosition ( r . getY ( ) , r . getMaxX ( ) ) ; } | Gets the south east position . |
23,491 | public ExecuterManager bindListener ( Class < ? extends IExecutersListener > listener ) throws IllegalAccessException , InstantiationException { if ( listener != null ) { this . executerListeners . add ( listener . newInstance ( ) ) ; } return this ; } | bind executer listener |
23,492 | public static void save ( byte [ ] bytes , String filePath , String fileName ) throws IOException { Path path = Paths . get ( filePath , fileName ) ; mkirDirs ( path . getParent ( ) ) ; String pathStr = path . toString ( ) ; File file = new File ( pathStr ) ; write ( bytes , file ) ; } | save bytes into file |
23,493 | public static void write ( byte [ ] bytes , File file ) throws IOException { BufferedOutputStream outputStream = new BufferedOutputStream ( new FileOutputStream ( file ) ) ; outputStream . write ( bytes ) ; outputStream . close ( ) ; } | wtire bytes into file |
23,494 | public static char forDigit ( int digit , int radix ) { if ( digit >= 0 && digit < radix && radix >= Character . MIN_RADIX && radix <= MAX_RADIX ) { return digits [ digit ] ; } return '\u0000' ; } | Determines the character representation for a specific digit in the specified radix . |
23,495 | public RequestResponse setRequestData ( Object requestData ) { this . requestData = requestData ; requestJson = requestData != null ? ( requestData instanceof JsonNode ? ( JsonNode ) requestData : SerializationUtils . toJson ( requestData ) ) : null ; return this ; } | HTTP request body . |
23,496 | public RequestResponse setResponseData ( byte [ ] responseData ) { this . responseData = responseData ; try { responseJson = responseData != null ? SerializationUtils . readJson ( responseData ) : null ; } catch ( Exception e ) { responseJson = null ; LOGGER . error ( e . getMessage ( ) , e ) ; } return this ; } | Raw HTTP response data . |
23,497 | public String create ( Request request , Response response , Long duration ) { return createStringBuilder ( request , response , duration ) . toString ( ) ; } | Creates a string suitable for logging output . |
23,498 | public static long getMacAddr ( ) { if ( macAddr == 0 ) { try { InetAddress ip = InetAddress . getLocalHost ( ) ; NetworkInterface network = NetworkInterface . getByInetAddress ( ip ) ; byte [ ] mac = network . getHardwareAddress ( ) ; for ( byte temp : mac ) { macAddr = ( macAddr << 8 ) | ( ( int ) temp & 0xFF ) ; } } catch ( Exception e ) { macAddr = 0 ; } } return macAddr ; } | Returns host s MAC address . |
23,499 | public static long waitTillNextMillisec ( long currentMillisec ) { long nextMillisec = System . currentTimeMillis ( ) ; for ( ; nextMillisec <= currentMillisec ; nextMillisec = System . currentTimeMillis ( ) ) { Thread . yield ( ) ; } return nextMillisec ; } | Waits till clock moves to the next millisecond . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.