idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
4,300 | private void createDestinations ( ) throws MessagingException { try { Enumeration < ? > propertyNames = m_connectionProperties . keys ( ) ; while ( propertyNames . hasMoreElements ( ) ) { String propertyName = ( String ) propertyNames . nextElement ( ) ; if ( propertyName . startsWith ( "topic." ) ) { String destinationName = m_connectionProperties . getProperty ( propertyName ) ; m_jmsManager . createDestination ( destinationName , DestinationType . Topic ) ; } else if ( propertyName . startsWith ( "queue." ) ) { String destinationName = m_connectionProperties . getProperty ( propertyName ) ; m_jmsManager . createDestination ( destinationName , DestinationType . Queue ) ; } } List < Destination > destinations = m_jmsManager . getDestinations ( ) ; if ( destinations . size ( ) == 0 ) { throw new MessagingException ( "No destinations available for " + "subscription, make sure that there is at least one topic " + "or queue specified in the connection properties." ) ; } for ( Destination destination : destinations ) { if ( m_durable && ( destination instanceof Topic ) ) { m_jmsManager . listenDurable ( ( Topic ) destination , m_messageSelector , this , null ) ; } else { m_jmsManager . listen ( destination , m_messageSelector , this ) ; } } } catch ( MessagingException me ) { logger . error ( "MessagingException encountered attempting to start " + "Messaging Client: " + m_clientId + ". Exception message: " + me . getMessage ( ) , me ) ; throw me ; } } | Creates topics and queues and starts listeners |
4,301 | public void stop ( boolean unsubscribe ) throws MessagingException { try { if ( unsubscribe ) { m_jmsManager . unsubscribeAllDurable ( ) ; } m_jmsManager . close ( ) ; m_jmsManager = null ; m_connected = false ; } catch ( MessagingException me ) { logger . error ( "Messaging Exception encountered attempting to stop " + "Messaging Client: " + m_clientId + ". Exception message: " + me . getMessage ( ) , me ) ; throw me ; } } | Stops the MessagingClient shuts down connections . If the unsubscribe parameter is set to true all durable subscriptions will be removed . |
4,302 | private void upgradeIfNeeded ( File oldPidGenDir ) throws IOException { if ( oldPidGenDir != null && oldPidGenDir . isDirectory ( ) ) { String [ ] names = oldPidGenDir . list ( ) ; Arrays . sort ( names ) ; if ( names . length > 0 ) { BufferedReader in = new BufferedReader ( new InputStreamReader ( new FileInputStream ( new File ( oldPidGenDir , names [ names . length - 1 ] ) ) ) ) ; String lastLine = null ; String line ; while ( ( line = in . readLine ( ) ) != null ) { lastLine = line ; } in . close ( ) ; if ( lastLine != null ) { String [ ] parts = lastLine . split ( "|" ) ; if ( parts . length == 2 ) { neverGeneratePID ( parts [ 0 ] ) ; } } } } } | Read the highest value from the old pidGen directory if it exists and ensure it is never used . |
4,303 | public synchronized PID generatePID ( String namespace ) throws IOException { int i = getHighestID ( namespace ) ; i ++ ; try { m_lastPID = new PID ( namespace + ":" + i ) ; } catch ( MalformedPIDException e ) { throw new IOException ( e . getMessage ( ) ) ; } setHighestID ( namespace , i ) ; return m_lastPID ; } | Generate a new pid that is guaranteed to be unique within the given namespace . |
4,304 | public synchronized void neverGeneratePID ( String pid ) throws IOException { logger . debug ( "Never generating PID: {}" , pid ) ; try { PID p = new PID ( pid ) ; String ns = p . getNamespaceId ( ) ; int id = Integer . parseInt ( p . getObjectId ( ) ) ; if ( id > getHighestID ( ns ) ) { setHighestID ( ns , id ) ; } } catch ( MalformedPIDException mpe ) { throw new IOException ( mpe . getMessage ( ) ) ; } catch ( NumberFormatException nfe ) { } } | Cause the given PID to never be generated by the PID generator . |
4,305 | private int getHighestID ( String namespace ) { Integer i = ( Integer ) m_highestID . get ( namespace ) ; if ( i == null ) { return 0 ; } return i . intValue ( ) ; } | Gets the highest id ever used for the given namespace . |
4,306 | private void setHighestID ( String namespace , int id ) throws IOException { logger . debug ( "Setting highest ID for {} to {}" , namespace , id ) ; m_highestID . put ( namespace , new Integer ( id ) ) ; Connection conn = null ; try { conn = m_connectionPool . getReadWriteConnection ( ) ; SQLUtility . replaceInto ( conn , "pidGen" , new String [ ] { "namespace" , "highestID" } , new String [ ] { namespace , "" + id } , "namespace" , new boolean [ ] { false , true } ) ; } catch ( SQLException sqle ) { throw new IOException ( "Error setting highest id for " + "namespace in db: " + sqle . getMessage ( ) ) ; } finally { if ( conn != null ) { m_connectionPool . free ( conn ) ; } } } | Sets the highest id ever used for the given namespace . |
4,307 | protected synchronized JournalInputFile openNextFile ( ) throws JournalException { while ( open ) { JournalInputFile nextFile = super . openNextFile ( ) ; if ( nextFile != null ) { return nextFile ; } try { wait ( pollingIntervalMillis ) ; } catch ( InterruptedException e ) { } } return null ; } | Ask for a new file using the superclass method but if none is found wait for a while and ask again . This will continue until we get a server shutdown signal . |
4,308 | public static String oneFromFile ( File file , String ingestFormat , FedoraAPIAMTOM targetRepoAPIA , FedoraAPIMMTOM targetRepoAPIM , String logMessage ) throws Exception { LAST_PATH = file . getPath ( ) ; String pid = AutoIngestor . ingestAndCommit ( targetRepoAPIA , targetRepoAPIM , new FileInputStream ( file ) , ingestFormat , getMessage ( logMessage , file ) ) ; return pid ; } | if logMessage is null will use original path in logMessage |
4,309 | public static String oneFromRepository ( FedoraAPIAMTOM sourceRepoAPIA , FedoraAPIMMTOM sourceRepoAPIM , String sourceExportFormat , String pid , FedoraAPIAMTOM targetRepoAPIA , FedoraAPIMMTOM targetRepoAPIM , String logMessage ) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; AutoExporter . export ( sourceRepoAPIA , sourceRepoAPIM , pid , sourceExportFormat , "migrate" , out ) ; String ingestFormat = sourceExportFormat ; if ( sourceExportFormat . equals ( METS_EXT1_0_LEGACY ) ) { ingestFormat = METS_EXT1_0 . uri ; } else if ( sourceExportFormat . equals ( FOXML1_0_LEGACY ) ) { ingestFormat = FOXML1_0 . uri ; } String realLogMessage = logMessage ; if ( realLogMessage == null ) { realLogMessage = "Ingested from source repository with pid " + pid ; } return AutoIngestor . ingestAndCommit ( targetRepoAPIA , targetRepoAPIM , new ByteArrayInputStream ( out . toByteArray ( ) ) , ingestFormat , realLogMessage ) ; } | if logMessage is null will make informative one up |
4,310 | public static synchronized TinyBus from ( Context context ) { final TinyBusDepot depot = TinyBusDepot . get ( context ) ; TinyBus bus = depot . getBusInContext ( context ) ; if ( bus == null ) { bus = depot . createBusInContext ( context ) ; } return bus ; } | Use this method to get a bus instance bound to the given context . If instance does not yet exist in the context a new instance will be created . Otherwise existing instance gets returned . |
4,311 | public String encode ( ) { ReadableByteArrayOutputStream out = new ReadableByteArrayOutputStream ( ) ; encode ( out ) ; return out . toString ( ) ; } | Simple encoding method that returns the text - encoded version of this attribute with no formatting . |
4,312 | private XmlQueryExpression getQuery ( Map < String , Collection < AttributeBean > > attributeMap , XmlQueryContext context , int r ) throws XmlException { StringBuilder sb = new StringBuilder ( 64 * attributeMap . size ( ) ) ; for ( Collection < AttributeBean > attributeBeans : attributeMap . values ( ) ) { sb . append ( attributeBeans . size ( ) + ":" ) ; for ( AttributeBean bean : attributeBeans ) { sb . append ( bean . getValues ( ) . size ( ) + "-" ) ; } } String hash = sb . toString ( ) + r ; XmlQueryExpression result = m_queries . get ( hash ) ; if ( result != null ) { return result ; } String query = createQuery ( attributeMap ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Query [{}]:\n{}" , hash , query ) ; } result = m_dbXmlManager . manager . prepare ( query , context ) ; m_queries . put ( hash , result ) ; return result ; } | Either returns a query that has previously been generated or generates a new one if it has not . |
4,313 | private String createQuery ( Map < String , Collection < AttributeBean > > attributeMap ) { StringBuilder sb = new StringBuilder ( 256 ) ; sb . append ( "collection('" ) ; sb . append ( m_dbXmlManager . CONTAINER ) ; sb . append ( "')" ) ; getXpath ( attributeMap , sb ) ; return sb . toString ( ) ; } | Given a set of attributes this method generates a DBXML XPath query based on those attributes to extract a subset of policies from the database . |
4,314 | private XmlDocument makeDocument ( String name , String document ) throws XmlException , PolicyIndexException { Map < String , String > metadata = m_utils . getDocumentMetadata ( document . getBytes ( ) ) ; XmlDocument doc = m_dbXmlManager . manager . createDocument ( ) ; String docName = name ; if ( docName == null || docName . isEmpty ( ) ) { docName = metadata . get ( "PolicyId" ) ; } if ( docName == null || docName . isEmpty ( ) ) { throw new PolicyIndexException ( "Could not extract PolicyID from document." ) ; } doc . setMetaData ( "metadata" , "PolicyId" , new XmlValue ( XmlValue . STRING , docName ) ) ; doc . setContent ( document ) ; doc . setName ( docName ) ; String item = null ; item = metadata . get ( "anySubject" ) ; if ( item != null ) { doc . setMetaData ( "metadata" , "anySubject" , new XmlValue ( XmlValue . STRING , item ) ) ; } item = metadata . get ( "anyResource" ) ; if ( item != null ) { doc . setMetaData ( "metadata" , "anyResource" , new XmlValue ( XmlValue . STRING , item ) ) ; } item = metadata . get ( "anyAction" ) ; if ( item != null ) { doc . setMetaData ( "metadata" , "anyAction" , new XmlValue ( XmlValue . STRING , item ) ) ; } item = metadata . get ( "anyEnvironment" ) ; if ( item != null ) { doc . setMetaData ( "metadata" , "anyEnvironment" , new XmlValue ( XmlValue . STRING , item ) ) ; } return doc ; } | Creates an instance of an XmlDocument for storage in the database . |
4,315 | public Iterator < String > list ( ) { try { final Enumeration < String > keys = pathRegistry . keys ( ) ; return new Iterator < String > ( ) { public boolean hasNext ( ) { return keys . hasMoreElements ( ) ; } public String next ( ) { return keys . nextElement ( ) ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } catch ( LowlevelStorageException e ) { throw new FaultException ( e ) ; } } | Gets the keys of all stored items . |
4,316 | public final long add ( String pid , InputStream content ) throws LowlevelStorageException { String filePath ; File file = null ; if ( pathRegistry . exists ( pid ) ) { throw new ObjectAlreadyInLowlevelStorageException ( pid ) ; } filePath = pathAlgorithm . get ( pid ) ; if ( filePath == null || filePath . equals ( "" ) ) { throw new LowlevelStorageException ( true , "null path from algorithm for pid " + pid ) ; } try { file = new File ( filePath ) ; } catch ( Exception eFile ) { throw new LowlevelStorageException ( true , "couldn't make File for " + filePath , eFile ) ; } fileSystem . write ( file , content ) ; pathRegistry . put ( pid , filePath ) ; return file . length ( ) ; } | add to lowlevel store content of Fedora object not already in lowlevel store |
4,317 | public final long replace ( String pid , InputStream content ) throws LowlevelStorageException { File file = getFile ( pid ) ; fileSystem . rewrite ( file , content ) ; return file . length ( ) ; } | replace into low - level store content of Fedora object already in lowlevel store |
4,318 | public final InputStream retrieve ( String pid ) throws LowlevelStorageException { File file = getFile ( pid ) ; return fileSystem . read ( file ) ; } | get content of Fedora object from low - level store |
4,319 | public final long getSize ( String pid ) throws LowlevelStorageException { File file = getFile ( pid ) ; return file . length ( ) ; } | get size of datastream |
4,320 | public final void remove ( String pid ) throws LowlevelStorageException { File file = getFile ( pid ) ; pathRegistry . remove ( pid ) ; fileSystem . delete ( file ) ; } | remove Fedora object from low - level store |
4,321 | public AbstractPolicy getPolicy ( EvaluationCtx eval ) throws TopLevelPolicyException , PolicyIndexException { Map < String , AbstractPolicy > potentialPolicies = m_policyIndex . getPolicies ( eval , m_policyFinder ) ; logger . debug ( "Obtained policies: {}" , potentialPolicies . size ( ) ) ; AbstractPolicy policy = matchPolicies ( eval , potentialPolicies ) ; logger . debug ( "Matched policies and created abstract policy." ) ; return policy ; } | Obtains a policy or policy set of matching policies from the policy store . If more than one policy is returned it creates a dynamic policy set that contains all the applicable policies . |
4,322 | private AbstractPolicy matchPolicies ( EvaluationCtx eval , Map < String , AbstractPolicy > policyList ) throws TopLevelPolicyException { Map < String , AbstractPolicy > list = new HashMap < String , AbstractPolicy > ( ) ; for ( String policyId : policyList . keySet ( ) ) { AbstractPolicy policy = policyList . get ( policyId ) ; MatchResult match = policy . match ( eval ) ; int result = match . getResult ( ) ; if ( result == MatchResult . INDETERMINATE ) { throw new TopLevelPolicyException ( match . getStatus ( ) ) ; } if ( result == MatchResult . MATCH ) { if ( m_combiningAlg == null && list . size ( ) > 0 ) { ArrayList < String > code = new ArrayList < String > ( ) ; code . add ( Status . STATUS_PROCESSING_ERROR ) ; Status status = new Status ( code , "too many applicable" + " top-level policies" ) ; throw new TopLevelPolicyException ( status ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Matched policy: {}" , policyId ) ; } list . put ( policyId , policy ) ; } } switch ( list . size ( ) ) { case 0 : return null ; case 1 : Iterator < AbstractPolicy > i = list . values ( ) . iterator ( ) ; AbstractPolicy p = i . next ( ) ; return p ; default : return new PolicySet ( parentPolicyId , m_combiningAlg , m_target , new ArrayList < AbstractPolicy > ( list . values ( ) ) ) ; } } | Given and Evaluation Context and a list of potential policies this method matches each policy against the Evaluation Context and extracts only the ones that match . If there is more than one policy a new dynamic policy set is created and returned . Otherwise the policy that is found is returned . |
4,323 | public void actionPerformed ( ActionEvent e ) { if ( foxml11Button . isSelected ( ) ) { fmt_chosen = FOXML1_1 . uri ; } else if ( foxml10Button . isSelected ( ) ) { fmt_chosen = FOXML1_0 . uri ; } else if ( mets11Button . isSelected ( ) ) { fmt_chosen = METS_EXT1_1 . uri ; } else if ( mets10Button . isSelected ( ) ) { fmt_chosen = METS_EXT1_0 . uri ; } else if ( atomButton . isSelected ( ) ) { fmt_chosen = ATOM1_1 . uri ; } else if ( atomZipButton . isSelected ( ) ) { fmt_chosen = ATOM_ZIP1_1 . uri ; } } | Listens to the radio buttons . |
4,324 | protected RDFName getStateResource ( String state ) throws ResourceIndexException { if ( state == null ) { throw new ResourceIndexException ( "State cannot be null" ) ; } else if ( state . equals ( "A" ) ) { return MODEL . ACTIVE ; } else if ( state . equals ( "D" ) ) { return MODEL . DELETED ; } else if ( state . equals ( "I" ) ) { return MODEL . INACTIVE ; } else { throw new ResourceIndexException ( "Unrecognized state: " + state ) ; } } | Helper methods for creating RDF components |
4,325 | protected void add ( SubjectNode subject , RDFName predicate , ObjectNode object , Set < Triple > set ) throws ResourceIndexException { set . add ( new SimpleTriple ( subject , predicate , object ) ) ; } | Helper methods for adding triples |
4,326 | private static void enc ( String in , StringBuilder out ) { for ( int i = 0 ; i < in . length ( ) ; i ++ ) { enc ( in . charAt ( i ) , out ) ; } } | Appends an XML - appropriate encoding of the given String to the given StringBuffer . |
4,327 | private static void enc ( char in , StringBuilder out ) { if ( in == '&' ) { out . append ( "&" ) ; } else if ( in == '<' ) { out . append ( "<" ) ; } else if ( in == '>' ) { out . append ( ">" ) ; } else if ( in == '\"' ) { out . append ( """ ) ; } else if ( in == '\'' ) { out . append ( "'" ) ; } else { out . append ( in ) ; } } | Appends an XML - appropriate encoding of the given character to the given StringBuffer . |
4,328 | public static Server getServer ( ) throws InitializationException { if ( server == null ) { server = RebuildServer . getRebuildInstance ( new File ( Constants . FEDORA_HOME ) ) ; } return server ; } | Gets the instance of the server appropriate for rebuilding . If no such instance has been initialized yet initialize one . |
4,329 | public final void remove ( final String pid ) { mapLock . lock ( ) ; cacheMap . remove ( pid ) ; mapLock . unlock ( ) ; } | remove an entry from the cache |
4,330 | public final void removeExpired ( ) { mapLock . lock ( ) ; Iterator < Entry < String , TimestampedCacheEntry < DOReader > > > entries = cacheMap . entrySet ( ) . iterator ( ) ; if ( entries . hasNext ( ) ) { long now = System . currentTimeMillis ( ) ; while ( entries . hasNext ( ) ) { Entry < String , TimestampedCacheEntry < DOReader > > entry = entries . next ( ) ; TimestampedCacheEntry < DOReader > e = entry . getValue ( ) ; long age = e . ageAt ( now ) ; if ( age > ( maxSeconds * 1000 ) ) { entries . remove ( ) ; String pid = entry . getKey ( ) ; LOG . debug ( "removing entry {} after {} milliseconds" , pid , age ) ; } } } mapLock . unlock ( ) ; } | remove expired entries from the cache |
4,331 | public void close ( ) { if ( this . m_stream != null ) { try { this . m_stream . close ( ) ; this . m_stream = null ; } catch ( IOException e ) { logger . warn ( "Error closing stream" , e ) ; } } } | Closes the underlying stream if it s not already closed . |
4,332 | public void get ( String url , OutputStream out ) throws IOException { InputStream in = get ( url ) ; StreamUtility . pipeStream ( in , out , 4096 ) ; } | Get data via HTTP and write it to an OutputStream following redirects and supplying credentials if the host is the Fedora server . |
4,333 | public void writeJournalEntry ( CreatorJournalEntry journalEntry ) throws JournalException { try { super . writeJournalEntry ( journalEntry , writer ) ; writer . flush ( ) ; } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } } | Every journal entry just gets added to the file . |
4,334 | public void shutdown ( ) throws JournalException { try { if ( fileHasHeader ) { super . writeDocumentTrailer ( writer ) ; } writer . close ( ) ; out . close ( ) ; } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } catch ( IOException e ) { throw new JournalException ( e ) ; } } | Add the document trailer and close the journal file . |
4,335 | private Map < String , String > parseArgsIntoMap ( String [ ] args ) { Map < String , String > parms = new HashMap < String , String > ( ) ; for ( int i = 0 ; i < args . length ; i ++ ) { String key = args [ i ] ; if ( ! isKeyword ( key ) ) { throw new ValidatorProcessUsageException ( "'" + key + "' is not a keyword." ) ; } if ( ! ALL_PARAMETERS . contains ( key ) ) { throw new ValidatorProcessUsageException ( "'" + key + "' is not a recognized keyword." ) ; } if ( i >= args . length - 1 ) { parms . put ( key , null ) ; } else { String value = args [ i + 1 ] ; if ( isKeyword ( value ) ) { parms . put ( key , null ) ; } else { parms . put ( key , value ) ; i ++ ; } } } return parms ; } | Decide which of the command line arguments are keywords and which are values and build a map to hold them . |
4,336 | private URL getRequiredUrlParameter ( String keyword , Map < String , String > parms ) { String urlString = getRequiredParameter ( keyword , parms ) ; try { return new URL ( urlString ) ; } catch ( MalformedURLException e ) { throw new ValidatorProcessUsageException ( "Value '" + urlString + "' for parameter '" + keyword + "' is not a valid URL: " + e . getMessage ( ) ) ; } } | Get the requested parameter from the map . Complain if not found or not a valid URL . |
4,337 | private String getOptionalParameter ( String keyword , Map < String , String > parms ) { if ( ! parms . containsKey ( keyword ) ) { return null ; } String value = parms . get ( keyword ) ; if ( value == null ) { throw new ValidatorProcessUsageException ( "If parameter '" + keyword + "' is provided, it must have a value." ) ; } else { return value ; } } | Get the requested parameter from the map . If it s not there return null but if it s there with no value complain . |
4,338 | private IteratorType figureOutIteratorType ( String query , String terms , String pidfileParm ) { int howMany = ( query == null ? 0 : 1 ) + ( terms == null ? 0 : 1 ) + ( pidfileParm == null ? 0 : 1 ) ; if ( howMany == 0 ) { throw new ValidatorProcessUsageException ( "You must provide " + "either '" + PARAMETER_QUERY + "', '" + PARAMETER_TERMS + "' or '" + PARAMETER_PIDFILE + "'." ) ; } if ( howMany > 1 ) { throw new ValidatorProcessUsageException ( "You must provide only " + "one of these parameters: '" + PARAMETER_QUERY + "', '" + PARAMETER_TERMS + "' or '" + PARAMETER_PIDFILE + "'." ) ; } return pidfileParm == null ? IteratorType . FS_QUERY : IteratorType . PIDFILE ; } | Look at the parameters . Is this a query - based request or a pidfile - based request? If we put in too many parms or not enough that s a problem . |
4,339 | private File assemblePidfile ( String pidfileParm ) { File pidfile = new File ( pidfileParm ) ; if ( ! pidfile . exists ( ) ) { throw new ValidatorProcessUsageException ( "-pidfile does not exist: '" + pidfileParm + "'" ) ; } if ( ! pidfile . canRead ( ) ) { throw new ValidatorProcessUsageException ( "-pidfile is not readable: '" + pidfileParm + "'" ) ; } return pidfile ; } | Is there a valid file out there for this parm? We already know that the parms is not null . |
4,340 | public void interrupt ( ) { Thread t = threadVar . get ( ) ; if ( t != null ) { t . interrupt ( ) ; } threadVar . clear ( ) ; } | A new method that interrupts the worker thread . Call this method to force the worker to stop what it s doing . |
4,341 | public static org . fcrepo . server . types . mtom . gen . MIMETypedStream convertMIMETypedStreamToGenMIMETypedStreamMTOM ( org . fcrepo . server . storage . types . MIMETypedStream mimeTypedStream ) { if ( mimeTypedStream != null ) { org . fcrepo . server . types . mtom . gen . MIMETypedStream genMIMETypedStream = new org . fcrepo . server . types . mtom . gen . MIMETypedStream ( ) ; genMIMETypedStream . setMIMEType ( mimeTypedStream . getMIMEType ( ) ) ; org . fcrepo . server . storage . types . Property [ ] header = mimeTypedStream . header ; org . fcrepo . server . types . mtom . gen . MIMETypedStream . Header head = new org . fcrepo . server . types . mtom . gen . MIMETypedStream . Header ( ) ; if ( header != null ) { for ( org . fcrepo . server . storage . types . Property property : header ) { head . getProperty ( ) . add ( convertPropertyToGenProperty ( property ) ) ; } } genMIMETypedStream . setHeader ( head ) ; InputStreamDataSource ds = new InputStreamDataSource ( mimeTypedStream . getStream ( ) , mimeTypedStream . getMIMEType ( ) ) ; genMIMETypedStream . setStream ( new DataHandler ( ds ) ) ; return genMIMETypedStream ; } else { return null ; } } | the standard and MTOM implementations |
4,342 | public void postInitModule ( ) throws ModuleInitializationException { super . postInitModule ( ) ; _gSearchRESTURL = getParameter ( GSEARCH_REST_URL ) ; if ( _gSearchRESTURL == null ) { throw new ModuleInitializationException ( "Required parameter, " + GSEARCH_REST_URL + " was not specified" , getRole ( ) ) ; } else { try { new URL ( _gSearchRESTURL ) ; logger . debug ( "Configured GSearch REST URL: " + _gSearchRESTURL ) ; } catch ( MalformedURLException e ) { throw new ModuleInitializationException ( "Malformed URL given " + "for " + GSEARCH_REST_URL + " parameter: " + _gSearchRESTURL , getRole ( ) ) ; } } String user = getParameter ( GSEARCH_USERNAME ) ; if ( user != null ) { logger . debug ( "Will authenticate to GSearch service as user: " + user ) ; String pass = getParameter ( GSEARCH_PASSWORD ) ; if ( pass != null ) { _gSearchCredentials = new UsernamePasswordCredentials ( user , pass ) ; } else { throw new ModuleInitializationException ( GSEARCH_PASSWORD + " must be specified because " + GSEARCH_USERNAME + " was specified" , getRole ( ) ) ; } } else { logger . debug ( GSEARCH_USERNAME + " unspecified; will not attempt " + "to authenticate to GSearch service" ) ; } _webClientConfig = getServer ( ) . getWebClientConfig ( ) ; _webClient = new WebClient ( _webClientConfig ) ; } | Performs superclass post - initialization then completes initialization using GSearch - specific parameters . |
4,343 | public void doCommit ( boolean cachedObjectRequired , Context context , DigitalObject obj , String logMessage , boolean remove ) throws ServerException { super . doCommit ( cachedObjectRequired , context , obj , logMessage , remove ) ; StringBuffer url = new StringBuffer ( ) ; url . append ( _gSearchRESTURL + "?operation=updateIndex" ) ; String pid = obj . getPid ( ) ; url . append ( "&value=" + urlEncode ( pid ) ) ; if ( remove ) { logger . info ( "Signaling removal of {} to GSearch" , pid ) ; url . append ( "&action=deletePid" ) ; } else { if ( logger . isInfoEnabled ( ) ) { if ( obj . isNew ( ) ) { logger . info ( "Signaling add of {} to GSearch" , pid ) ; } else { logger . info ( "Signaling mod of {} to GSearch" , pid ) ; } } url . append ( "&action=fromPid" ) ; } sendRESTMessage ( url . toString ( ) ) ; } | Commits the changes to the given object as usual then attempts to propagate the change to the GSearch service . |
4,344 | private void sendRESTMessage ( String url ) { HttpInputStream response = null ; try { logger . debug ( "Getting " + url ) ; response = _webClient . get ( url , false , _gSearchCredentials ) ; int code = response . getStatusCode ( ) ; if ( code != 200 ) { logger . warn ( "Error sending update to GSearch service (url=" + url + "). HTTP response code was " + code + ". " + "Body of response from GSearch follows:\n" + getString ( response ) ) ; } } catch ( Exception e ) { logger . warn ( "Error sending update to GSearch service via URL: " + url , e ) ; } finally { if ( response != null ) { try { response . close ( ) ; } catch ( Exception e ) { logger . warn ( "Error closing GSearch response" , e ) ; } } } } | Performs the given HTTP request logging a warning if we don t get a 200 OK response . |
4,345 | private static String getString ( InputStream in ) { try { StringBuffer out = new StringBuffer ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; String line = reader . readLine ( ) ; while ( line != null ) { out . append ( line + "\n" ) ; line = reader . readLine ( ) ; } return out . toString ( ) ; } catch ( Exception e ) { return "[Error reading response body: " + e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) + "]" ; } } | Read the remainder of the given stream as a String and return it or an error message if we encounter an error . |
4,346 | private static final String urlEncode ( String s ) { try { return URLEncoder . encode ( s , "UTF-8" ) ; } catch ( Exception e ) { logger . warn ( "Failed to encode '" + s + "'" , e ) ; return s ; } } | URL - encode the given string using UTF - 8 encoding . |
4,347 | private void unpack ( ) throws InstallationFailedException { System . out . println ( "Preparing FEDORA_HOME..." ) ; if ( ! _installDir . exists ( ) && ! _installDir . mkdirs ( ) ) { throw new InstallationFailedException ( "Unable to create FEDORA_HOME: " + _installDir . getAbsolutePath ( ) ) ; } if ( ! _installDir . isDirectory ( ) ) { throw new InstallationFailedException ( _installDir . getAbsolutePath ( ) + " is not a directory" ) ; } try { Zip . unzip ( _dist . get ( Distribution . FEDORA_HOME ) , _installDir ) ; setScriptsExecutable ( new File ( _installDir , "client" + File . separator + "bin" ) ) ; File serverDir = new File ( _installDir , "server" ) ; if ( _clientOnlyInstall ) { FileUtils . delete ( serverDir ) ; } else { setScriptsExecutable ( new File ( serverDir , "bin" ) ) ; } } catch ( IOException e ) { throw new InstallationFailedException ( e . getMessage ( ) , e ) ; } } | Unpacks the contents of the FEDORA_HOME directory from the Distribution . |
4,348 | public static void zip ( File destination , File [ ] source ) throws FileNotFoundException , IOException { FileOutputStream dest = new FileOutputStream ( destination ) ; ZipOutputStream zout = new ZipOutputStream ( new BufferedOutputStream ( dest ) ) ; for ( File element : source ) { zip ( null , element , zout ) ; } zout . close ( ) ; } | Create a zip file . |
4,349 | public static void extractFile ( File zipFile , String entryName , File destination ) throws IOException { ZipFile zip = new ZipFile ( zipFile ) ; try { ZipEntry entry = zip . getEntry ( entryName ) ; if ( entry != null ) { InputStream entryStream = zip . getInputStream ( entry ) ; try { File parent = destination . getParentFile ( ) ; if ( parent != null ) { parent . mkdirs ( ) ; } FileOutputStream file = new FileOutputStream ( destination ) ; try { byte [ ] data = new byte [ BUFFER ] ; int bytesRead ; while ( ( bytesRead = entryStream . read ( data ) ) != - 1 ) { file . write ( data , 0 , bytesRead ) ; } } finally { file . close ( ) ; } } finally { entryStream . close ( ) ; } } else { throw new IOException ( zipFile . getName ( ) + " does not contain: " + entryName ) ; } } finally { zip . close ( ) ; } } | Extracts the file given by entryName to destination . |
4,350 | public static void unzip ( InputStream is , File destDir ) throws FileNotFoundException , IOException { BufferedOutputStream dest = null ; ZipInputStream zis = new ZipInputStream ( new BufferedInputStream ( is ) ) ; ZipEntry entry ; while ( ( entry = zis . getNextEntry ( ) ) != null ) { if ( entry . isDirectory ( ) ) { ( new File ( destDir , entry . getName ( ) ) ) . mkdirs ( ) ; } else { File f = new File ( destDir , entry . getName ( ) ) ; f . getParentFile ( ) . mkdirs ( ) ; int count ; byte data [ ] = new byte [ BUFFER ] ; FileOutputStream fos = new FileOutputStream ( f ) ; dest = new BufferedOutputStream ( fos , BUFFER ) ; while ( ( count = zis . read ( data , 0 , BUFFER ) ) != - 1 ) { dest . write ( data , 0 , count ) ; } dest . flush ( ) ; dest . close ( ) ; } } zis . close ( ) ; } | Unzips the InputStream to the given destination directory . |
4,351 | public void init ( PolicyFinder finder ) { try { logger . info ( "Loading repository policies..." ) ; setupActivePolicyDirectories ( ) ; m_repositoryPolicies . clear ( ) ; Map < String , AbstractPolicy > repositoryPolicies = m_policyLoader . loadPolicies ( m_policyParser , m_validateRepositoryPolicies , new File ( m_repositoryBackendPolicyDirectoryPath ) ) ; repositoryPolicies . putAll ( m_policyLoader . loadPolicies ( m_policyParser , m_validateRepositoryPolicies , new File ( m_repositoryPolicyDirectoryPath ) ) ) ; m_repositoryPolicies . addAll ( repositoryPolicies . values ( ) ) ; m_repositoryPolicySet = toPolicySet ( m_repositoryPolicies , m_combiningAlgorithm ) ; } catch ( Throwable t ) { logger . error ( "Error loading repository policies: " + t . toString ( ) , t ) ; } } | Does nothing at init time . |
4,352 | public PolicyFinderResult findPolicy ( EvaluationCtx context ) { PolicyFinderResult policyFinderResult = null ; PolicySet policySet = m_repositoryPolicySet ; try { String pid = getPid ( context ) ; if ( pid != null && ! pid . isEmpty ( ) ) { AbstractPolicy objectPolicyFromObject = m_policyLoader . loadObjectPolicy ( m_policyParser . copy ( ) , pid , m_validateObjectPoliciesFromDatastream ) ; if ( objectPolicyFromObject != null ) { List < AbstractPolicy > policies = new ArrayList < AbstractPolicy > ( m_repositoryPolicies ) ; policies . add ( objectPolicyFromObject ) ; policySet = toPolicySet ( policies , m_combiningAlgorithm ) ; } } policyFinderResult = new PolicyFinderResult ( policySet ) ; } catch ( Exception e ) { logger . warn ( "PolicyFinderModule seriously failed to evaluate a policy " , e ) ; policyFinderResult = new PolicyFinderResult ( new Status ( ERROR_CODE_LIST , e . getMessage ( ) ) ) ; } return policyFinderResult ; } | Gets a deny - biased policy set that includes all repository - wide and object - specific policies . |
4,353 | public static String getPid ( EvaluationCtx context ) { EvaluationResult attribute = context . getResourceAttribute ( STRING_ATTRIBUTE , Constants . OBJECT . PID . attributeId , null ) ; BagAttribute element = getAttributeFromEvaluationResult ( attribute ) ; if ( element == null ) { logger . debug ( "PolicyFinderModule:getPid exit on can't get pid on request callback" ) ; return null ; } if ( ! ( element . getType ( ) . equals ( STRING_ATTRIBUTE ) ) ) { logger . debug ( "PolicyFinderModule:getPid exit on couldn't get pid from xacml request non-string returned" ) ; return null ; } return ( element . size ( ) == 1 ) ? ( String ) element . getValue ( ) : null ; } | get the pid from the context or null if unable |
4,354 | private static final BagAttribute getAttributeFromEvaluationResult ( EvaluationResult attribute ) { if ( attribute . indeterminate ( ) ) { return null ; } if ( attribute . getStatus ( ) != null && ! Status . STATUS_OK . equals ( attribute . getStatus ( ) ) ) { return null ; } AttributeValue attributeValue = attribute . getAttributeValue ( ) ; if ( ! ( attributeValue instanceof BagAttribute ) ) { return null ; } return ( BagAttribute ) attributeValue ; } | copy of code in AttributeFinderModule ; consider refactoring |
4,355 | private static String byte2hex ( byte [ ] bytes ) { char [ ] hexChars = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' } ; StringBuffer sb = new StringBuffer ( ) ; for ( byte b : bytes ) { sb . append ( hexChars [ b >> 4 & 0xf ] ) ; sb . append ( hexChars [ b & 0xf ] ) ; } return new String ( sb ) ; } | Converts a hash into its hexadecimal string representation . |
4,356 | public synchronized void shutdown ( ) { try { if ( open ) { open = false ; writer . close ( ) ; logFile . renameTo ( new File ( fileName ) ) ; } } catch ( IOException e ) { logger . error ( "Error shutting down" , e ) ; } } | On the first call to this method close the log file and rename it . Set the flag so no more logging calls will be accepted . |
4,357 | protected Map < URI , AttributeValue > getEnvironment ( HttpServletRequest request ) { Map < URI , AttributeValue > envAttr = new HashMap < URI , AttributeValue > ( ) ; String ip = request . getRemoteAddr ( ) ; if ( ip != null && ! ip . isEmpty ( ) ) { envAttr . put ( Constants . HTTP_REQUEST . CLIENT_IP_ADDRESS . getURI ( ) , new StringAttribute ( ip ) ) ; } return envAttr ; } | Returns a map of environment attributes . |
4,358 | protected boolean isDate ( String item ) { if ( item == null ) { return false ; } if ( item . matches ( "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}Z$" ) ) { return true ; } if ( item . matches ( "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$" ) ) { return true ; } if ( item . matches ( "^\\d{4}-\\d{2}-\\d{2}$" ) ) { return true ; } return false ; } | Checks whether a parameter fits the date pattern . |
4,359 | public static byte [ ] encode ( byte [ ] in ) { return org . apache . commons . codec . binary . Base64 . encodeBase64 ( in ) ; } | Encodes bytes to base 64 returning bytes . |
4,360 | public static byte [ ] decode ( byte [ ] in ) { return org . apache . commons . codec . binary . Base64 . decodeBase64 ( in ) ; } | Decodes bytes from base 64 returning bytes . |
4,361 | public static byte [ ] decode ( InputStream in ) { try { return IOUtils . toByteArray ( decodeToStream ( in ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } } | Decode an input stream of b64 - encoded data to an array of bytes . |
4,362 | public static void enc ( char [ ] in , int start , int length , StringBuffer out ) { for ( int i = start ; i < length + start ; i ++ ) { enc ( in [ i ] , out ) ; } } | Prints an XML - appropriate encoding of the given range of characters to the given Writer . |
4,363 | public static void enc ( char in , StringBuffer out ) { if ( in == '&' ) { out . append ( "&" ) ; } else if ( in == '<' ) { out . append ( "<" ) ; } else if ( in == '>' ) { out . append ( ">" ) ; } else if ( in == '"' ) { out . append ( """ ) ; } else if ( in == '\'' ) { out . append ( "'" ) ; } else { out . append ( in ) ; } } | Appends an XML - appropriate encoding of the given character to the given Appendable . |
4,364 | public static byte [ ] getBytes ( InputStream in ) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; pipeStream ( in , out , 4096 ) ; return out . toByteArray ( ) ; } | Gets a byte array for the given input stream . |
4,365 | public static InputStream getStream ( String string ) { try { return new ByteArrayInputStream ( string . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException wontHappen ) { throw new FaultException ( wontHappen ) ; } } | Gets a stream for the given string . |
4,366 | public void invoke ( ) { try { m_console . setBusy ( true ) ; m_console . print ( "Invoking " + m_command . toString ( ) + "\n" ) ; Object [ ] parameters = new Object [ m_command . getParameterTypes ( ) . length ] ; if ( m_command . getParameterTypes ( ) . length > 0 ) { for ( int i = 0 ; i < m_command . getParameterTypes ( ) . length ; i ++ ) { m_console . print ( m_command . getParameterNames ( ) [ i ] ) ; m_console . print ( "=" ) ; Object paramValue = m_inputPanels [ i ] . getValue ( ) ; parameters [ i ] = paramValue ; if ( paramValue == null ) { m_console . print ( "<null>" ) ; } else { m_console . print ( stringify ( paramValue ) ) ; } m_console . print ( "\n" ) ; } } long startms = new Date ( ) . getTime ( ) ; Object returned = m_command . invoke ( m_console . getInvocationTarget ( m_command ) , parameters ) ; long endms = new Date ( ) . getTime ( ) ; long totalms = endms - startms ; if ( returned != null ) { m_console . print ( "Returned: " + stringify ( returned ) + "\n" ) ; } else { if ( m_command . getReturnType ( ) == null ) { m_console . print ( "Returned.\n" ) ; } else { m_console . print ( "Returned: <null>\n" ) ; } } String duration ; if ( totalms == 0 ) { duration = "< 0.001 seconds." ; } else { double secs = totalms / 1000.0 ; duration = secs + " seconds." ; } m_console . print ( "Roundtrip time: " ) ; m_console . print ( duration ) ; m_console . print ( "\n" ) ; } catch ( InvocationTargetException ite ) { m_console . print ( "ERROR (" + ite . getTargetException ( ) . getClass ( ) . getName ( ) + ") : " + ite . getTargetException ( ) . getMessage ( ) + "\n" ) ; } catch ( Throwable th ) { m_console . print ( "ERROR (" + th . getClass ( ) . getName ( ) + ") : " + th . getMessage ( ) + "\n" ) ; StringWriter sw = new StringWriter ( ) ; th . printStackTrace ( new PrintWriter ( sw ) ) ; m_console . print ( sw . toString ( ) ) ; } finally { m_console . setBusy ( false ) ; } } | Invokes the console command with whatever parameters have been set thus far sending any errors to the console . |
4,367 | public synchronized Document readPolicy ( File file ) throws ParsingException { try { return builder . parse ( file ) ; } catch ( IOException ioe ) { throw new ParsingException ( "Failed to read the file" , ioe ) ; } catch ( SAXException saxe ) { throw new ParsingException ( "Failed to parse the file" , saxe ) ; } } | Tries to read an XACML policy or policy set from the given file . |
4,368 | public synchronized Document readPolicy ( InputStream input ) throws ParsingException { try { return builder . parse ( input ) ; } catch ( IOException ioe ) { throw new ParsingException ( "Failed to read the stream" , ioe ) ; } catch ( SAXException saxe ) { throw new ParsingException ( "Failed to parse the stream" , saxe ) ; } } | Tries to read an XACML policy or policy set from the given stream . |
4,369 | public synchronized Document readPolicy ( URL url ) throws ParsingException { try { return readPolicy ( url . openStream ( ) ) ; } catch ( IOException ioe ) { throw new ParsingException ( "Failed to resolve the URL: " + url . toString ( ) , ioe ) ; } } | Tries to read an XACML policy or policy set based on the given URL . This may be any resolvable URL like a file or http pointer . |
4,370 | public String read ( int maxStringLength ) throws IOException { if ( maxStringLength < 4 ) { throw new IllegalArgumentException ( "maxStringLength must be 4 or more, not " + maxStringLength ) ; } if ( ! open ) { throw new IllegalStateException ( "Stream has already been closed." ) ; } int bytesRequestedForEncoding = maxStringLength / 4 * 3 ; if ( bytesRequestedForEncoding > bytesInBuffer ) { readMoreBytesFromStream ( ) ; } if ( bytesInBuffer == 0 && ! innerStreamHasMoreData ) { return null ; } int bytesToEncode = Math . min ( bytesRequestedForEncoding , bytesInBuffer ) ; String result = encodeBytesFromBuffer ( bytesToEncode ) ; return result ; } | Read encoded data from the stream . Data is read in 3 - byte multiples and encoded into 4 - character sequences per the Base64 specification . As many bytes as possible will be read limited by the amount of data available and by the limitation of maxStringLength on the size of the resulting encoded String . Since the smallest unit of encoded data is 4 characters maxStringLength must not be less than 4 . |
4,371 | private void readMoreBytesFromStream ( ) throws IOException { if ( ! innerStreamHasMoreData ) { return ; } int bufferSpaceAvailable = buffer . length - bytesInBuffer ; if ( bufferSpaceAvailable <= 0 ) { return ; } int bytesRead = stream . read ( buffer , bytesInBuffer , bufferSpaceAvailable ) ; if ( bytesRead == - 1 ) { innerStreamHasMoreData = false ; } else { bytesInBuffer += bytesRead ; } } | Fill the buffer with more data from the InputStream if there is any . |
4,372 | private String encodeBytesFromBuffer ( int howMany ) { String result ; if ( innerStreamHasMoreData ) { howMany = howMany - howMany % 3 ; } if ( howMany == 0 ) { return "" ; } byte [ ] encodeBuffer = new byte [ howMany ] ; System . arraycopy ( buffer , 0 , encodeBuffer , 0 , howMany ) ; result = Base64 . encodeToString ( encodeBuffer ) ; bytesInBuffer -= howMany ; if ( bytesInBuffer != 0 ) { System . arraycopy ( buffer , howMany , buffer , 0 , bytesInBuffer ) ; } return result ; } | Encode a group of bytes and remove them from the buffer . If the input stream has more data we need to limit the encoding to a multiple of 3 to avoid prematurely padding the result with equals signs . |
4,373 | public ContentModelInfo getContentModelInfo ( String pid ) throws ObjectSourceException , InvalidContentModelException { try { ObjectInfo object = getValidationObject ( pid ) ; if ( object == null ) { return null ; } DatastreamInfo dsInfo = object . getDatastreamInfo ( DS_COMPOSITE_MODEL ) ; if ( dsInfo == null ) { throw new InvalidContentModelException ( pid , "Content model has no '" + DS_COMPOSITE_MODEL + "' datastream." ) ; } if ( ! DS_COMPOSITE_MODEL_FORMAT . equals ( dsInfo . getFormatUri ( ) ) ) { throw new InvalidContentModelException ( pid , "Datastream '" + DS_COMPOSITE_MODEL + "' has incorrect format URI: '" + dsInfo . getFormatUri ( ) + "'." ) ; } MIMETypedStream ds = apia . getDatastreamDissemination ( pid , DS_COMPOSITE_MODEL , null ) ; DsCompositeModelDoc model = new DsCompositeModelDoc ( pid , org . fcrepo . server . utilities . TypeUtility . convertDataHandlerToBytes ( ds . getStream ( ) ) ) ; return new BasicContentModelInfo ( object , model . getTypeModels ( ) ) ; } catch ( Exception e ) { throw new ObjectSourceException ( "Problem fetching '" + DS_COMPOSITE_MODEL + "' datastream for pid='" + pid + "'" , e ) ; } } | A content model must exist as an object . If must have a ( |
4,374 | public boolean isDatastreamActive ( ) throws ServerException { if ( m_dsState == null && getDatastream ( ) != null ) m_dsState = m_datastream . DSState ; return m_dsState != null && m_dsState . equals ( "A" ) ; } | determines if the policy datastream in this object is active |
4,375 | public boolean hasPolicyDatastream ( ) throws ServerException { if ( m_hasPolicyDatastream == null ) { m_hasPolicyDatastream = false ; Datastream [ ] allDs = getReader ( ) . GetDatastreams ( null , null ) ; for ( int i = 0 ; i < allDs . length ; i ++ ) { if ( allDs [ i ] . DatastreamID . equals ( POLICY_DATASTREAM ) ) { m_hasPolicyDatastream = true ; m_datastream = allDs [ i ] ; break ; } } } return m_hasPolicyDatastream ; } | determines if this object contains a policy datastream |
4,376 | public InputStream getDsContent ( ) throws ServerException { if ( m_dsContent == null && getDatastream ( ) != null ) { m_dsContent = getDatastream ( ) . getContentStream ( ) ; m_hasPolicyDatastream = true ; } return m_dsContent ; } | get the policy datastream content |
4,377 | public static ManagementMethod getInstance ( String methodName , JournalEntry parent ) { if ( METHOD_INGEST . equals ( methodName ) ) { return new IngestMethod ( parent ) ; } else if ( METHOD_MODIFY_OBJECT . equals ( methodName ) ) { return new ModifyObjectMethod ( parent ) ; } else if ( METHOD_PURGE_OBJECT . equals ( methodName ) ) { return new PurgeObjectMethod ( parent ) ; } else if ( METHOD_ADD_DATASTREAM . equals ( methodName ) ) { return new AddDatastreamMethod ( parent ) ; } else if ( METHOD_MODIFY_DATASTREAM_BY_REFERENCE . equals ( methodName ) ) { return new ModifyDatastreamByReferenceMethod ( parent ) ; } else if ( METHOD_MODIFY_DATASTREAM_BY_VALUE . equals ( methodName ) ) { return new ModifyDatastreamByValueMethod ( parent ) ; } else if ( METHOD_SET_DATASTREAM_STATE . equals ( methodName ) ) { return new SetDatastreamStateMethod ( parent ) ; } else if ( METHOD_SET_DATASTREAM_VERSIONABLE . equals ( methodName ) ) { return new SetDatastreamVersionableMethod ( parent ) ; } else if ( METHOD_PURGE_DATASTREAM . equals ( methodName ) ) { return new PurgeDatastreamMethod ( parent ) ; } else if ( METHOD_PURGE_RELATIONSHIP . equals ( methodName ) ) { return new PurgeRelationshipMethod ( parent ) ; } else if ( METHOD_PUT_TEMP_STREAM . equals ( methodName ) ) { return new PutTempStreamMethod ( parent ) ; } else if ( METHOD_GET_NEXT_PID . equals ( methodName ) ) { return new GetNextPidMethod ( parent ) ; } else if ( METHOD_ADD_RELATIONSHIP . equals ( methodName ) ) { return new AddRelationshipMethod ( parent ) ; } else { throw new IllegalArgumentException ( "Unrecognized method name: '" + methodName + "'" ) ; } } | Get an instance of the proper class based on the method name . |
4,378 | public static void indent ( int num , PrintWriter out ) { if ( num <= SIXTY_FOUR ) { out . write ( SIXTY_FOUR_SPACES , 0 , num ) ; return ; } else if ( num <= 128 ) { out . write ( SIXTY_FOUR_SPACES , 0 , SIXTY_FOUR ) ; out . write ( SIXTY_FOUR_SPACES , 0 , num - SIXTY_FOUR ) ; } else { int times = num / SIXTY_FOUR ; int rem = num % SIXTY_FOUR ; for ( int i = 0 ; i < times ; i ++ ) { out . write ( SIXTY_FOUR_SPACES , 0 , SIXTY_FOUR ) ; } out . write ( SIXTY_FOUR_SPACES , 0 , rem ) ; return ; } } | Write a number of whitespaces to a writer |
4,379 | public static void indent ( int num , StringBuilder out ) { if ( num <= SIXTY_FOUR ) { out . append ( SIXTY_FOUR_SPACES , 0 , num ) ; return ; } else if ( num <= 128 ) { out . append ( SIXTY_FOUR_SPACES , 0 , SIXTY_FOUR ) ; out . append ( SIXTY_FOUR_SPACES , 0 , num - SIXTY_FOUR ) ; } else { int times = num / SIXTY_FOUR ; int rem = num % SIXTY_FOUR ; for ( int i = 0 ; i < times ; i ++ ) { out . append ( SIXTY_FOUR_SPACES , 0 , SIXTY_FOUR ) ; } out . append ( SIXTY_FOUR_SPACES , 0 , rem ) ; return ; } } | Write a number of whitespaces to a StringBuffer |
4,380 | @ SuppressWarnings ( "unused" ) public void shutdownModule ( ) throws ModuleShutdownException { logger . info ( "Shutting down " + getClass ( ) . getName ( ) ) ; if ( 1 == 2 ) { throw new ModuleShutdownException ( null , null ) ; } } | Frees system resources allocated by this Module . |
4,381 | protected static BeanDefinition getServerConfigurationBeanDefinition ( ) { String className = ServerConfiguration . class . getName ( ) ; GenericBeanDefinition result = new GenericBeanDefinition ( ) ; result . setAutowireCandidate ( true ) ; result . setScope ( BeanDefinition . SCOPE_SINGLETON ) ; result . setBeanClass ( Server . class ) ; result . setFactoryMethodName ( "getConfig" ) ; result . setAttribute ( "id" , className ) ; result . setAttribute ( "name" , className ) ; return result ; } | Provide a generic bean definition if the Server was not created by Spring |
4,382 | protected static GenericBeanDefinition createModuleBeanDefinition ( String className , Map < String , String > params , String role ) throws IOException { ScannedGenericBeanDefinition result = getScannedBeanDefinition ( className ) ; result . setParentName ( Module . class . getName ( ) ) ; result . setScope ( BeanDefinition . SCOPE_SINGLETON ) ; result . setAttribute ( "id" , role ) ; result . setAttribute ( "name" , role ) ; result . setAttribute ( "init-method" , "initModule" ) ; result . setEnforceInitMethod ( true ) ; result . setAttribute ( "destroy-method" , "shutdownModule" ) ; result . setEnforceDestroyMethod ( true ) ; ConstructorArgumentValues cArgs = new ConstructorArgumentValues ( ) ; cArgs . addIndexedArgumentValue ( 0 , params , MODULE_CONSTRUCTOR_PARAM1_CLASS ) ; BeanReference serverRef = new RuntimeBeanReference ( MODULE_CONSTRUCTOR_PARAM2_CLASS ) ; cArgs . addIndexedArgumentValue ( 1 , serverRef ) ; cArgs . addIndexedArgumentValue ( 2 , role , MODULE_CONSTRUCTOR_PARAM3_CLASS ) ; result . setConstructorArgumentValues ( cArgs ) ; return result ; } | Generates Spring Bean definitions for Fedora Modules . Server param should be unnecessary if autowired . |
4,383 | public static PID getPID ( String pidString ) throws MalformedPidException { try { return new PID ( pidString ) ; } catch ( MalformedPIDException e ) { throw new MalformedPidException ( e . getMessage ( ) ) ; } } | Wraps PID constructor throwing a ServerException instead |
4,384 | public static PID pidFromFilename ( String filename ) throws MalformedPidException { try { return PID . fromFilename ( filename ) ; } catch ( MalformedPIDException e ) { throw new MalformedPidException ( e . getMessage ( ) ) ; } } | Wraps PID . fromFilename throwing a ServerException instead |
4,385 | public static Date getCurrentDate ( Context context ) throws GeneralException { URI propName = Constants . ENVIRONMENT . CURRENT_DATE_TIME . attributeId ; String dateTimeValue = context . getEnvironmentValue ( propName ) ; if ( dateTimeValue == null ) { throw new GeneralException ( "Missing value for environment " + "context attribute: " + propName ) ; } try { return DateUtility . parseDateStrict ( dateTimeValue ) ; } catch ( ParseException e ) { throw new GeneralException ( e . getMessage ( ) ) ; } } | Get the current date from the context . If the context doesn t specify a value for the current date or the specified value cannot be parsed as an ISO8601 date string a GeneralException will be thrown . |
4,386 | private void addObjectProperties ( Feed feed , DigitalObject obj ) throws ObjectIntegrityException { PID pid ; try { pid = new PID ( feed . getId ( ) . toString ( ) ) ; } catch ( MalformedPIDException e ) { throw new ObjectIntegrityException ( e . getMessage ( ) , e ) ; } String label = feed . getTitle ( ) ; String state = m_xpath . valueOf ( "/a:feed/a:category[@scheme='" + MODEL . STATE . uri + "']/@term" , feed ) ; String createDate = m_xpath . valueOf ( "/a:feed/a:category[@scheme='" + MODEL . CREATED_DATE . uri + "']/@term" , feed ) ; obj . setPid ( pid . toString ( ) ) ; try { obj . setState ( DOTranslationUtility . readStateAttribute ( state ) ) ; } catch ( ParseException e ) { throw new ObjectIntegrityException ( "Could not read object state" , e ) ; } obj . setLabel ( label ) ; obj . setOwnerId ( getOwnerId ( feed ) ) ; obj . setCreateDate ( DateUtility . convertStringToDate ( createDate ) ) ; obj . setLastModDate ( feed . getUpdated ( ) ) ; setExtProps ( obj , feed ) ; } | Set the Fedora Object properties from the Feed metadata . |
4,387 | private String getDatastreamId ( DigitalObject obj , Entry entry ) { String entryId = entry . getId ( ) . toString ( ) ; Pattern pattern = Pattern . compile ( "^" + Constants . FEDORA . uri + ".+?/([^/]+)/?.*" ) ; Matcher matcher = pattern . matcher ( entryId ) ; if ( matcher . find ( ) ) { return matcher . group ( 1 ) ; } else { return obj . newDatastreamID ( ) ; } } | Parses the id to determine a datastreamId . |
4,388 | protected File getContentSrcAsFile ( IRI contentSrc , File tempDir ) throws ObjectIntegrityException , IOException { if ( contentSrc . isAbsolute ( ) || contentSrc . isPathAbsolute ( ) ) { throw new ObjectIntegrityException ( "contentSrc must not be absolute" ) ; } try { NormalizedURI nUri = new NormalizedURI ( tempDir . toURI ( ) . toString ( ) + contentSrc . toString ( ) ) ; nUri . normalize ( ) ; File f = new File ( nUri . toURI ( ) ) ; if ( f . getParentFile ( ) . equals ( tempDir ) ) { File temp = File . createTempFile ( "binary-datastream" , null ) ; FileUtils . move ( f , temp ) ; temp . deleteOnExit ( ) ; return temp ; } else { throw new ObjectIntegrityException ( contentSrc . toString ( ) + " is not a valid path." ) ; } } catch ( URISyntaxException e ) { throw new ObjectIntegrityException ( e . getMessage ( ) , e ) ; } } | Returns the an Entry s contentSrc as a File relative to the tempDir param . |
4,389 | public InputStream GetObjectXML ( ) throws ObjectIntegrityException , StreamIOException , UnsupportedTranslationException , ServerException { ReadableByteArrayOutputStream bytes = new ReadableByteArrayOutputStream ( 4096 ) ; m_translator . serialize ( m_obj , bytes , m_storageFormat , "UTF-8" , DOTranslationUtility . SERIALIZE_STORAGE_INTERNAL ) ; return bytes . toInputStream ( ) ; } | Return the object as an XML input stream in the internal serialization format . |
4,390 | @ Produces ( { HTML , XML } ) public Response getAllObjectMethods ( @ PathParam ( RestParam . PID ) String pid , @ QueryParam ( RestParam . AS_OF_DATE_TIME ) String dTime , @ QueryParam ( RestParam . FORMAT ) @ DefaultValue ( HTML ) String format , @ QueryParam ( RestParam . FLASH ) @ DefaultValue ( "false" ) boolean flash ) { return getObjectMethodsForSDefImpl ( pid , null , dTime , format , flash ) ; } | Lists all Service Definitions methods that can be invoked on a digital object . |
4,391 | @ Path ( "/{sDef}" ) @ Produces ( { HTML , XML } ) public Response getObjectMethodsForSDef ( @ PathParam ( RestParam . PID ) String pid , @ PathParam ( RestParam . SDEF ) String sDef , @ QueryParam ( RestParam . AS_OF_DATE_TIME ) String dTime , @ QueryParam ( RestParam . FORMAT ) @ DefaultValue ( HTML ) String format , @ QueryParam ( RestParam . FLASH ) @ DefaultValue ( "false" ) boolean flash ) { return getObjectMethodsForSDefImpl ( pid , sDef , dTime , format , flash ) ; } | Lists all Service Definitions methods that can be invoked on a digital object for the supplied Service Definition . |
4,392 | public static JournalWriter getInstance ( Map < String , String > parameters , String role , ServerInterface server ) throws JournalException { Object journalWriter = JournalHelper . createInstanceAccordingToParameter ( PARAMETER_JOURNAL_WRITER_CLASSNAME , new Class [ ] { Map . class , String . class , ServerInterface . class } , new Object [ ] { parameters , role , server } , parameters ) ; logger . info ( "JournalWriter is " + journalWriter . toString ( ) ) ; return ( JournalWriter ) journalWriter ; } | Create an instance of the proper JournalWriter child class as determined by the server parameters . |
4,393 | protected void writeDocumentHeader ( XMLEventWriter writer , String repositoryHash , Date currentDate ) throws JournalException { try { putStartDocument ( writer ) ; putStartTag ( writer , QNAME_TAG_JOURNAL ) ; putAttribute ( writer , QNAME_ATTR_REPOSITORY_HASH , repositoryHash ) ; putAttribute ( writer , QNAME_ATTR_TIMESTAMP , JournalHelper . formatDate ( currentDate ) ) ; } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } } | Subclasses should call this method to initialize a new Journal file if they already know the repository hash and the current date . |
4,394 | protected void writeDocumentTrailer ( XMLEventWriter writer ) throws JournalException { try { putEndDocument ( writer ) ; } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } } | Subclasses should call this method to close a Journal file . |
4,395 | protected void writeJournalEntry ( CreatorJournalEntry journalEntry , XMLEventWriter writer ) throws JournalException { try { writeJournaEntryStartTag ( journalEntry , writer ) ; new ContextXmlWriter ( ) . writeContext ( journalEntry . getContext ( ) , writer ) ; writeArguments ( journalEntry . getArgumentsMap ( ) , writer ) ; putEndTag ( writer , QNAME_TAG_JOURNAL_ENTRY ) ; writer . flush ( ) ; } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } } | Format a JournalEntry object and write a JournalEntry tag to the journal . |
4,396 | private void writeFileArgument ( String key , File file , XMLEventWriter writer ) throws XMLStreamException , JournalException { try { putStartTag ( writer , QNAME_TAG_ARGUMENT ) ; putAttribute ( writer , QNAME_ATTR_NAME , key ) ; putAttribute ( writer , QNAME_ATTR_TYPE , ARGUMENT_TYPE_STREAM ) ; EncodingBase64InputStream encoder = new EncodingBase64InputStream ( new BufferedInputStream ( new FileInputStream ( file ) ) ) ; String encodedChunk ; while ( null != ( encodedChunk = encoder . read ( 1000 ) ) ) { putCharacters ( writer , encodedChunk ) ; } encoder . close ( ) ; putEndTag ( writer , QNAME_TAG_ARGUMENT ) ; } catch ( IOException e ) { throw new JournalException ( "IO Exception on temp file" , e ) ; } } | An InputStream argument must be written as a Base64 - encoded String . It is read from the temp file in segments . Each segment is encoded and written to the XML writer as a series of character events . |
4,397 | private String getRepositoryHash ( ) throws JournalException { if ( ! server . hasInitialized ( ) ) { throw new IllegalStateException ( "The repository hash is not available until " + "the server is fully initialized." ) ; } try { return server . getRepositoryHash ( ) ; } catch ( ServerException e ) { throw new JournalException ( e ) ; } } | This method must not be called before the server has completed initialization . That s the only way we can be confident that the DOManager is present and ready to create the repository has that we will compare to . |
4,398 | private void closeAndForgetOldResults ( ) { Iterator < FieldSearchResultSQLImpl > iter = m_currentResults . values ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { FieldSearchResultSQLImpl r = iter . next ( ) ; if ( r . isExpired ( ) ) { logger . debug ( "listSession " + r . getToken ( ) + " expired; will forget it." ) ; iter . remove ( ) ; } } } | erase and cleanup expired stuff |
4,399 | private static String getDbValue ( List < DCField > dcFields ) { if ( dcFields . size ( ) == 0 ) { return null ; } StringBuilder out = new StringBuilder ( 64 * dcFields . size ( ) ) ; for ( DCField dcField : dcFields ) { out . append ( ' ' ) ; out . append ( dcField . getValue ( ) . toLowerCase ( ) ) ; } out . append ( " ." ) ; return out . toString ( ) ; } | Get the string that should be inserted for a repeating - value column given a list of values . Turn each value to lowercase and separate them all by space characters . If the list is empty return null . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.