idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
10,500
public static String getIdentifyerFromDN ( String dn ) { if ( dn != null ) { String [ ] parts = dn . trim ( ) . split ( "," ) ; String [ ] kvs ; if ( parts . length > 0 && parts [ 0 ] . contains ( "=" ) ) { kvs = parts [ 0 ] . trim ( ) . split ( "=" ) ; return kvs . length > 0 ? kvs [ 0 ] : null ; } } return null ; }
Return the Value of the given Identifyer from a given dn .
10,501
public static Router createRouterFor ( ServletContext con ) { String contextName = EldaRouterRestletSupport . flatContextPath ( con . getContextPath ( ) ) ; List < PrefixAndFilename > pfs = prefixAndFilenames ( con , contextName ) ; Router result = new DefaultRouter ( ) ; String baseFilePath = ServletUtils . withTrailingSlash ( con . getRealPath ( "/" ) ) ; AuthMap am = AuthMap . loadAuthMap ( EldaFileManager . get ( ) , noNamesAndValues ) ; ModelLoader modelLoader = new APIModelLoader ( baseFilePath ) ; addBaseFilepath ( baseFilePath ) ; SpecManagerImpl sm = new SpecManagerImpl ( result , modelLoader ) ; SpecManagerFactory . set ( sm ) ; for ( PrefixAndFilename pf : pfs ) { loadOneConfigFile ( result , am , modelLoader , pf . prefixPath , pf . fileName ) ; } int count = result . countTemplates ( ) ; return count == 0 ? RouterFactory . getDefaultRouter ( ) : result ; }
Create a new Router initialised with the configs appropriate to the contextPath .
10,502
protected static Renderer changeMediaType ( final Renderer r , final MediaType mt ) { return new Renderer ( ) { public MediaType getMediaType ( Bindings unused ) { return mt ; } public BytesOut render ( Times t , Bindings rc , Map < String , String > termBindings , APIResultSet results ) { return r . render ( t , rc , termBindings , results ) ; } public String getPreferredSuffix ( ) { return r . getPreferredSuffix ( ) ; } public CompleteContext . Mode getMode ( ) { return r . getMode ( ) ; } } ; }
Given a renderer r and a media type mt return a new renderer which behaves like r except that it announces its media type as mt . r itself is not changed .
10,503
public char match ( ISense source , ISense target ) throws MatcherLibraryException { String sSynset = source . getGloss ( ) ; String tSynset = target . getGloss ( ) ; StringTokenizer stSource = new StringTokenizer ( sSynset , " ,.\"'();" ) ; StringTokenizer stTarget = new StringTokenizer ( tSynset , " ,.\"'();" ) ; String lemma ; int counter = 0 ; while ( stSource . hasMoreTokens ( ) ) { lemma = stSource . nextToken ( ) ; if ( ! meaninglessWords . contains ( lemma ) ) { List < String > lemmas = target . getLemmas ( ) ; for ( String lemmaToCompare : lemmas ) { if ( lemma . equals ( lemmaToCompare ) ) { counter ++ ; } } } } if ( counter >= threshold ) { return IMappingElement . LESS_GENERAL ; } while ( stTarget . hasMoreTokens ( ) ) { lemma = stTarget . nextToken ( ) ; if ( ! meaninglessWords . contains ( lemma ) ) { List < String > lemmas = source . getLemmas ( ) ; for ( String lemmaToCompare : lemmas ) { if ( lemma . equals ( lemmaToCompare ) ) { counter ++ ; } } } } if ( counter >= threshold ) { return IMappingElement . MORE_GENERAL ; } return IMappingElement . IDK ; }
Computes the relations with WordNet gloss matcher .
10,504
@ Produces ( { MediaType . TEXT_HTML , "application/json" } ) @ ApiOperation ( value = "Delete all the registered services" , notes = "BE CAREFUL! You can lose all your data. It returns a message which confirms all the service deletions." ) @ ApiResponses ( value = { @ ApiResponse ( code = 200 , message = "Registry cleaned. All the services are deleted." ) , @ ApiResponse ( code = 304 , message = "The services could not be cleared." ) , @ ApiResponse ( code = 403 , message = "You have not got the appropriate permissions for clearing the services" ) , @ ApiResponse ( code = 500 , message = "Internal error" ) } ) public Response clearServices ( @ ApiParam ( value = "Response message media type" , allowableValues = "application/json,text/html" ) @ HeaderParam ( "Accept" ) String accept ) { URI serviceUri = uriInfo . getRequestUri ( ) ; String response ; try { if ( manager . getServiceManager ( ) . clearServices ( ) ) { if ( accept . contains ( MediaType . TEXT_HTML ) ) { response = "<html>\n <head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n </head>\n" + " <body>\n The services have been cleared.\n </body>\n</html>" ; } else { JsonObject message = new JsonObject ( ) ; message . add ( "message" , new JsonPrimitive ( "The services have been cleared." ) ) ; response = message . toString ( ) ; } return Response . status ( Status . OK ) . contentLocation ( serviceUri ) . entity ( response ) . build ( ) ; } else { if ( accept . contains ( MediaType . TEXT_HTML ) ) { response = "<html>\n <head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n </head>\n" + " <body>\n The services could not be cleared. Try again or contact a server administrator.\n </body>\n</html>" ; } else { JsonObject message = new JsonObject ( ) ; message . add ( "message" , new JsonPrimitive ( "The services could not be cleared. Try again or contact a server administrator." ) ) ; response = message . toString ( ) ; } return Response . status ( Status . NOT_MODIFIED ) . contentLocation ( serviceUri ) . entity ( response ) . build ( ) ; } } catch ( SalException e ) { if ( accept . contains ( MediaType . TEXT_HTML ) ) { response = "<html>\n <head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n </head>\n" + "<body>\nThere was an error while clearing the services. Contact the system administrator. \n </body>\n</html>" ; } else { JsonObject message = new JsonObject ( ) ; message . add ( "message" , new JsonPrimitive ( "There was an error while clearing the services. Contact the system administrator." ) ) ; response = message . toString ( ) ; } log . error ( "SAL Exception while deleting service" , e ) ; return Response . status ( Status . INTERNAL_SERVER_ERROR ) . entity ( response ) . build ( ) ; } }
Clears the services registry
10,505
private char matchPrefix ( String str1 , String str2 ) { char rel = IMappingElement . IDK ; int spacePos1 = str1 . indexOf ( ' ' ) ; String suffix = str1 . substring ( str2 . length ( ) ) ; if ( - 1 < spacePos1 && ! suffixes . containsKey ( suffix ) ) { if ( str2 . length ( ) == spacePos1 ) { rel = IMappingElement . LESS_GENERAL ; } else { String left = str1 . substring ( 0 , spacePos1 ) ; char secondRel = match ( left , str2 ) ; if ( IMappingElement . MORE_GENERAL == secondRel || IMappingElement . EQUIVALENCE == secondRel ) { rel = IMappingElement . LESS_GENERAL ; } else { rel = secondRel ; } } } else { if ( suffix . startsWith ( "-" ) ) { suffix = suffix . substring ( 1 ) ; } if ( suffix . endsWith ( "-" ) || suffix . endsWith ( ";" ) || suffix . endsWith ( "." ) || suffix . endsWith ( "," ) || suffix . endsWith ( "-" ) ) { suffix = suffix . substring ( 0 , suffix . length ( ) - 1 ) ; } if ( suffixes . containsKey ( suffix ) ) { rel = suffixes . get ( suffix ) ; rel = reverseRelation ( rel ) ; } } return rel ; }
Computes relation with prefix matcher .
10,506
protected void reset ( ) { attributeStatics = new StringBuilder ( ) ; functionGroupStatics = new StringBuilder ( ) ; properties = new StringBuilder ( ) ; constructor = new StringBuilder ( ) ; gettersSetters = new StringBuilder ( ) ; equals = new StringBuilder ( ) ; hashCode = new StringBuilder ( ) ; toString = new StringBuilder ( ) ; footer = new StringBuilder ( ) ; }
Resets all of the buffers .
10,507
protected String generateInterfaceName ( CpoClass cpoClass ) { String className = cpoClass . getName ( ) ; if ( className . lastIndexOf ( "." ) != - 1 ) { className = className . substring ( className . lastIndexOf ( "." ) + 1 ) ; } return className ; }
The cpoClass name will be used for the name of the interface
10,508
protected void firePropertyChange ( String propertyName , Object oldValue , Object newValue ) { if ( oldValue instanceof JsonValue ) { oldValue = getRawObject ( ( JsonValue ) oldValue ) ; } if ( newValue instanceof JsonValue ) { newValue = getRawObject ( ( JsonValue ) newValue ) ; } changeSupport . firePropertyChange ( propertyName , oldValue , newValue ) ; }
Notify listeners that a property has changed its value
10,509
public static String [ ] getAvailableStatusNames ( ) { List < String > nameList = new ArrayList < > ( ) ; for ( Status status : INSTANCES . values ( ) ) { nameList . add ( status . getName ( ) ) ; } return nameList . toArray ( new String [ nameList . size ( ) ] ) ; }
Gets the available status names in ascending order of their corresponding status .
10,510
public BioCDocument readDocument ( ) throws XMLStreamException { if ( reader . document != null ) { BioCDocument thisDocument = reader . document ; reader . read ( ) ; return thisDocument ; } else { return null ; } }
Reads one BioC document from the XML file .
10,511
public void waitFor ( long timeout ) throws JSchException , ExitCode , InterruptedException { long deadline ; try { deadline = System . currentTimeMillis ( ) + timeout ; while ( ! channel . isClosed ( ) ) { if ( System . currentTimeMillis ( ) >= deadline ) { throw new TimeoutException ( this ) ; } Thread . sleep ( 100 ) ; } if ( channel . getExitStatus ( ) != 0 ) { throw new ExitCode ( new Launcher ( command ) , channel . getExitStatus ( ) ) ; } } finally { channel . disconnect ( ) ; } }
Waits for termination .
10,512
public Integer transformIn ( Integer dbIn ) throws CpoException { logger . debug ( "Inside TransformNoOp::transformIn(" + dbIn + ");" ) ; return dbIn ; }
Transforms the datasource object into an object required by the class . The type of the dbIn parameter and the type of the return value must change to match the types being converted . Reflection is used to true everything up at runtime .
10,513
public void dispatch ( Event < ? > event ) { for ( EventListener listener : KReflection . Holder . INSTANCE . listeners ) { try { listener . handleEvent ( event ) ; } catch ( Exception e ) { } } }
Dispatch an event to all listeners .
10,514
public boolean isSatisfiable ( String input ) throws SATSolverException { Boolean result = solutionsCache . get ( input ) ; if ( null == result ) { result = satSolver . isSatisfiable ( input ) ; solutionsCache . put ( input , result ) ; } return result ; }
Calls the solver and caches the answer .
10,515
public ExtendedPropertyDescriptor setReadOnly ( ) { try { setWriteMethod ( null ) ; } catch ( IntrospectionException e ) { Logger . getLogger ( ExtendedPropertyDescriptor . class . getName ( ) ) . log ( Level . SEVERE , null , e ) ; } return this ; }
Force this property to be readonly .
10,516
private void complete ( KSplit split , KCall call ) { reset ( call . getProcess ( ) ) ; split . split ( call ) ; }
Called at the end of a KWhileLoop
10,517
public void end ( String state , String attributes ) { this . end = System . currentTimeMillis ( ) ; this . state = state ; this . attributes = attributes ; }
Called when it is ended
10,518
public static ResourceManager get ( String bundleName ) { ResourceManager rm = ( ResourceManager ) nameToRM . get ( bundleName ) ; if ( rm == null ) { ResourceBundle rb = ResourceBundle . getBundle ( bundleName ) ; rm = new ResourceManager ( rb ) ; nameToRM . put ( bundleName , rm ) ; } return rm ; }
Gets the ResourceManager with the given name .
10,519
public static void configureLog4J ( ) { String log4jConf = System . getProperty ( "log4j.configuration" ) ; if ( null != log4jConf ) { PropertyConfigurator . configure ( log4jConf ) ; } else { System . err . println ( "No log4j.configuration property specified. Using defaults." ) ; BasicConfigurator . configure ( ) ; } }
Configures LOG4J using a configuration file given in a log4j . configuration system property .
10,520
public static void writeObject ( Object object , String fileName ) throws DISIException { log . info ( "Writing " + fileName ) ; try { FileOutputStream fos = new FileOutputStream ( fileName ) ; ObjectOutputStream oos = new ObjectOutputStream ( fos ) ; oos . writeObject ( object ) ; oos . close ( ) ; fos . close ( ) ; } catch ( IOException e ) { final String errMessage = e . getClass ( ) . getSimpleName ( ) + ": " + e . getMessage ( ) ; log . error ( errMessage , e ) ; throw new DISIException ( errMessage , e ) ; } }
Writes Java object to a file .
10,521
public static Object readObject ( String fileName , boolean isInternalFile ) throws DISIException { Object result ; try { InputStream fos = null ; if ( isInternalFile == true ) { fos = Thread . currentThread ( ) . getContextClassLoader ( ) . getResource ( fileName ) . openStream ( ) ; } else { fos = new FileInputStream ( fileName ) ; } BufferedInputStream bis = new BufferedInputStream ( fos ) ; ObjectInputStream oos = new ObjectInputStream ( bis ) ; try { result = oos . readObject ( ) ; } catch ( IOException e ) { final String errMessage = e . getClass ( ) . getSimpleName ( ) + ": " + e . getMessage ( ) ; log . error ( errMessage , e ) ; throw new DISIException ( errMessage , e ) ; } catch ( ClassNotFoundException e ) { final String errMessage = e . getClass ( ) . getSimpleName ( ) + ": " + e . getMessage ( ) ; log . error ( errMessage , e ) ; throw new DISIException ( errMessage , e ) ; } oos . close ( ) ; bis . close ( ) ; fos . close ( ) ; } catch ( IOException e ) { final String errMessage = e . getClass ( ) . getSimpleName ( ) + ": " + e . getMessage ( ) ; log . error ( errMessage , e ) ; throw new DISIException ( errMessage , e ) ; } return result ; }
Reads Java object from a file .
10,522
public void release ( ) { parent = null ; firstChild = null ; prevSibling = null ; nextSibling = null ; allowChildren = true ; }
Resets all the attributes to their default state .
10,523
public void addChild ( Node node ) throws ChildNodeException { if ( node != null ) { if ( ! allowChildren ) { throw new ChildNodeException ( ) ; } if ( getFirstChild ( ) == null ) { setFirstChild ( node ) ; getFirstChild ( ) . setPrevSibling ( firstChild ) ; getFirstChild ( ) . setNextSibling ( firstChild ) ; } else { Node lastChild = getFirstChild ( ) . getPrevSibling ( ) ; if ( lastChild != null ) { lastChild . setNextSibling ( node ) ; } node . setNextSibling ( getFirstChild ( ) ) ; } node . setParent ( this ) ; } }
This function adds a child to the linked - list of children for this node . It adds the child to the end of the list .
10,524
public void insertSiblingBefore ( Node node ) throws ChildNodeException { if ( node != null ) { node . setPrevSibling ( getPrevSibling ( ) ) ; node . setNextSibling ( this ) ; } }
Inserts a Sibling into the linked list just prior to this Node
10,525
public void insertSiblingAfter ( Node node ) { if ( node != null ) { node . setNextSibling ( getNextSibling ( ) ) ; node . setPrevSibling ( this ) ; } }
Adds a Sibling immediately following this Node .
10,526
public void insertParentBefore ( Node node ) throws ChildNodeException { if ( node != null ) { if ( hasParent ( ) ) { getParentNode ( ) . addChild ( node ) ; getParentNode ( ) . removeChild ( this ) ; } node . addChild ( this ) ; } }
Inserts a new Parent into the tree structure and adds this node as its child .
10,527
public void insertParentAfter ( Node node ) throws ChildNodeException { if ( node != null ) { node . setFirstChild ( getFirstChild ( ) ) ; setFirstChild ( null ) ; addChild ( node ) ; } }
Inserts a new Parent Node as a child of this node and moves all pre - existing children to be children of the new Parent Node .
10,528
public boolean removeChild ( Node node ) throws ChildNodeException { Node currNode = getFirstChild ( ) ; boolean rc = false ; if ( ! allowChildren ) { throw new ChildNodeException ( ) ; } if ( node != null && ! isLeaf ( ) ) { if ( node == currNode && node == currNode . getNextSibling ( ) ) { setFirstChild ( null ) ; rc = true ; } else { do { if ( currNode == node ) { if ( node . getPrevSibling ( ) != null ) { node . getPrevSibling ( ) . setNextSibling ( node . getNextSibling ( ) ) ; } if ( node == getFirstChild ( ) ) { setFirstChild ( node . getNextSibling ( ) ) ; } rc = true ; break ; } currNode = currNode . getNextSibling ( ) ; } while ( currNode != getFirstChild ( ) ) ; } } return rc ; }
Searches for an immediate child node and if found removes it from the linked - list of children .
10,529
public void removeChildNode ( ) throws ChildNodeException { Node parentLast ; Node thisLast ; if ( ! isLeaf ( ) && hasParent ( ) ) { parentLast = getParentNode ( ) . getFirstChild ( ) . getPrevSibling ( ) ; thisLast = getFirstChild ( ) . getPrevSibling ( ) ; parentLast . setNextSibling ( getFirstChild ( ) ) ; thisLast . setNextSibling ( getParentNode ( ) . getFirstChild ( ) ) ; getParentNode ( ) . removeChild ( this ) ; } }
Remove just this node from the tree . The children of this node get attached to the parent .
10,530
public String getPath ( ) { String result ; result = path . toString ( ) . substring ( getRoot ( ) . getAbsolute ( ) . length ( ) ) ; return result . replace ( File . separatorChar , Filesystem . SEPARATOR_CHAR ) ; }
does not include the drive on windows
10,531
public FileNode deleteTree ( ) throws DeleteException , NodeNotFoundException { if ( ! exists ( ) ) { throw new NodeNotFoundException ( this ) ; } try { doDeleteTree ( path ) ; } catch ( IOException e ) { throw new DeleteException ( this , e ) ; } return this ; }
Deletes a file or directory . Directories are deleted recursively . Handles Links .
10,532
public void analyze ( ) { for ( String key : importSource . getKeys ( ) ) { Change change = createChange ( key ) ; setConflictAttributes ( change ) ; if ( change . getType ( ) != Change . TYPE_NO_CHANGE ) { if ( change . isConflicting ( ) ) { conflictingChanges . add ( change ) ; } else { nonConflictingChanges . add ( change ) ; } } } }
Determines the changes between the import source and the database and classifies them as conflicting and non - conflicting .
10,533
protected void setConflictAttributes ( Change change ) throws IllegalArgumentException { change . setAcceptStatus ( change . getImportedStatus ( ) ) ; change . setAcceptValue ( change . getImportedValue ( ) ) ; if ( useMasterValueFromFile ) { change . setAcceptMasterValue ( change . getImportedMasterValue ( ) ) ; } else { change . setAcceptMasterValue ( change . getDbMasterValue ( ) ) ; } switch ( change . getType ( ) ) { case Change . TYPE_NO_CHANGE : break ; case Change . TYPE_MASTER_VALUE_CHANGED : change . setConflicting ( true ) ; change . setAcceptable ( true ) ; change . setAccept ( false ) ; break ; case Change . TYPE_IMPORTED_STATUS_OLDER : change . setConflicting ( true ) ; change . setAcceptable ( true ) ; change . setAccept ( true ) ; break ; case Change . TYPE_IMPORTED_STATUS_NEWER : change . setConflicting ( false ) ; change . setAcceptable ( true ) ; change . setAccept ( true ) ; break ; case Change . TYPE_LANGUAGE_ADDITION : change . setConflicting ( true ) ; change . setAcceptable ( false ) ; break ; case Change . TYPE_MASTER_LANGUAGE_ADDITION : change . setConflicting ( true ) ; change . setAcceptable ( false ) ; break ; case Change . TYPE_VALUE_CHANGED : case Change . TYPE_VALUE_AND_STATUS_CHANGED : change . setConflicting ( false ) ; change . setAcceptable ( true ) ; change . setAccept ( true ) ; Status importedStatus = change . getImportedStatus ( ) ; Status dbStatus = change . getDbStatus ( ) ; if ( dbStatus == Status . SPECIAL ) { change . setConflicting ( true ) ; change . setAcceptable ( false ) ; } else if ( dbStatus == Status . INITIAL ) { if ( importedStatus == Status . INITIAL ) { change . setAcceptStatus ( Status . TRANSLATED ) ; } else if ( importedStatus == Status . SPECIAL ) { change . setConflicting ( true ) ; change . setAcceptable ( false ) ; change . setAcceptStatus ( Status . TRANSLATED ) ; } } else if ( dbStatus == Status . TRANSLATED ) { if ( importedStatus == Status . INITIAL || importedStatus == Status . SPECIAL ) { change . setConflicting ( true ) ; change . setAcceptStatus ( Status . TRANSLATED ) ; } } else if ( dbStatus == Status . VERIFIED ) { change . setConflicting ( true ) ; if ( importedStatus == Status . VERIFIED ) { change . setAccept ( false ) ; } } break ; case Change . TYPE_KEY_ADDITION : change . setConflicting ( true ) ; change . setAcceptable ( false ) ; break ; default : throw new IllegalArgumentException ( "Unknown change type: " + change . getType ( ) ) ; } }
Determines whether a change is conflicting acceptable and to be accepted and sets the values to be accepted . This routine is the only one dealing with the mentioned conflict attributes . It may be overridden to change the conflict specification .
10,534
private void setupModelSpecification ( Map < String , String > locationMappings , Set < String > ignoredImports ) { OntDocumentManager documentManager = new OntDocumentManager ( ) ; for ( Map . Entry < String , String > mapping : locationMappings . entrySet ( ) ) { documentManager . addAltEntry ( mapping . getKey ( ) , mapping . getValue ( ) ) ; } for ( String ignoreUri : ignoredImports ) { documentManager . addIgnoreImport ( ignoreUri ) ; } documentManager . setProcessImports ( false ) ; documentManager . setCacheModels ( false ) ; this . modelSpec = new OntModelSpec ( OntModelSpec . OWL_MEM ) ; this . modelSpec . setDocumentManager ( documentManager ) ; }
Setup a the OntModelSpec to be used when parsing services . In particular setup import redirections etc .
10,535
public void shutdown ( ) { log . info ( "Shutting down Ontology crawlers." ) ; this . executor . shutdown ( ) ; try { if ( ! this . executor . awaitTermination ( 5 , TimeUnit . SECONDS ) ) { this . executor . shutdownNow ( ) ; if ( ! this . executor . awaitTermination ( 2 , TimeUnit . SECONDS ) ) log . error ( "Pool did not terminate" ) ; } } catch ( InterruptedException ie ) { this . executor . shutdownNow ( ) ; Thread . currentThread ( ) . interrupt ( ) ; } }
This method will be called when the server is being shutdown . Ensure a clean shutdown .
10,536
public void addModelToGraph ( URI graphUri , Model data ) { if ( graphUri == null || data == null ) return ; if ( this . sparqlServiceEndpoint != null ) { datasetAccessor . add ( graphUri . toASCIIString ( ) , data ) ; } else { this . addModelToGraphSparqlQuery ( graphUri , data ) ; } }
Add statements to a named model
10,537
public void deleteGraph ( URI graphUri ) { if ( graphUri == null || ! this . canBeModified ( ) ) return ; if ( this . sparqlServiceEndpoint != null ) { this . datasetAccessor . deleteModel ( graphUri . toASCIIString ( ) ) ; } else { deleteGraphSparqlUpdate ( graphUri ) ; } log . debug ( "Graph deleted: {}" , graphUri . toASCIIString ( ) ) ; }
Delete a named model of a Dataset
10,538
private void deleteGraphSparqlUpdate ( URI graphUri ) { UpdateRequest request = UpdateFactory . create ( ) ; request . setPrefixMapping ( PrefixMapping . Factory . create ( ) . setNsPrefixes ( Vocabularies . prefixes ) ) ; request . add ( new UpdateDrop ( graphUri . toASCIIString ( ) ) ) ; UpdateProcessor processor = UpdateExecutionFactory . createRemoteForm ( request , this . getSparqlUpdateEndpoint ( ) . toASCIIString ( ) ) ; processor . execute ( ) ; }
Delete Graph using SPARQL Update
10,539
protected OntModel getGraph ( ) { if ( this . sparqlServiceEndpoint != null ) { return ModelFactory . createOntologyModel ( this . modelSpec , datasetAccessor . getModel ( ) ) ; } else { return this . getGraphSparqlQuery ( ) ; } }
Gets the default model of a Dataset
10,540
public OntModel getGraph ( URI graphUri ) { log . debug ( "Obtaining graph: {}" , graphUri . toASCIIString ( ) ) ; if ( graphUri == null ) return null ; return this . getGraphSparqlQuery ( graphUri ) ; }
Get a named model of a Dataset
10,541
private OntModel getGraphSparqlQuery ( URI graphUri ) { StringBuilder queryStr = new StringBuilder ( "CONSTRUCT { ?s ?p ?o } \n" ) . append ( "WHERE {\n" ) ; if ( graphUri != null ) { queryStr . append ( "GRAPH <" ) . append ( graphUri . toASCIIString ( ) ) . append ( "> " ) ; } queryStr . append ( "{ ?s ?p ?o } } \n" ) ; log . debug ( "Querying graph store: {}" , queryStr . toString ( ) ) ; Query query = QueryFactory . create ( queryStr . toString ( ) ) ; QueryExecution qe = QueryExecutionFactory . sparqlService ( this . getSparqlQueryEndpoint ( ) . toASCIIString ( ) , query ) ; MonitoredQueryExecution qexec = new MonitoredQueryExecution ( qe ) ; OntModel resultModel = ModelFactory . createOntologyModel ( OntModelSpec . OWL_MEM_MICRO_RULE_INF ) ; try { qexec . execConstruct ( resultModel ) ; return resultModel ; } finally { qexec . close ( ) ; } }
Obtains the OntModel within a named graph or the default graph if no graphUri is provided
10,542
public Set < URI > listStoredGraphs ( ) { StringBuilder strBuilder = new StringBuilder ( ) . append ( "SELECT DISTINCT ?graph WHERE {" ) . append ( "\n" ) . append ( "GRAPH ?graph {" ) . append ( "?s ?p ?o" ) . append ( " }" ) . append ( "\n" ) . append ( "}" ) . append ( "\n" ) ; return listResourcesByQuery ( strBuilder . toString ( ) , "graph" ) ; }
Figure out the models that are already in the Knowledge Base
10,543
public int getSerializedSize ( ) { int result = 0 ; for ( final Map . Entry < Integer , Field > entry : fields . entrySet ( ) ) { result += entry . getValue ( ) . getSerializedSize ( entry . getKey ( ) ) ; } return result ; }
Get the number of bytes required to encode this set .
10,544
public void add ( V value ) { values . add ( value ) ; if ( value instanceof JsonEntity ) { ( ( JsonEntity ) value ) . addPropertyChangeListener ( propListener ) ; } firePropertyChange ( "#" + ( values . size ( ) - 1 ) , null , value ) ; }
Adds a value to the receiver s collection
10,545
public void remove ( V value ) { int index = values . indexOf ( value ) ; values . remove ( value ) ; if ( value instanceof JsonEntity ) { ( ( JsonEntity ) value ) . removePropertyChangeListener ( propListener ) ; } firePropertyChange ( "#" + index , value , null ) ; }
Removes a value from the receiver s collection
10,546
public void replace ( V oldValue , V newValue ) { if ( values . contains ( oldValue ) ) { int index = values . indexOf ( oldValue ) ; values . remove ( oldValue ) ; values . add ( index , newValue ) ; if ( oldValue instanceof JsonEntity ) { ( ( JsonEntity ) oldValue ) . removePropertyChangeListener ( propListener ) ; } if ( newValue instanceof JsonEntity ) { ( ( JsonEntity ) newValue ) . removePropertyChangeListener ( propListener ) ; } firePropertyChange ( "#" + index , oldValue , newValue ) ; } }
If oldValue exists replaces with newValue
10,547
private void init ( ) { masterLanguage = null ; additionalRootAttrs . clear ( ) ; additionalNamespaces = new ArrayList < > ( ) ; textNodeList . clear ( ) ; parseWarnings . clear ( ) ; }
Reinitializes the instance variables for a new build .
10,548
public void writeXML ( OutputStream outputStream , String encoding , String indent , String lineSeparator ) throws IOException { XMLOutputter outputter = new XMLOutputter ( ) ; Format format = Format . getPrettyFormat ( ) ; format . setEncoding ( encoding ) ; format . setIndent ( indent ) ; format . setLineSeparator ( lineSeparator ) ; outputter . setFormat ( format ) ; outputter . output ( getDocument ( ) , outputStream ) ; }
Serializes the database to the output stream .
10,549
public ITextNode getTextNode ( String key ) { for ( ITextNode node : textNodeList ) { if ( key . equals ( node . getKey ( ) ) ) { return node ; } } return null ; }
Gets the text node for a given key .
10,550
protected void fireTextNodesRemoved ( ITextNode [ ] textNodes , int index ) { for ( IDatabaseListener iDatabaseListener : listeners ) { iDatabaseListener . textNodesRemoved ( this , textNodes , index ) ; } }
Notifies the registered listeners that some text nodes have been removed .
10,551
public void fireValueNodeAdded ( IValueNode valueNode ) { for ( IDatabaseListener iDatabaseListener : listeners ) { iDatabaseListener . valueNodeAdded ( valueNode ) ; } }
Notifies the registered listeners of an addition of a value node . to
10,552
public void fireValueNodeRemoved ( IValueNode valueNode ) { for ( IDatabaseListener iDatabaseListener : listeners ) { iDatabaseListener . valueNodeRemoved ( valueNode ) ; } }
Notifies the registered listeners of a removal of a value node . removed from
10,553
public final synchronized void start ( ) throws IOException { if ( this . acceptor != null ) { if ( this . acceptor . getHandler ( ) == null ) { this . acceptor . setHandler ( new TcpIpHandlerAdapter ( ) ) ; } LaunchingMessageKind . ITCPIP0001 . format ( this . host , this . port ) ; this . acceptor . bind ( new InetSocketAddress ( this . host , this . port ) ) ; } }
Start the TcpIpServer
10,554
public boolean clearDocuments ( ) throws DocumentException { File internalFolder = new File ( this . getDocumentsInternalPath ( ) ) ; File [ ] files = internalFolder . listFiles ( ) ; for ( File file : files ) { if ( file . isDirectory ( ) ) { try { FileUtils . deleteDirectory ( file ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw new DocumentException ( "Unable to delete " + file . getAbsolutePath ( ) ) ; } log . info ( "Folder deleted: {}" , file . getAbsolutePath ( ) ) ; } else { boolean deleted = file . delete ( ) ; if ( deleted ) { log . info ( "File deleted: {}" , file . getAbsolutePath ( ) ) ; } else { log . warn ( "Unable to delete file: {}" , file . getAbsolutePath ( ) ) ; } } } File mapFile = new File ( URI . create ( new StringBuilder ( documentsInternalPath . toString ( ) ) . append ( "/" + MEDIA_TYPE_INDEX ) . toString ( ) ) ) ; if ( mapFile . exists ( ) ) { mapFile . delete ( ) ; } fileMediatypeMap . clear ( ) ; this . getEventBus ( ) . post ( new DocumentsClearedEvent ( new Date ( ) ) ) ; return true ; }
Deletes all the documents in iServe
10,555
private String getFNSignatureFromIContext ( INode node ) { String ret = node . getNodeData ( ) . getName ( ) ; List < INode > children = node . getChildrenList ( ) ; if ( children != null && children . size ( ) > 0 ) { ret += "(" ; for ( INode aChildren : children ) { ret += getFNSignatureFromIContext ( aChildren ) + "," ; } ret = ret . substring ( 0 , ret . length ( ) - 1 ) ; ret += ")" ; } return ret ; }
Creates a function - like tree from the given root node
10,556
public synchronized Launch newLaunch ( final Class < ? > jobClass , ExecutorService executorService ) throws LaunchException { return new Launch ( jobClass , executorService ) ; }
Create a new instance of Launch .
10,557
public void addConverter ( Class < ? > from , Class < ? > to , Converter converter ) { Map toMap = fromMap . get ( from ) ; if ( toMap == null ) { toMap = new HashMap < Class < ? > , Map < Class < ? > , Converter > > ( ) ; fromMap . put ( from , toMap ) ; } toMap . put ( to , converter ) ; }
Converter calls this method to register conversion path .
10,558
public Converter getConverter ( Class < ? > from , Class < ? > to ) { Map < Class < ? > , Converter > toMap = fromMap . get ( from ) ; if ( toMap != null ) { return toMap . get ( to ) ; } else { return null ; } }
Get the desired converter .
10,559
public Object convert ( Class < ? > targetType , Object value ) { if ( value == null ) { return null ; } Converter converter = getConverter ( value . getClass ( ) , targetType ) ; if ( converter == null ) { throw new IllegalArgumentException ( "No converter from " + value . getClass ( ) + " to " + targetType . getName ( ) ) ; } else { return converter . convert ( targetType , value ) ; } }
Do Conversion .
10,560
public Boolean call ( ) { if ( ! this . graphStoreManager . containsGraph ( this . modelUri ) ) { Model model = fetchModel ( this . modelUri , this . syntax ) ; if ( model == null || model . isEmpty ( ) ) { return Boolean . FALSE ; } this . graphStoreManager . putGraph ( this . modelUri , model ) ; } return Boolean . TRUE ; }
Given the model uri this method takes care of retrieving the remote model and any imported documents and uploads them all to the graph store within the same graph . This implementation relies on Jena s embedded support for retrieving ontologies and their imports .
10,561
public < A extends Annotation > A annotation ( Class < A > annoCls ) { return method . getAnnotation ( annoCls ) ; }
Returns this element s annotation for the specified type if such an annotation is present else null .
10,562
private Map < FieldDescriptor , Object > getAllFieldsMutable ( ) { final TreeMap < FieldDescriptor , Object > result = new TreeMap < FieldDescriptor , Object > ( ) ; final Descriptor descriptor = internalGetFieldAccessorTable ( ) . descriptor ; for ( final FieldDescriptor field : descriptor . getFields ( ) ) { if ( field . isRepeated ( ) ) { final List < ? > value = ( List < ? > ) getField ( field ) ; if ( ! value . isEmpty ( ) ) { result . put ( field , value ) ; } } else { if ( hasField ( field ) ) { result . put ( field , getField ( field ) ) ; } } } return result ; }
Internal helper which returns a mutable map .
10,563
@ SuppressWarnings ( "unchecked" ) private static Method getMethodOrDie ( final Class clazz , final String name , final Class ... params ) { try { return clazz . getMethod ( name , params ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( "Generated message class \"" + clazz . getName ( ) + "\" missing method \"" + name + "\"." , e ) ; } }
Calls Class . getMethod and throws a RuntimeException if it fails .
10,564
private static Object invokeOrDie ( final Method method , final Object object , final Object ... params ) { try { return method . invoke ( object , params ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( "Couldn't use Java reflection to implement protocol message " + "reflection." , e ) ; } catch ( InvocationTargetException e ) { final Throwable cause = e . getCause ( ) ; if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else if ( cause instanceof Error ) { throw ( Error ) cause ; } else { throw new RuntimeException ( "Unexpected exception thrown by generated accessor method." , cause ) ; } } }
Calls invoke and throws a RuntimeException if it fails .
10,565
public boolean clearKnowledgeBase ( ) { if ( ! this . graphStoreManager . canBeModified ( ) ) { log . warn ( "The dataset cannot be modified." ) ; return false ; } log . info ( "Clearing knowledge base." ) ; this . graphStoreManager . clearDataset ( ) ; this . getEventBus ( ) . post ( new KnowledgeBaseClearedEvent ( new Date ( ) ) ) ; return true ; }
Deletes all the ontologies from a Knowledge Base . This operation cannot be undone . Use with care .
10,566
private boolean fetchModelsForService ( Service svc ) { boolean result = true ; Set < URI > modelUris = obtainReferencedModelUris ( svc ) ; for ( URI modelUri : modelUris ) { if ( ! this . graphStoreManager . containsGraph ( modelUri ) ) { boolean fetch = true ; if ( this . unreachableModels . containsKey ( modelUri ) ) { Date now = new Date ( ) ; Date lastAttempt = this . unreachableModels . get ( modelUri ) ; long diffHours = ( now . getTime ( ) - lastAttempt . getTime ( ) ) / ( 60 * 60 * 1000 ) % 24 ; fetch = ( diffHours >= 24 ? true : false ) ; } if ( fetch ) { boolean isStored = this . graphStoreManager . fetchAndStore ( modelUri ) ; if ( ! isStored ) { this . unreachableModels . put ( modelUri , new Date ( ) ) ; } else { this . getEventBus ( ) . post ( new OntologyCreatedEvent ( new Date ( ) , modelUri ) ) ; } result = result & isStored ; } } } return result ; }
Given a service this method will fetch and upload the models referred to by the service . This is a synchronous implementation that will therefore wait until its fetched and uploaded .
10,567
private boolean checkFetchingTasks ( Map < URI , Future < Boolean > > concurrentTasks ) { boolean result = true ; Boolean fetched ; for ( URI modelUri : concurrentTasks . keySet ( ) ) { Future < Boolean > f = concurrentTasks . get ( modelUri ) ; try { fetched = f . get ( ) ; result = result && fetched ; if ( fetched && this . unreachableModels . containsKey ( modelUri ) ) { this . unreachableModels . remove ( modelUri ) ; log . info ( "A previously unreachable model has finally been obtained - {}" , modelUri ) ; } if ( ! fetched ) { this . unreachableModels . put ( modelUri , new Date ( ) ) ; log . error ( "Cannot load " + modelUri + ". Marked as invalid" ) ; } } catch ( Exception e ) { log . error ( "There was an error while trying to fetch a remote model" , e ) ; this . unreachableModels . put ( modelUri , new Date ( ) ) ; log . info ( "Added {} to the unreachable models list." , modelUri ) ; result = false ; } } return result ; }
This method checks a set of fetching tasks that are pending to validate their adequate conclusion . For each of the fetching tasks launched we will track the models that were not adequately loaded for ulterior uploading .
10,568
public void handleServiceCreated ( ServiceCreatedEvent event ) { log . debug ( "Processing Service Created Event {}" , event ) ; this . fetchModelsForService ( event . getService ( ) ) ; }
Event Processing of internal changes
10,569
private static boolean traverseTree ( PointerTargetTree syn , PointerTargetNodeList ptnl , Synset source ) { java . util . List MGListsList = syn . toList ( ) ; for ( Object aMGListsList : MGListsList ) { PointerTargetNodeList MGList = ( PointerTargetNodeList ) aMGListsList ; for ( Object aMGList : MGList ) { Synset toAdd = ( ( PointerTargetNode ) aMGList ) . getSynset ( ) ; if ( toAdd . equals ( source ) ) { return true ; } } } for ( Object aPtnl : ptnl ) { Synset toAdd = ( ( PointerTargetNode ) aPtnl ) . getSynset ( ) ; if ( toAdd . equals ( source ) ) { return true ; } } return false ; }
traverses PointerTargetTree .
10,570
private boolean isUnidirestionalList ( RelationshipList list ) { if ( list . size ( ) > 0 ) { try { if ( ( ( AsymmetricRelationship ) list . get ( 0 ) ) . getCommonParentIndex ( ) == 0 ) { return true ; } } catch ( java . lang . IndexOutOfBoundsException ex ) { return true ; } } return false ; }
Checks unidirectionality of semantic relations in the list .
10,571
public void add ( int idx , int ele ) { ensureCapacity ( size + 1 ) ; System . arraycopy ( data , idx , data , idx + 1 , size - idx ) ; data [ idx ] = ele ; size ++ ; }
Adds an element to the List . All following elements are moved up by one index .
10,572
public void remove ( int idx ) { size -- ; System . arraycopy ( data , idx + 1 , data , idx , size - idx ) ; }
Removes an element from the List . All following elements are moved down by one index .
10,573
public int indexOf ( int ele ) { int i ; for ( i = 0 ; i < size ; i ++ ) { if ( data [ i ] == ele ) { return i ; } } return - 1 ; }
Searches an element .
10,574
public static Object createInstanceNoArgs ( Class < ? > clazz ) { assertReflectionAccessor ( ) ; try { return accessor . newInstance ( clazz ) ; } catch ( Exception e ) { throw SneakyException . sneakyThrow ( e ) ; } }
Creates an instance of this class through reflection . Class must have a no - args constructor . Any exceptions thrown during the process will be re - thrown as unchecked .
10,575
public static Class < ? > [ ] getDeclaredClasses ( Class < ? > clazz ) { assertReflectionAccessor ( ) ; try { return accessor . getDeclaredClasses ( clazz ) ; } catch ( Exception e ) { throw SneakyException . sneakyThrow ( e ) ; } }
Get all inner classes and interfaces declared by the given class .
10,576
public static < T > ReflectionConstructor < T > getDeclaredConstructor ( Class < T > clazz , Class < ? > ... parameterTypes ) { assertReflectionAccessor ( ) ; try { return accessor . getDeclaredConstructor ( clazz , parameterTypes ) ; } catch ( Exception e ) { throw SneakyException . sneakyThrow ( e ) ; } }
Returns a constructor of the given class that takes the given parameter types .
10,577
public static ReflectionMethod getNoArgsMethod ( Class < ? > clazz , String methodName ) { assertReflectionAccessor ( ) ; try { return accessor . getDeclaredMethod ( clazz , methodName , NO_ARGS_TYPE ) ; } catch ( Exception e ) { throw SneakyException . sneakyThrow ( e ) ; } }
Returns a method with the provided name that takes no - args .
10,578
public static boolean isAssignableFrom ( Class < ? > c1 , Class < ? > c2 ) { assertReflectionAccessor ( ) ; return accessor . isAssignableFrom ( c1 , c2 ) ; }
Determines if the class or interface represented by first Class parameter is either the same as or is a superclass or superinterface of the class or interface represented by the second Class parameter .
10,579
public static void assertReturnValue ( ReflectionMethod method , Class < ? > expectedReturnType ) { final Class < ? > returnType = method . getReturnType ( ) ; if ( returnType != expectedReturnType ) { final String message = "Class='" + method . getDeclaringClass ( ) + "', method='" + method . getName ( ) + "': Must return a value of type '" + expectedReturnType + "'!" ; throw new IllegalArgumentException ( message ) ; } }
Assert that the given method returns the expected return type .
10,580
public static void assertNoParameters ( ReflectionMethod method ) { final List < ReflectionParameter > parameters = method . getParameters ( ) ; if ( ! parameters . isEmpty ( ) ) { final String message = "Class='" + method . getDeclaringClass ( ) + "', method='" + method . getName ( ) + "': Must take no parameters!" ; throw new IllegalArgumentException ( message ) ; } }
Assert that the given method takes no parameters .
10,581
private INode findRoot ( ) { for ( INode node : nodes . values ( ) ) { if ( ! node . hasParent ( ) && ! BASE_NODE . equals ( node . getNodeData ( ) . getName ( ) ) ) { return node ; } } return null ; }
org . xml . sax . helpers . DefaultHandler methods re - implementation end
10,582
public static < T > void setInjectorInstance ( Class < T > injectorClass , T injectorInstance ) { if ( injectorInstance == null ) { injectorsMap . remove ( injectorClass ) ; } injectorsMap . put ( injectorClass , injectorInstance ) ; }
Sets the injector instance to be used internally by the framework to inject views . If an injector instance is not declared here a new instance is created every time a view is invoked .
10,583
@ SuppressWarnings ( "unchecked" ) public static < T > T getInjectorInstance ( Class < T > injectorClass ) { return ( T ) injectorsMap . get ( injectorClass ) ; }
Gets the current injector instance associated to the injector class literal . This method is called internally by the framework to determine which injector instance should be used when injecting views .
10,584
private Connection getTargetConnection ( Method operation ) throws SQLException { if ( this . target == null ) { boolean readOnly = MasterSlaveInterceptor . isReadOnly ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Connecting to database for operation '" + operation . getName ( ) + "'" ) ; } DruidDataSource ds = router . determineTargetDataSource ( readOnly ) ; TraceContext . get ( ) . setServerName ( router . getConfigName ( ) ) . setUrl ( extractHost ( ds . getUrl ( ) ) ) ; this . target = ( this . username != null ) ? ds . getConnection ( this . username , this . password ) : ds . getConnection ( ) ; if ( this . readOnly ) { this . target . setReadOnly ( true ) ; } if ( this . transactionIsolation != null ) { this . target . setTransactionIsolation ( this . transactionIsolation ) ; } if ( this . autoCommit != null && this . autoCommit != this . target . getAutoCommit ( ) ) { this . target . setAutoCommit ( this . autoCommit ) ; } } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Using existing database connection for operation '" + operation . getName ( ) + "'" ) ; } } return this . target ; }
Return the target Connection fetching it and initializing it if necessary .
10,585
public static void check ( BioCDocument document ) { String text = BioCUtils . getText ( document ) ; checkAnnotations ( document . getAnnotations ( ) , text , 0 , BioCLog . log ( document ) ) ; for ( BioCRelation relation : document . getRelations ( ) ) { for ( BioCNode node : relation . getNodes ( ) ) { checkArgument ( document . getAnnotation ( node . getRefid ( ) ) . isPresent ( ) , "Cannot find node %s in relation %s\n" + "Location: %s" , node , relation , BioCLog . log ( document ) ) ; } } for ( BioCPassage passage : document . getPassages ( ) ) { text = BioCUtils . getText ( passage ) ; checkAnnotations ( passage . getAnnotations ( ) , text , passage . getOffset ( ) , BioCLog . log ( document , passage ) ) ; for ( BioCRelation relation : passage . getRelations ( ) ) { for ( BioCNode node : relation . getNodes ( ) ) { checkArgument ( passage . getAnnotation ( node . getRefid ( ) ) . isPresent ( ) , "Cannot find node %s in relation %s\n" + "Location: %s" , node , relation , BioCLog . log ( document , passage ) ) ; } } for ( BioCSentence sentence : passage . getSentences ( ) ) { checkAnnotations ( sentence . getAnnotations ( ) , sentence . getText ( ) . get ( ) , sentence . getOffset ( ) , BioCUtils . getXPathString ( document , passage , sentence ) ) ; for ( BioCRelation relation : sentence . getRelations ( ) ) { for ( BioCNode node : relation . getNodes ( ) ) { checkArgument ( sentence . getAnnotation ( node . getRefid ( ) ) . isPresent ( ) , "Cannot find node %s in relation %s\n" + " Location: %s" , node , relation , BioCUtils . getXPathString ( document , passage , sentence ) ) ; } } } } }
Checks annotations and ie .
10,586
private boolean isRedundant ( IContextMapping < INode > mapping , IMappingElement < INode > e ) { switch ( e . getRelation ( ) ) { case IMappingElement . LESS_GENERAL : { if ( verifyCondition1 ( mapping , e ) ) { return true ; } break ; } case IMappingElement . MORE_GENERAL : { if ( verifyCondition2 ( mapping , e ) ) { return true ; } break ; } case IMappingElement . DISJOINT : { if ( verifyCondition3 ( mapping , e ) ) { return true ; } break ; } case IMappingElement . EQUIVALENCE : { if ( verifyCondition4 ( mapping , e ) ) { return true ; } break ; } default : { return false ; } } return false ; }
Checks the relation between source and target is redundant or not for minimal mapping .
10,587
public void setToken ( String completeToken ) { clearParameters ( ) ; id = "" ; if ( completeToken != null ) { StringBuilder builder = new StringBuilder ( ) ; char [ ] chs = completeToken . toCharArray ( ) ; String currentKey = null ; TokenParseState state = TokenParseState . PARSING_ID ; for ( char ch : chs ) { switch ( state ) { case PARSING_ID : if ( ch == '&' ) { state = TokenParseState . PARSING_KEY ; id = builder . toString ( ) ; builder . delete ( 0 , builder . length ( ) ) ; } else { builder . append ( ch ) ; } break ; case PARSING_KEY : if ( ch == '=' ) { state = TokenParseState . PARSING_VALUE ; currentKey = builder . toString ( ) ; if ( ! currentKey . isEmpty ( ) ) { parameters . put ( currentKey , "" ) ; builder . delete ( 0 , builder . length ( ) ) ; } } else if ( ch == '&' ) { currentKey = builder . toString ( ) ; if ( ! currentKey . isEmpty ( ) ) { parameters . put ( currentKey , "" ) ; builder . delete ( 0 , builder . length ( ) ) ; } } else { builder . append ( ch ) ; } break ; case PARSING_VALUE : if ( ch == '\'' ) { state = TokenParseState . PARSING_COMPLEX_VALUE ; } else if ( ch == '&' ) { state = TokenParseState . PARSING_KEY ; parameters . put ( currentKey , builder . toString ( ) ) ; builder . delete ( 0 , builder . length ( ) ) ; } else { builder . append ( ch ) ; } break ; case PARSING_COMPLEX_VALUE : if ( ch == '\'' ) { state = TokenParseState . PARSED_COMPLEX_VALUE ; parameters . put ( currentKey , builder . toString ( ) ) ; builder . delete ( 0 , builder . length ( ) ) ; } else { builder . append ( ch ) ; } break ; case PARSED_COMPLEX_VALUE : if ( ch == '&' ) { state = TokenParseState . PARSING_KEY ; } break ; } } switch ( state ) { case PARSING_ID : id = builder . toString ( ) ; break ; case PARSING_KEY : currentKey = builder . toString ( ) ; if ( ! currentKey . isEmpty ( ) ) { parameters . put ( currentKey , "" ) ; } break ; case PARSING_COMPLEX_VALUE : case PARSING_VALUE : String value = builder . toString ( ) ; if ( ! value . isEmpty ( ) && currentKey != null ) { parameters . put ( currentKey , value ) ; } break ; default : break ; } } }
Sets the current token causing it to parse the parameters and the tokenId .
10,588
public < T extends Composite < S > > T copy ( ) { try { String fullJSON = fullMapper . writeValueAsString ( this ) ; @ SuppressWarnings ( "unchecked" ) T copy = ( T ) fullMapper . readValue ( fullJSON , getClass ( ) ) ; return copy ; } catch ( IOException e ) { throw new RuntimeException ( "The attempted copy of an object failed." , e ) ; } }
This method should work for all objects . However it is very inefficient and should only be used sparingly and for unit testing .
10,589
protected void addSerializableClass ( Class < ? > serializable , Class < ? > mixin ) { safeMapper . addMixIn ( serializable , mixin ) ; fullMapper . addMixIn ( serializable , mixin ) ; }
This protected method allows a subclass to add to the mappers a class type that can be serialized using mixin class .
10,590
private IContext buildCLabs ( IContext context ) throws ContextPreprocessorException { int counter = 0 ; int total = context . getRoot ( ) . getDescendantCount ( ) + 1 ; int reportInt = ( total / 20 ) + 1 ; for ( Iterator < INode > i = context . getNodes ( ) ; i . hasNext ( ) ; ) { processNode ( i . next ( ) ) ; counter ++ ; if ( ( SMatchConstants . LARGE_TREE < total ) && ( 0 == ( counter % reportInt ) ) && log . isEnabledFor ( Level . INFO ) ) { log . info ( 100 * counter / total + "%" ) ; } } return context ; }
Constructs cLabs for all nodes of the context .
10,591
private boolean isTokenMeaningful ( String token ) { token = token . trim ( ) ; return andWords . contains ( token ) || orWords . contains ( token ) || token . length ( ) >= 3 ; }
Checks the token is meaningful or not .
10,592
private List < String > complexWordsRecognition ( String token ) throws ContextPreprocessorException { List < String > result = new ArrayList < String > ( ) ; try { List < ISense > senses = new ArrayList < ISense > ( ) ; int i = 0 ; String start = null ; String end = null ; String toCheck = null ; boolean flag = false ; boolean multiword = false ; while ( ( i < token . length ( ) - 1 ) && ( 0 == senses . size ( ) ) ) { i ++ ; start = token . substring ( 0 , i ) ; end = token . substring ( i , token . length ( ) ) ; toCheck = start + ' ' + end ; senses = linguisticOracle . getSenses ( toCheck ) ; if ( 0 == senses . size ( ) ) { toCheck = start + '-' + end ; senses = linguisticOracle . getSenses ( toCheck ) ; } if ( 0 < senses . size ( ) ) { multiword = true ; break ; } else { if ( ( start . length ( ) > 3 ) && ( end . length ( ) > 3 ) ) { senses = linguisticOracle . getSenses ( start ) ; if ( 0 < senses . size ( ) ) { senses = linguisticOracle . getSenses ( end ) ; if ( 0 < senses . size ( ) ) { flag = true ; break ; } } } } } if ( multiword ) { result . add ( toCheck ) ; return result ; } if ( flag ) { result . add ( start ) ; result . add ( end ) ; return result ; } return result ; } catch ( LinguisticOracleException e ) { final String errMessage = e . getClass ( ) . getSimpleName ( ) + ": " + e . getMessage ( ) ; log . error ( errMessage , e ) ; throw new ContextPreprocessorException ( errMessage , e ) ; } }
Finds out if the input token is a complex word or not using WordNet . Tries to insert spaces and dash between all characters and searches for the result to be in WordNet .
10,593
private static String replacePunctuation ( String lemma ) { lemma = lemma . replace ( "," , " , " ) ; lemma = lemma . replace ( '.' , ' ' ) ; lemma = lemma . replace ( '\'' , ' ' ) ; lemma = lemma . replace ( '(' , ' ' ) ; lemma = lemma . replace ( ')' , ' ' ) ; lemma = lemma . replace ( ':' , ' ' ) ; lemma = lemma . replace ( ";" , " ; " ) ; return lemma ; }
Replaces punctuation by spaces .
10,594
private boolean isNumber ( String in1 ) { for ( StringTokenizer stringTokenizer = new StringTokenizer ( in1 , numberCharacters ) ; stringTokenizer . hasMoreTokens ( ) ; ) { return false ; } return true ; }
Checks whether input string contains a number or not .
10,595
private int extendedIndexOf ( List < String > vec , String str , int init_pos ) throws ContextPreprocessorException { try { for ( int i = init_pos ; i < vec . size ( ) ; i ++ ) { String vel = vec . get ( i ) ; if ( vel . equals ( str ) ) { return i ; } else if ( vel . indexOf ( str ) == 0 ) { if ( linguisticOracle . isEqual ( vel , str ) ) { vec . add ( i , str ) ; vec . remove ( i + 1 ) ; return i ; } } } return - 1 ; } catch ( LinguisticOracleException e ) { final String errMessage = e . getClass ( ) . getSimpleName ( ) + ": " + e . getMessage ( ) ; log . error ( errMessage , e ) ; throw new ContextPreprocessorException ( errMessage , e ) ; } }
An extension of the list indexOf method which uses approximate comparison of the words as elements of the List .
10,596
public static String shortDebugString ( final MessageOrBuilder message ) { try { final StringBuilder sb = new StringBuilder ( ) ; SINGLE_LINE_PRINTER . print ( message , new TextGenerator ( sb ) ) ; return sb . toString ( ) . trim ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }
Generates a human readable form of this message useful for debugging and other purposes with no newline characters .
10,597
public static String shortDebugString ( final UnknownFieldSet fields ) { try { final StringBuilder sb = new StringBuilder ( ) ; SINGLE_LINE_PRINTER . printUnknownFields ( fields , new TextGenerator ( sb ) ) ; return sb . toString ( ) . trim ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }
Generates a human readable form of the unknown fields useful for debugging and other purposes with no newline characters .
10,598
public static void printUnknownFieldValue ( final int tag , final Object value , final Appendable output ) throws IOException { printUnknownFieldValue ( tag , value , new TextGenerator ( output ) ) ; }
Outputs a textual representation of the value of an unknown field .
10,599
private static String unsignedToString ( final long value ) { if ( value >= 0 ) { return Long . toString ( value ) ; } else { return BigInteger . valueOf ( value & 0x7FFFFFFFFFFFFFFFL ) . setBit ( 63 ) . toString ( ) ; } }
Convert an unsigned 64 - bit integer to a string .