idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
4,100
public Boolean storePropertiesFile ( String path ) throws IOException { Properties prop = new Properties ( ) ; OutputStream output = null ; try { output = new FileOutputStream ( path ) ; for ( String key : configs . keySet ( ) ) { prop . setProperty ( key , configs . get ( key ) ) ; } prop . store ( output , null ) ; r...
Store Configs in Properties File
4,101
public Boolean send ( MessageTemplate template ) throws UnirestException { String url = this . remote_url + this . configs . get ( "page_access_token" , "" ) ; String body = template . build ( ) ; Logger . info ( "curl -X POST -H \"Content-Type: application/json\" -d '" + body + "' \"" + url + "\"" ) ; HttpResponse < S...
Send Default Message
4,102
protected synchronized JournalInputFile openNextFile ( ) throws JournalException { while ( open ) { boolean locked = processLockingMechanism ( ) ; if ( pauseBeforePolling ) { try { wait ( pollingIntervalMillis ) ; } catch ( InterruptedException e ) { } } if ( ! locked ) { JournalInputFile nextFile = super . openNextFil...
Process the locking mechanism . If we are not locked we should look for another journal file to process . Ask for a new file using the superclass method but if none is found wait for a while and repeat . This will continue until we get a server shutdown signal .
4,103
private boolean processLockingMechanism ( ) throws JournalException { boolean locked ; if ( lockRequestedFile . exists ( ) ) { try { if ( ! lockAcceptedFile . exists ( ) ) { lockAcceptedFile . createNewFile ( ) ; } } catch ( IOException e ) { throw new JournalException ( "Unable to create 'Lock Accepted' file at '" + l...
If we see a lock request issue an acceptance . If we do not withdraw the acceptance .
4,104
private void getPath ( String uri , StringBuilder builder ) { if ( pattern . length ( ) == 0 ) { return ; } String hash = getHash ( uri ) ; int hashPos = 0 ; for ( int i = 0 ; i < pattern . length ( ) ; i ++ ) { char c = pattern . charAt ( i ) ; if ( c == '#' ) { builder . append ( hash . charAt ( hashPos ++ ) ) ; } el...
gets the path based on the hash of the uri or if the pattern is empty
4,105
private void setRDFAsDatastream ( StringBuffer buf ) { DatastreamXMLMetadata ds = new DatastreamXMLMetadata ( ) ; ds . DatastreamID = "RELS-INT" ; ds . DSVersionable = false ; ds . DSFormatURI = m_dsFormatURI ; ds . DatastreamAltIDs = m_dsAltIDs ; ds . DSVersionID = "RELS-INT.0" ; ds . DSLabel = "DO NOT EDIT: System-ge...
DMDID and ADMID relationships found in the METS file .
4,106
public void setSSLPort ( ) throws InstallationFailedException { Element httpsConnector = ( Element ) getDocument ( ) . selectSingleNode ( HTTPS_CONNECTOR_XPATH ) ; if ( options . getBooleanValue ( InstallOptions . SSL_AVAILABLE , true ) ) { if ( httpsConnector == null ) { Element service = ( Element ) getDocument ( ) ....
Sets the port and keystore information on the SSL connector if it already exists ; creates a new SSL connector otherwise . Also sets the redirectPort on the non - SSL connector to match .
4,107
private void addAttribute ( Element element , String attributeName , String attributeValue , String defaultValue ) { if ( attributeValue == null || attributeValue . equals ( defaultValue ) ) { Attribute attribute = ( Attribute ) element . selectSingleNode ( attributeName ) ; if ( attribute != null ) { element . remove ...
Adds the attribute to the element if the attributeValue is not equal to defaultValue . If attributeValue is null or equals defaultValue remove the attribute from the element if it is present .
4,108
public boolean accepts ( String type ) { if ( m_acceptsAll ) { return true ; } String [ ] parts = type . split ( "/" ) ; if ( parts . length != 2 ) { return false ; } for ( String element : m_types ) { if ( element . equals ( parts [ 0 ] + "/*" ) || element . equals ( type ) ) { return true ; } } return false ; }
Does this rule allow the given type?
4,109
public static final void loadAndRegister ( File driverJarFile , String driverClassName ) throws Exception { loadAndRegister ( new URL ( "jar:" + driverJarFile . toURI ( ) + "!/" ) , driverClassName ) ; }
Loads the driver from the given jar file and registers it with the driver manager .
4,110
public String [ ] getServiceDefinitions ( Context context , String PID , Date asOfDateTime ) throws ServerException { ArrayList < String > sdefs = new ArrayList < String > ( ) ; Iterator < String > iter = dynamicServiceToDeployment . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { sdefs . add ( iter . next (...
Get a list of Service Definition identifiers for dynamic disseminators associated with the digital object .
4,111
public ObjectMethodsDef [ ] listMethods ( Context context , String PID , Date asOfDateTime ) throws ServerException { String [ ] sDefPIDs = getServiceDefinitions ( context , PID , asOfDateTime ) ; Date versDateTime = asOfDateTime ; ArrayList < ObjectMethodsDef > objectMethods = new ArrayList < ObjectMethodsDef > ( ) ; ...
Get the definitions for all dynamic disseminations on the object . This will return the method definitions for all methods for all of the dynamic disseminators associated with the object .
4,112
private static String getDuration ( long millis ) { long tsec = millis / 1000 ; long h = tsec / 60 / 60 ; long m = ( tsec - h * 60 * 60 ) / 60 ; long s = tsec - h * 60 * 60 - m * 60 ; StringBuffer out = new StringBuffer ( ) ; if ( h > 0 ) { out . append ( h + " hour" ) ; if ( h > 1 ) { out . append ( 's' ) ; } } if ( m...
Convert the duration time from milliseconds to standard hours minutes and seconds format .
4,113
private static void openLog ( String rootName ) throws Exception { s_rootName = rootName ; String fileName = s_rootName + "-" + System . currentTimeMillis ( ) + ".xml" ; File outFile ; String fedoraHome = Constants . FEDORA_HOME ; if ( fedoraHome == null ) { outFile = new File ( fileName ) ; } else { File logDir = new ...
Initializes the log file for writing .
4,114
private static String fileAsString ( String path ) throws Exception { StringBuffer buffer = new StringBuffer ( ) ; InputStream fis = new FileInputStream ( path ) ; InputStreamReader isr = new InputStreamReader ( fis , "UTF-8" ) ; Reader in = new BufferedReader ( isr ) ; int ch ; while ( ( ch = in . read ( ) ) > - 1 ) {...
Converts file into string .
4,115
private String fileToName ( File policyFile ) throws PolicyIndexException { try { if ( ! policyFile . getName ( ) . endsWith ( ".xml" ) ) throw new PolicyIndexException ( "Invalid policy file name. Policy files must end in .xml - " + policyFile . getName ( ) ) ; return PID . fromFilename ( policyFile . getName ( ) . s...
Determine name of policy from file . . xml prefix is removed and name is converted to a PID . Policy names must be valid PIDs .
4,116
protected AbstractPolicy loadObjectPolicy ( PolicyParser policyParser , String pid , boolean validate ) throws ServerException { try { DOReader reader = m_repoReader . getReader ( Server . USE_DEFINITIVE_STORE , ReadOnlyContext . EMPTY , pid ) ; Datastream ds = reader . GetDatastream ( "POLICY" , null ) ; if ( ds != nu...
the passed parser must be safe to use in this thread
4,117
private static boolean isValidDateTime ( String lex ) { try { DateUtility . parseDateStrict ( lex ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Validated dateTime: " + lex ) ; } return true ; } catch ( ParseException e ) { logger . warn ( "Not a valid dateTime: " + lex ) ; return false ; } }
Tells whether the given string is a valid lexical representation of a dateTime value . Passing this test will ensure successful indexing later .
4,118
public void openFile ( String repositoryHash , String filename , Date currentDate ) throws JournalException { try { super . testStateChange ( State . FILE_OPEN ) ; writer = new RmiTransportWriter ( receiver , repositoryHash , filename ) ; xmlWriter = new IndentingXMLEventWriter ( XMLOutputFactory . newInstance ( ) . cr...
check state send the open request open a very special writer write the file opening set state
4,119
public static boolean hasViewer ( String type ) { return s_viewers . containsKey ( type ) || type . endsWith ( "+xml" ) && s_viewers . containsKey ( "text/xml" ) ; }
Can the factory provide a viewer for the given type?
4,120
public static boolean viewerIsEditor ( String type ) { Object viewer = s_viewers . get ( type ) ; if ( viewer != null ) { return viewer instanceof ContentEditor ; } else { return false ; } }
If a viewer would be provided for the given type is that viewer also an editor?
4,121
public static boolean hasEditor ( String type ) { return s_editors . containsKey ( type ) || type . endsWith ( "+xml" ) && s_editors . containsKey ( "text/xml" ) ; }
Can the factory provide an editor for the given type?
4,122
public static ContentViewer getViewer ( String type , InputStream data ) throws IOException { ContentViewer viewer = ( ContentViewer ) s_viewers . get ( type ) ; if ( viewer == null && type . endsWith ( "+xml" ) ) { viewer = ( ContentViewer ) s_viewers . get ( "text/xml" ) ; } return viewer . newInstance ( type , data ...
Get a viewer for the given type initialized with the given data . This should only be called if the caller knows there is a viewer for the type .
4,123
public static ContentEditor getEditor ( String type , InputStream data ) throws IOException { ContentEditor editor = ( ContentEditor ) s_editors . get ( type ) ; if ( editor == null && type . endsWith ( "+xml" ) ) { editor = ( ContentEditor ) s_editors . get ( "text/xml" ) ; } return ( ContentEditor ) editor . newInsta...
Get an editor for the given type initialized with the given data . This should only be called if the caller knows there is an editor for the type .
4,124
public Level getSeverityLevel ( ) { Level severity = Level . INFO ; for ( ValidationResultNotation note : notes ) { Level noteLevel = note . getLevel ( ) ; if ( noteLevel . compareTo ( severity ) > 0 ) { severity = noteLevel ; } } return severity ; }
What s the highest severity level of any of the notations on this result?
4,125
public void shutdownModule ( ) throws ModuleShutdownException { if ( _ri != null ) { try { _ri . close ( ) ; } catch ( TrippiException e ) { throw new ModuleShutdownException ( "Error closing RI" , getRole ( ) , e ) ; } } }
Shutdown the RI module by closing the wrapped ResourceIndex .
4,126
public static WebXML getInstance ( String webxml ) { WebXML wx = null ; BeanReader reader = new BeanReader ( ) ; reader . getXMLIntrospector ( ) . getConfiguration ( ) . setAttributesForPrimitives ( false ) ; reader . getBindingConfiguration ( ) . setMapIDs ( false ) ; try { reader . registerMultiMapping ( getBetwixtMa...
Create an instance of WebXML from the specified file .
4,127
private void preIngestIfNeeded ( boolean firstRun , DOManager doManager , RDFName objectName ) throws Exception { PID pid = new PID ( objectName . uri . substring ( "info:fedora/" . length ( ) ) ) ; boolean exists = doManager . objectExists ( pid . toString ( ) ) ; if ( exists && firstRun ) { logger . info ( "Purging o...
Ingests the given system object if it doesn t exist OR if it exists but this instance of Fedora has never been started . This ensures that upon upgrade the old system object is replaced with the new one .
4,128
private void validateXMLSchema ( InputStream objectAsStream , DOValidatorXMLSchema xsv ) throws ObjectValidityException , GeneralException { try { xsv . validate ( objectAsStream ) ; } catch ( ObjectValidityException e ) { logger . error ( "VALIDATE: ERROR - failed XML Schema validation." , e ) ; throw e ; } catch ( Ex...
Do XML Schema validation on the Fedora object .
4,129
private void validateByRules ( InputStream objectAsStream , String ruleSchemaPath , String preprocessorPath , String phase ) throws ObjectValidityException , GeneralException { try { DOValidatorSchematron schtron = new DOValidatorSchematron ( ruleSchemaPath , preprocessorPath , phase ) ; schtron . validate ( objectAsSt...
Do Schematron rules validation on the Fedora object . Schematron validation tests the object against a set of rules expressed using XPATH in a Schematron schema . These test for things that are beyond what can be expressed using XML Schema .
4,130
private void cleanUp ( File f ) { if ( f != null && f . getParentFile ( ) != null ) { if ( m_absoluteTempPath . equalsIgnoreCase ( f . getParentFile ( ) . getAbsolutePath ( ) ) ) { f . delete ( ) ; } } }
but it should only blow away files in the temp directory .
4,131
private void setupResource ( List resource ) throws ParsingException { mapAttributes ( resource , resourceMap ) ; List < Attribute > resourceId = resourceMap . get ( RESOURCE_ID ) ; if ( resourceId == null ) { logger . warn ( "Resource must contain resource-id attr" ) ; } else { if ( resourceId . size ( ) != 1 ) { logg...
This basically does the same thing that the other types need to do except that we also look for a resource - id attribute not because we re going to use but only to make sure that it s actually there and for the optional scope attribute to see what the scope of the attribute is
4,132
private void mapAttributes ( List < Attribute > input , Map < String , List < Attribute > > output ) { Iterator < Attribute > it = input . iterator ( ) ; while ( it . hasNext ( ) ) { Attribute attr = it . next ( ) ; String id = attr . getId ( ) . toString ( ) ; if ( output . containsKey ( id ) ) { List < Attribute > li...
Generic routine for resource attribute and environment attributes to build the lookup map for each . The Form is a Map that is indexed by the String form of the attribute ids and that contains Sets at each entry with all attributes that have that id
4,133
private EvaluationResult getGenericAttributes ( URI type , URI id , URI issuer , Map < String , List < Attribute > > map , URI category , int designatorType ) { List < Attribute > attrList = ( List ) ( map . get ( id . toString ( ) ) ) ; if ( attrList == null ) { Attribute contextValue = checkContext ( type , id , issu...
Helper function for the resource action and environment methods to get an attribute .
4,134
private Attribute checkContext ( URI type , URI id , URI issuer , URI category , int designatorType ) { if ( ! STRING_ATTRIBUTE_TYPE_URI . equals ( type ) ) return null ; String [ ] values = null ; switch ( designatorType ) { case AttributeDesignator . SUBJECT_TARGET : values = context . getSubjectValues ( id . toStrin...
Private helper that checks the request context for an attribute or else returns null
4,135
private EvaluationResult callHelper ( URI type , URI id , URI issuer , URI category , int adType ) { if ( finder != null ) { return finder . findAttribute ( type , id , issuer , category , this , adType ) ; } else { logger . warn ( NO_FINDER_MSG ) ; return new EvaluationResult ( BagAttribute . createEmptyBag ( type ) )...
Private helper that calls the finder if it s non - null or else returns an empty bag
4,136
public DOReader getReader ( boolean cachedObjectRequired , Context context , String pid ) throws ServerException { long getReaderStartTime = logger . isDebugEnabled ( ) ? System . currentTimeMillis ( ) : - 1 ; String source = null ; try { { DOReader reader = null ; if ( m_readerCache != null ) { reader = m_readerCache ...
Gets a reader on an existing digital object .
4,137
public ServiceDeploymentReader getServiceDeploymentReader ( boolean cachedObjectRequired , Context context , String pid ) throws ServerException { { return new SimpleServiceDeploymentReader ( context , this , m_translator , m_defaultExportFormat , m_defaultStorageFormat , m_storageCharacterEncoding , m_permanentStore ....
Gets a reader on an existing service deployment object .
4,138
public ServiceDefinitionReader getServiceDefinitionReader ( boolean cachedObjectRequired , Context context , String pid ) throws ServerException { { return new SimpleServiceDefinitionReader ( context , this , m_translator , m_defaultExportFormat , m_defaultStorageFormat , m_storageCharacterEncoding , m_permanentStore ....
Gets a reader on an existing service definition object .
4,139
public DOWriter getWriter ( boolean cachedObjectRequired , Context context , String pid ) throws ServerException , ObjectLockedException { if ( cachedObjectRequired ) { throw new InvalidContextException ( "A DOWriter is unavailable in a cached context." ) ; } else { BasicDigitalObject obj = new BasicDigitalObject ( ) ;...
Gets a writer on an existing object .
4,140
private static void populateDC ( Context ctx , DigitalObject obj , DOWriter w , Date nowUTC ) throws IOException , ServerException { logger . debug ( "Adding/Checking default DC datastream" ) ; Datastream dc = w . GetDatastream ( "DC" , null ) ; DCFields dcf ; XMLDatastreamProcessor dcxml = null ; if ( dc == null ) { d...
Adds a minimal DC datastream if one isn t already present .
4,141
public boolean objectExists ( String pid ) throws StorageDeviceException { boolean registered = objectExistsInRegistry ( pid ) ; boolean exists = false ; if ( ! registered && m_checkableStore ) { try { exists = ( ( ICheckable ) m_permanentStore ) . objectExists ( pid ) ; } catch ( LowlevelStorageException e ) { throw n...
Checks the object registry for the given object .
4,142
private void unregisterObject ( DigitalObject obj ) throws StorageDeviceException { String pid = obj . getPid ( ) ; Connection conn = null ; PreparedStatement st = null ; try { conn = m_connectionPool . getReadWriteConnection ( ) ; String query = "DELETE FROM doRegistry WHERE doPID=?" ; st = conn . prepareStatement ( q...
Removes an object from the object registry .
4,143
private String [ ] getPIDs ( String whereClause ) throws StorageDeviceException { Connection conn = null ; PreparedStatement s = null ; ResultSet results = null ; try { conn = m_connectionPool . getReadOnlyConnection ( ) ; String query = "SELECT doPID FROM doRegistry " + whereClause ; s = conn . prepareStatement ( quer...
whereClause is a WHERE clause starting with where
4,144
private int getNumObjectsWithVersion ( Connection conn , int n ) throws SQLException { PreparedStatement st = null ; try { String query ; if ( n > 0 ) { query = "SELECT COUNT(*) FROM doRegistry WHERE systemVersion = " . concat ( Integer . toString ( n ) ) ; } else { query = "SELECT COUNT(*) FROM doRegistry" ; } st = co...
Get the number of objects in the registry whose system version is equal to the given value . If n is less than one return the total number of objects in the registry .
4,145
public static Templates getTemplates ( File src ) throws TransformerException { String key = src . getAbsolutePath ( ) ; TimestampedCacheEntry < Templates > entry = TEMPLATES_CACHE . get ( key ) ; if ( entry == null || entry . timestamp ( ) < src . lastModified ( ) ) { TransformerFactory factory = null ; try { factory ...
Try to cache parsed Templates but check for changes on disk
4,146
private void addAuditDatastream ( Feed feed , DigitalObject obj , ZipOutputStream zout , String encoding ) throws ObjectIntegrityException , StreamIOException { if ( obj . getAuditRecords ( ) . size ( ) == 0 ) { return ; } String dsId = PID . toURI ( obj . getPid ( ) ) + "/AUDIT" ; String dsvId = dsId + "/" + DateUtili...
AUDIT datastream is rebuilt from the latest in - memory audit trail which is a separate array list in the DigitalObject class . Audit trail datastream re - created from audit records . There is only ONE version of the audit trail datastream
4,147
public void setNames ( String names ) { this . names = new HashSet < String > ( Arrays . asList ( names . split ( " " ) ) ) ; }
setNames set the list of attribute names to look for
4,148
private MIMETypedStream getFromWeb ( ContentManagerParams params ) throws ModuleInitializationException , GeneralException , RangeNotSatisfiableException { String username = params . getUsername ( ) ; String password = params . getPassword ( ) ; boolean backendSSL = false ; String url = params . getUrl ( ) ; url = para...
Retrieves external content via http or https .
4,149
private String determineMimeType ( File file ) { String mimeType = MIME_MAP . getContentType ( file ) ; if ( mimeType == null || mimeType . equalsIgnoreCase ( "" ) ) { mimeType = DEFAULT_MIMETYPE ; } return mimeType ; }
Determines the mime type of a given file
4,150
private static boolean isHEADRequest ( ContentManagerParams params ) { Context context = params . getContext ( ) ; if ( context != null ) { String method = context . getEnvironmentValue ( Constants . HTTP_REQUEST . METHOD . attributeId ) ; return "HEAD" . equalsIgnoreCase ( method ) ; } return false ; }
determine whether the context is a HEAD http request
4,151
private static RemoteObjectSource openObjectSource ( ServiceInfo serviceInfo ) { try { return new RemoteObjectSource ( serviceInfo ) ; } catch ( ServiceException e ) { throw new IllegalStateException ( "Failed to initialize " + "the ValidatorProcess: " , e ) ; } catch ( IOException e ) { throw new IllegalStateException...
Open the connection to the Fedora server .
4,152
private static Iterator < String > getPidIterator ( ValidatorProcessParameters parms , RemoteObjectSource objectSource ) throws ObjectSourceException { if ( parms . getIteratorType ( ) == IteratorType . FS_QUERY ) { return objectSource . findObjectPids ( parms . getQuery ( ) ) ; } else { return new PidfileIterator ( pa...
The list of PIDs may come from a file or from a query against the object source .
4,153
private JPanel makePanel ( String sDefPID ) throws IOException { JTextArea supportsMethodsTextArea = new JTextArea ( " defines method" ) ; supportsMethodsTextArea . setLineWrap ( false ) ; supportsMethodsTextArea . setEditable ( false ) ; supportsMethodsTextArea . setBackground ( Administrator . BACKGROUND_COLOR ) ; ...
Create and return a new panel describing the service definition . Methods dropdown methodName - descriptionIfExists Parameters None . | tabbedPane
4,154
private Document parseBytesToDocument ( String pid , byte [ ] bytes ) throws InvalidContentModelException { try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; return builder . parse ( new B...
Create a DOM document from the original XML .
4,155
public void putContentStream ( MIMETypedStream stream ) throws StreamIOException { String oldDSLocation = DSLocation ; try { File tempFile = File . createTempFile ( "managedcontentupdate" , null ) ; OutputStream os = new FileOutputStream ( tempFile ) ; StreamUtility . pipeStream ( stream . getStream ( ) , os , 32768 ) ...
Set the contents of this managed datastream by storing as a temp file . If the previous content was stored in a temp file clean up this file .
4,156
protected boolean usesDOTable ( ) throws Exception { Connection conn = getConnection ( ) ; DatabaseMetaData dmd = conn . getMetaData ( ) ; ResultSet rs = dmd . getTables ( null , null , "do%" , null ) ; while ( rs . next ( ) ) { if ( rs . getString ( "TABLE_NAME" ) . equals ( "do" ) ) { rs . close ( ) ; return true ; }...
Determines whether or not the database has a table named do .
4,157
protected XMLEvent readStartTag ( XMLEventReader reader , QName tagName ) throws XMLStreamException , JournalException { XMLEvent event = reader . nextTag ( ) ; if ( ! isStartTagEvent ( event , tagName ) ) { throw getNotStartTagException ( tagName , event ) ; } return event ; }
Read the next event and complain if it is not the Start Tag that we expected .
4,158
protected boolean isStartTagEvent ( XMLEvent event , QName tagName ) { return event . isStartElement ( ) && event . asStartElement ( ) . getName ( ) . equals ( tagName ) ; }
Test an event to see whether it is an start tag with the expected name .
4,159
protected boolean isEndTagEvent ( XMLEvent event , QName tagName ) { return event . isEndElement ( ) && event . asEndElement ( ) . getName ( ) . equals ( tagName ) ; }
Test an event to see whether it is an end tag with the expected name .
4,160
protected String getRequiredAttributeValue ( StartElement start , QName attributeName ) throws JournalException { Attribute mapNameAttribute = start . getAttributeByName ( attributeName ) ; if ( mapNameAttribute == null ) { throw new JournalException ( "Start tag '" + start + "' must contain a '" + attributeName + "' a...
Get the value of a given attribute from this start tag or complain if it s not there .
4,161
protected String getOptionalAttributeValue ( StartElement start , QName attributeName ) { Attribute mapNameAttribute = start . getAttributeByName ( attributeName ) ; if ( mapNameAttribute == null ) { return null ; } else { return mapNameAttribute . getValue ( ) ; } }
Get the value of a given attribute from this start tag or null if the attribute is not there .
4,162
protected JournalException getNotNextMemberOrEndOfGroupException ( QName groupTagName , QName memberTagName , XMLEvent event ) { return new JournalException ( "Expecting either '" + memberTagName + "' start tag, or '" + groupTagName + "' end tag, but event was '" + event + "'" ) ; }
While traversing a group of member tags we expected either the start of another member tag or the end of the group .
4,163
public Object invokeMethod ( Object service_object , String methodName , Property [ ] userParms ) throws ServerException { Method method = null ; if ( userParms == null ) { userParms = new Property [ 0 ] ; } Object [ ] parmValues = new Object [ userParms . length ] ; Class < ? > [ ] parmClassTypes = new Class [ userPar...
Invoke a method on an internal service . This is done using Java reflection where the service is the target object of a dynamic method request .
4,164
private Management getProxyChain ( Management m ) throws ModuleInitializationException { try { invocationHandlers = getInvocationHandlers ( ) ; return ( Management ) ProxyFactory . getProxy ( m , invocationHandlers ) ; } catch ( Exception e ) { throw new ModuleInitializationException ( e . getMessage ( ) , getRole ( ) ...
Build a proxy chain as configured by the module parameters .
4,165
public String put ( String optionName , String optionValue ) { options . put ( optionName , optionValue ) ; return optionValue ; }
Add or update a config item for this attribute
4,166
private void refreshStash ( ) throws ObjectSourceException { if ( ! stash . isEmpty ( ) ) { return ; } try { if ( SEARCH_NOT_STARTED . equals ( token ) ) { beginSearch ( ) ; } else if ( token != null ) { resumeSearch ( ) ; } } catch ( RemoteException e ) { throw new ObjectSourceException ( e ) ; } }
Does the stash have anything in it? If it s empty try to fill it .
4,167
private void beginSearch ( ) throws RemoteException { org . fcrepo . server . types . gen . FieldSearchQuery genFieldSearchQuery = TypeUtility . convertFieldSearchQueryToGenFieldSearchQuery ( query ) ; org . fcrepo . server . types . gen . FieldSearchResult searchResult = apia . findObjects ( org . fcrepo . server . ut...
We haven t tried searching yet . Do so and set the stash and token from the results .
4,168
private void resumeSearch ( ) throws RemoteException { org . fcrepo . server . types . gen . FieldSearchResult searchResult = apia . resumeFindObjects ( token ) ; FieldSearchResult fsr = TypeUtility . convertGenFieldSearchResultToFieldSearchResult ( searchResult ) ; for ( ObjectFields fields : fsr . objectFieldsList ( ...
We are already searching . Use the stored token to continue the search and set the stash and token from the results .
4,169
public static void writeXmlNoSpace ( Document doc , String encoding , Writer out ) throws IOException { XMLSerializer ser = new XMLSerializer ( out , getXmlNoSpace ( encoding ) ) ; ser . serialize ( doc ) ; out . close ( ) ; }
Serialize the dom Document with no preserved space between elements but without indenting line wrapping omission of XML declaration or omission of doctype
4,170
public String uploadFile ( File file ) throws IOException { HttpPost post = null ; try { post = new HttpPost ( getUploadURL ( ) ) ; post . getParams ( ) . setParameter ( "Connection" , "Keep-Alive" ) ; MultipartEntity entity = new MultipartEntity ( ) ; entity . addPart ( "file" , new FileBody ( file ) ) ; post . setEnt...
Upload the given file to Fedora s upload interface via HTTP POST .
4,171
private static String replaceNewlines ( String in , String replaceWith ) { return in . replaceAll ( "\r" , replaceWith ) . replaceAll ( "\n" , replaceWith ) ; }
Replace newlines with the given string .
4,172
public synchronized String getUploadURL ( ) throws IOException { if ( m_uploadURL != null ) { return m_uploadURL ; } else { m_uploadURL = m_baseURL + "management/upload" ; if ( m_uploadURL . startsWith ( "http:" ) ) { URL redirectURL = getRedirectURL ( m_uploadURL ) ; if ( redirectURL != null ) { m_uploadURL = redirect...
Get the URL to which API - M upload requests will be sent .
4,173
public String getServerVersion ( ) throws IOException { if ( m_serverVersion == null ) { String desc = getResponseAsString ( "/describe?xml=true" , true , true ) ; logger . debug ( "describeRepository response:\n" + desc ) ; String [ ] parts = desc . split ( "<repositoryVersion>" ) ; if ( parts . length < 2 ) { throw n...
Get the version reported by the remote Fedora server .
4,174
public Date getServerDate ( ) throws IOException { HttpInputStream in = get ( "/describe" , false , false ) ; String dateString = null ; try { Header header = in . getResponseHeader ( "Date" ) ; if ( header == null ) { throw new IOException ( "Date was not supplied in HTTP response " + "header for " + m_baseURL + "desc...
Return the current date as reported by the Fedora server .
4,175
private URL getRedirectURL ( String location ) throws IOException { HttpInputStream in = get ( location , false , false ) ; try { if ( in . getStatusCode ( ) == 302 ) { Header h = in . getResponseHeader ( "location" ) ; if ( h != null ) { return new URL ( h . getValue ( ) ) ; } } return null ; } finally { try { in . cl...
Ping the given endpoint to see if an HTTP 302 status code is returned . If so return the location given in the HTTP response header . If not return null .
4,176
protected static String getXpath ( Map < String , Collection < AttributeBean > > attributeMap ) { StringBuilder sb = new StringBuilder ( ) ; getXpath ( attributeMap , sb ) ; return sb . toString ( ) ; }
Creates an XPath query from the attributes
4,177
public Destination createDestination ( String name , DestinationType type , boolean fTransacted , int ackMode ) throws MessagingException { JMSDestination jmsDest = jmsDestinations . get ( name ) ; if ( jmsDest != null ) { return jmsDest . destination ; } Session session ; try { session = connection . createSession ( f...
Creates a Destination if the Destination has not already been created .
4,178
public void send ( String destName , Message msg ) throws MessagingException { JMSDestination jmsDest = getJMSDestination ( destName ) ; setupProducer ( jmsDest ) ; try { jmsDest . producer . send ( msg ) ; } catch ( JMSException e ) { throw new MessagingException ( e . getMessage ( ) , e ) ; } if ( logger . isDebugEna...
Allows the caller to send a Message object to a named destination
4,179
public void send ( Destination dest , Message msg ) throws MessagingException { try { Session s = connection . createSession ( false , Session . AUTO_ACKNOWLEDGE ) ; MessageProducer p = s . createProducer ( dest ) ; p . send ( msg ) ; s . close ( ) ; } catch ( JMSException e ) { throw new MessagingException ( e . getMe...
Allows the caller to send a Message object to a destination
4,180
public void send ( String destName , String messageText ) throws MessagingException { this . send ( destName , ( Serializable ) messageText ) ; }
Allows the caller to send text to a destination
4,181
public void stop ( String destName ) throws MessagingException { try { JMSDestination jmsDest = jmsDestinations . get ( destName ) ; if ( jmsDest != null ) { if ( jmsDest . producer != null ) { jmsDest . producer . close ( ) ; logger . debug ( "Closed producer for " + destName ) ; } if ( jmsDest . consumer != null ) { ...
Stops producers and consumers on a given destination . This has no effect on durable subscriptions .
4,182
public void stopDurable ( String subscriptionName ) throws MessagingException { try { MessageConsumer durableSubscriber = durableSubscriptions . get ( subscriptionName ) ; if ( durableSubscriber != null ) { durableSubscriber . close ( ) ; } } catch ( JMSException jmse ) { throw new MessagingException ( "Exception encou...
Stops a durable message consumer . Note that this is not the same as unsubscribing . When a durable message consumer is restarted all messages received since it was stopped will be delivered .
4,183
public void unsubscribeDurable ( String subscriptionName ) throws MessagingException { try { Session session = connection . createSession ( false , Session . AUTO_ACKNOWLEDGE ) ; MessageConsumer consumer = durableSubscriptions . get ( subscriptionName ) ; if ( consumer != null ) { consumer . close ( ) ; } session . uns...
Removes the durable subscription with the given name .
4,184
public Destination getDestination ( String destName ) throws MessagingException { Destination destination = null ; JMSDestination jmsDest = getJMSDestination ( destName ) ; if ( jmsDest != null ) { destination = jmsDest . destination ; } return destination ; }
Gets the named Destination if it has been created .
4,185
public List < Destination > getDestinations ( ) { List < Destination > destinations = new ArrayList < Destination > ( ) ; Iterator < JMSDestination > destinationIterator = jmsDestinations . values ( ) . iterator ( ) ; while ( destinationIterator . hasNext ( ) ) { destinations . add ( destinationIterator . next ( ) . de...
Provides a listing of the currently available destinations
4,186
protected void connectToJMS ( String clientId ) throws MessagingException { if ( connected == true ) return ; try { connection = getConnection ( ) ; if ( clientId != null ) { connection . setClientID ( clientId ) ; } connection . start ( ) ; connected = true ; logger . debug ( "connectToJMS - connected" ) ; } catch ( J...
Internal worker methods
4,187
public static String encipher ( String key , String clearText ) { if ( key == null ) { throw new NullPointerException ( "key may not be null" ) ; } if ( key == "" ) { return clearText ; } if ( clearText == null ) { return null ; } byte [ ] keyBytes = convertKeyToByteArray ( key ) ; byte [ ] clearTextBytes = convertClea...
Use the key to produce a ciphered String from the clearText .
4,188
public static String decipher ( String key , String cipherText , String cipherType ) { if ( key == null || key == "" ) { return cipherText ; } if ( cipherText == null ) { return null ; } if ( cipherType == null || cipherType == "" ) { return cipherText ; } else if ( "1" . equalsIgnoreCase ( cipherType ) ) { byte [ ] ke...
Use the key to produce a clear text String from the cipherText . If no key is provided or if no type is specified just return the text as is .
4,189
private static byte [ ] convertKeyToByteArray ( String key ) { byte [ ] result = new byte [ key . length ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { char thisChar = key . charAt ( i ) ; result [ i ] = ( byte ) ( thisChar >>> 8 & 0xFF ^ thisChar & 0xFF ) ; } return result ; }
Convert the key to a byte array by compressing the 16 - bit characters to bytes . This XOR compression insures that the top 8 bits are still significant so a key of \ u0020 yields a different cipher than a key of \ u0120 .
4,190
private static byte [ ] convertClearTextToByteArray ( String clearText ) { byte [ ] result = new byte [ clearText . length ( ) * 2 ] ; for ( int i = 0 ; i < clearText . length ( ) ; i ++ ) { char thisChar = clearText . charAt ( i ) ; int pos = i * 2 ; result [ pos ] = ( byte ) ( thisChar >>> 8 & 0xFF ) ; result [ pos +...
Convert the clear text to a byte array by splitting each 16 - bit character into 2 bytes . This insures that no data is lost .
4,191
private static void sanityCheckOnCipherBytes ( String cipherText , byte [ ] cipherBytes ) { if ( cipherBytes . length % 2 != 0 ) { throw new IllegalStateException ( "Ciphered text decodes to an odd number of bytes! Text='" + cipherText + "', decodes to " + cipherBytes . length + " bytes." ) ; } }
If the cipher text decodes to an odd number of bytes we can t go on!
4,192
private static String convertByteArrayToClearText ( byte [ ] bytes ) { StringBuffer result = new StringBuffer ( ) ; for ( int i = 0 ; i < bytes . length ; i += 2 ) { char thisChar = ( char ) ( bytes [ i ] << 8 | bytes [ i + 1 ] ) ; result . append ( thisChar ) ; } return result . toString ( ) ; }
Convert a byte array to text by joining each two bytes into a 16 - bit character .
4,193
private static byte [ ] applyCipher ( byte [ ] keyBytes , byte [ ] textBytes ) { byte [ ] result = new byte [ textBytes . length ] ; for ( int i = 0 ; i < result . length ; i ++ ) { int keyPos = i % keyBytes . length ; result [ i ] = ( byte ) ( textBytes [ i ] ^ keyBytes [ keyPos ] ) ; } return result ; }
The same algorithm applies for enciphering or deciphering . Go through the text XORing with successive bytes of the key . If you apply it twice you get the original text back .
4,194
private static Document getUserDocument ( ) throws Exception { if ( userDoc == null || userFileParsed != userFile . lastModified ( ) || userFileBytesLoaded != userFile . length ( ) ) { synchronized ( XmlUsersFileModule . class ) { if ( userDoc == null || userFileParsed != userFile . lastModified ( ) || userFileBytesLoa...
Quick and dirty caching .
4,195
static String getRequiredParameter ( Map < String , String > parameters , String parameterName ) throws JournalException { String value = parameters . get ( parameterName ) ; if ( value == null ) { throw new JournalException ( "'" + parameterName + "' is required." ) ; } return value ; }
Get the requested parameter or throw an exception if it is not found .
4,196
static long parseParametersForPollingInterval ( Map < String , String > parameters ) throws JournalException { String intervalString = parameters . get ( PARAMETER_FOLLOW_POLLING_INTERVAL ) ; if ( intervalString == null ) { intervalString = DEFAULT_FOLLOW_POLLING_INTERVAL ; } Pattern p = Pattern . compile ( "([0-9]+)([...
Find the polling interval that we will choose when checking for new journal files to appear .
4,197
static File [ ] getSortedArrayOfJournalFiles ( File journalDirectory , String filenamePrefix ) { JournalFileFilter filter = new JournalFileFilter ( filenamePrefix ) ; File [ ] journalFiles = journalDirectory . listFiles ( filter ) ; Arrays . sort ( journalFiles , new FilenameComparator ( ) ) ; return journalFiles ; }
Get the Journal Files that exist the Journal Directory sorted by name .
4,198
public final void populate ( Boolean authenticated , Set < ? > predicates , Map < String , Set < ? > > map , String errorMessage ) { String m = m_cacheabbrev + " populate() " ; logger . debug ( "{}>" , m ) ; try { if ( predicates != null ) { logger . warn ( m + " predicates are deprecated; will be ignored" ) ; } assert...
Populates this cache element with the given authenticated state and named values then puts it in the valid state .
4,199
public static JournalRecoveryLog getInstance ( Map < String , String > parameters , String role , ServerInterface server ) throws ModuleInitializationException { try { Object recoveryLog = JournalHelper . createInstanceAccordingToParameter ( PARAMETER_JOURNAL_RECOVERY_LOG_CLASSNAME , new Class [ ] { Map . class , Strin...
Create an instance of the proper JournalRecoveryLog child class as determined by the server parameters .