idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
4,400
private void advanceIntoFile ( ) throws XMLStreamException , JournalException { XMLEvent event = reader . nextEvent ( ) ; if ( ! event . isStartDocument ( ) ) { throw new JournalException ( "Expecting XML document header, but event was '" + event + "'" ) ; } event = reader . nextTag ( ) ; if ( ! isStartTagEvent ( event , QNAME_TAG_JOURNAL ) ) { throw new JournalException ( "Expecting FedoraJournal start tag, but event was '" + event + "'" ) ; } String hash = getOptionalAttributeValue ( event . asStartElement ( ) , QNAME_ATTR_REPOSITORY_HASH ) ; checkRepositoryHash ( hash ) ; }
Advance past the document header to the first JournalEntry .
4,401
public synchronized ConsumerJournalEntry readJournalEntry ( ) throws JournalException , XMLStreamException { if ( ! open ) { return null ; } if ( ! advancedPastHeader ) { advanceIntoFile ( ) ; advancedPastHeader = true ; } XMLEvent next = reader . peek ( ) ; while ( next . isCharacters ( ) && next . asCharacters ( ) . isWhiteSpace ( ) ) { reader . nextEvent ( ) ; next = reader . peek ( ) ; } if ( isStartTagEvent ( next , QNAME_TAG_JOURNAL_ENTRY ) ) { String identifier = peekAtJournalEntryIdentifier ( ) ; ConsumerJournalEntry journalEntry = super . readJournalEntry ( reader ) ; journalEntry . setIdentifier ( identifier ) ; return journalEntry ; } else if ( isEndTagEvent ( next , QNAME_TAG_JOURNAL ) ) { return null ; } else { throw getNotNextMemberOrEndOfGroupException ( QNAME_TAG_JOURNAL , QNAME_TAG_JOURNAL_ENTRY , next ) ; } }
Advance past any white space and then see whether we have any more JournalEntry tags . If we don t just return null .
4,402
public synchronized void shutdown ( ) throws JournalException { try { if ( open ) { reader . close ( ) ; open = false ; } } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } }
On the first call Just close the reader .
4,403
public String fileToString ( File f ) throws MelcoePDPException { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; byte [ ] bytes = new byte [ 1024 ] ; try { FileInputStream fis = new FileInputStream ( f ) ; int count = fis . read ( bytes ) ; while ( count > - 1 ) { out . write ( bytes , 0 , count ) ; count = fis . read ( bytes ) ; } fis . close ( ) ; } catch ( IOException e ) { throw new MelcoePDPException ( "Error reading file: " + f . getName ( ) , e ) ; } return out . toString ( ) ; }
Read file and return contents as a string
4,404
public Map < String , String > getDocumentMetadata ( InputStream docIS ) { Map < String , String > metadata = new HashMap < String , String > ( ) ; try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder docBuilder = factory . newDocumentBuilder ( ) ; Document doc = docBuilder . parse ( docIS ) ; NodeList nodes = null ; metadata . put ( "PolicyId" , doc . getDocumentElement ( ) . getAttribute ( "PolicyId" ) ) ; nodes = doc . getElementsByTagName ( "Subjects" ) ; if ( nodes . getLength ( ) == 0 ) { metadata . put ( "anySubject" , "T" ) ; } nodes = doc . getElementsByTagName ( "Resources" ) ; if ( nodes . getLength ( ) == 0 ) { metadata . put ( "anyResource" , "T" ) ; } nodes = doc . getElementsByTagName ( "Actions" ) ; if ( nodes . getLength ( ) == 0 ) { metadata . put ( "anyAction" , "T" ) ; } nodes = doc . getElementsByTagName ( "Environments" ) ; if ( nodes . getLength ( ) == 0 ) { metadata . put ( "anyEnvironment" , "T" ) ; } } catch ( Exception e ) { log . error ( e . getMessage ( ) ) ; } return metadata ; }
Obtains the metadata for the given document .
4,405
public static String getOptionalStringParameter ( Map < String , String > parameters , String parameterName , String defaultValue ) { validateParameters ( parameters ) ; validateParameterName ( parameterName ) ; String value = parameters . get ( parameterName ) ; return value == null ? defaultValue : value ; }
Get an optional String parameter If not found use the default value .
4,406
public static boolean getOptionalBooleanParameter ( Map < String , String > parameters , String parameterName , boolean defaultValue ) throws JournalException { validateParameters ( parameters ) ; validateParameterName ( parameterName ) ; String string = parameters . get ( parameterName ) ; if ( string == null ) { return defaultValue ; } else if ( string . equals ( VALUE_FALSE ) ) { return false ; } else if ( string . equals ( VALUE_TRUE ) ) { return true ; } else { throw new JournalException ( "'" + parameterName + "' parameter must be '" + VALUE_FALSE + "'(default) or '" + VALUE_TRUE + "'" ) ; } }
Get an optional boolean parameter . If not found use the default value .
4,407
public static File parseParametersForWritableDirectory ( Map < String , String > parameters , String parameterName ) throws JournalException { String directoryString = parameters . get ( parameterName ) ; if ( directoryString == null ) { throw new JournalException ( "'" + parameterName + "' is required." ) ; } File directory = new File ( directoryString ) ; if ( ! directory . exists ( ) ) { throw new JournalException ( "Directory '" + directory + "' does not exist." ) ; } if ( ! directory . isDirectory ( ) ) { throw new JournalException ( "Directory '" + directory + "' is not a directory." ) ; } if ( ! directory . canWrite ( ) ) { throw new JournalException ( "Directory '" + directory + "' is not writable." ) ; } return directory ; }
Look in the parameters for the path to a writable directory . The parameter is required .
4,408
public static String parseParametersForFilenamePrefix ( Map < String , String > parameters ) { return getOptionalStringParameter ( parameters , PARAMETER_JOURNAL_FILENAME_PREFIX , DEFAULT_FILENAME_PREFIX ) ; }
Look for a string to use as a prefix for the names of the journal files . Default is fedoraJournal
4,409
public void itemStateChanged ( ItemEvent e ) { if ( e . getStateChange ( ) == ItemEvent . DESELECTED ) { m_customPIDField . setEditable ( false ) ; } else if ( e . getStateChange ( ) == ItemEvent . SELECTED ) { m_customPIDField . setEditable ( true ) ; } }
for the checkbox
4,410
protected AbstractPolicy handleDocument ( Document doc , PolicyFinder policyFinder ) throws ParsingException { Element root = doc . getDocumentElement ( ) ; String name = root . getTagName ( ) ; if ( name . equals ( "Policy" ) ) { return Policy . getInstance ( root ) ; } else if ( name . equals ( "PolicySet" ) ) { return PolicySet . getInstance ( root , policyFinder ) ; } else { throw new ParsingException ( "Unknown root document type: " + name ) ; } }
A private method that handles reading the policy and creates the correct kind of AbstractPolicy . Because this makes use of the policyFinder it cannot be reused between finders . Consider moving to policyManager which is not intended to be reused outside of a policyFinderModule which is not intended to be reused amongst PolicyFinder instances .
4,411
protected static String [ ] makeComponents ( String resourceId ) { if ( resourceId == null || resourceId . isEmpty ( ) || ! resourceId . startsWith ( "/" ) ) { return null ; } List < String > components = new ArrayList < String > ( ) ; String [ ] parts = resourceId . split ( "\\/" ) ; int bufPrimer = 0 ; for ( int x = 1 ; x < parts . length ; x ++ ) { bufPrimer = Math . max ( bufPrimer , ( parts [ x ] . length ( ) + 1 ) ) ; StringBuilder sb = new StringBuilder ( bufPrimer ) ; for ( int y = 0 ; y < x ; y ++ ) { sb . append ( "/" ) ; sb . append ( parts [ y + 1 ] ) ; } String componentBase = sb . toString ( ) ; bufPrimer = componentBase . length ( ) + 16 ; components . add ( componentBase ) ; if ( x != parts . length - 1 ) { components . add ( componentBase . concat ( "/.*" ) ) ; } else { components . add ( componentBase . concat ( "$" ) ) ; } } return components . toArray ( parts ) ; }
Splits a XACML hierarchical resource - id value into a set of resource - id values that can be matched against a policy .
4,412
public String [ ] getDetails ( Locale locale ) { if ( m_details == null || m_details . length == 0 ) { return s_emptyStringArray ; } String [ ] ret = new String [ m_details . length ] ; for ( int i = 0 ; i < m_details . length ; i ++ ) { ret [ i ] = getLocalizedOrCode ( m_bundleName , locale , m_code , null ) ; } return ret ; }
Gets any detail messages preferring the provided locale .
4,413
private static String getLocalizedOrCode ( String bundleName , Locale locale , String code , String [ ] values ) { ResourceBundle bundle = null ; if ( bundleName != null ) { bundle = ResourceBundle . getBundle ( bundleName , locale ) ; } if ( bundle == null ) { return code ; } String locMessage = bundle . getString ( code ) ; if ( locMessage == null ) { return code ; } if ( values == null ) { return locMessage ; } return MessageFormat . format ( locMessage , ( Object [ ] ) values ) ; }
Gets the message from the resource bundle formatting it if needed and on failure just returns the code .
4,414
public Object invokeAndClose ( ManagementDelegate delegate , JournalWriter writer ) throws ServerException , JournalException { Object result = invokeMethod ( delegate , writer ) ; close ( ) ; return result ; }
A convenience method that invokes the management method and then closes the JournalEntry thereby cleaning up any temp files .
4,415
public static Datastream setDatastreamDefaults ( Datastream ds ) throws ObjectIntegrityException { if ( ( ds . DSMIME == null || ds . DSMIME . isEmpty ( ) ) && ds . DSControlGrp . equalsIgnoreCase ( "X" ) ) { ds . DSMIME = "text/xml" ; } if ( ds . DSState == null || ds . DSState . isEmpty ( ) ) { ds . DSState = "A" ; } if ( ds . DSInfoType == null || ds . DSInfoType . isEmpty ( ) || ds . DSInfoType . equalsIgnoreCase ( "OTHER" ) ) { ds . DSInfoType = "UNSPECIFIED" ; } if ( ds . DSControlGrp . equalsIgnoreCase ( "X" ) ) { if ( ( ( DatastreamXMLMetadata ) ds ) . DSMDClass != 0 && ds . DSFormatURI == null ) { String mdClassName = "" ; String mdType = ds . DSInfoType ; String otherType = "" ; if ( ( ( DatastreamXMLMetadata ) ds ) . DSMDClass == 1 ) { mdClassName = "techMD" ; } else if ( ( ( DatastreamXMLMetadata ) ds ) . DSMDClass == 2 ) { mdClassName = "sourceMD" ; } else if ( ( ( DatastreamXMLMetadata ) ds ) . DSMDClass == 3 ) { mdClassName = "rightsMD" ; } else if ( ( ( DatastreamXMLMetadata ) ds ) . DSMDClass == 4 ) { mdClassName = "digiprovMD" ; } else if ( ( ( DatastreamXMLMetadata ) ds ) . DSMDClass == 5 ) { mdClassName = "descMD" ; } if ( ! mdType . equals ( "MARC" ) && ! mdType . equals ( "EAD" ) && ! mdType . equals ( "DC" ) && ! mdType . equals ( "NISOIMG" ) && ! mdType . equals ( "LC-AV" ) && ! mdType . equals ( "VRA" ) && ! mdType . equals ( "TEIHDR" ) && ! mdType . equals ( "DDI" ) && ! mdType . equals ( "FGDC" ) ) { mdType = "OTHER" ; otherType = ds . DSInfoType ; } ds . DSFormatURI = "info:fedora/fedora-system:format/xml.mets." + mdClassName + "." + mdType + "." + otherType ; } } return ds ; }
Check for null values in attributes and set them to empty string so null does not appear in XML attribute values . This helps in XML validation of required attributes . If null is the attribute value then validation would incorrectly consider in a valid non - empty value . Also we set some other default values here .
4,416
protected static void appendXMLStream ( InputStream in , PrintWriter writer , String encoding ) throws ObjectIntegrityException , UnsupportedEncodingException , StreamIOException { if ( in == null ) { throw new ObjectIntegrityException ( "Object's inline xml " + "stream cannot be null." ) ; } try { InputStreamReader chars = new InputStreamReader ( in , Charset . forName ( encoding ) ) ; char [ ] charBuf = new char [ 4096 ] ; char [ ] wsBuf = new char [ 4096 ] ; int len ; int start ; int end ; int wsLen = 0 ; boolean atBeginning = true ; while ( ( len = chars . read ( charBuf ) ) != - 1 ) { start = 0 ; end = len - 1 ; if ( atBeginning ) { while ( start < len ) { if ( charBuf [ start ] > 0x20 ) break ; start ++ ; } if ( start < len ) atBeginning = false ; } if ( wsLen > 0 ) { writer . write ( wsBuf , 0 , wsLen ) ; wsLen = 0 ; } while ( end > start ) { if ( charBuf [ end ] > 0x20 ) break ; wsBuf [ wsLen ] = charBuf [ end ] ; wsLen ++ ; end -- ; } if ( start < len ) { writer . write ( charBuf , start , end + 1 - start ) ; } } } catch ( UnsupportedEncodingException uee ) { throw uee ; } catch ( IOException ioe ) { throw new StreamIOException ( "Error reading from inline xml datastream." ) ; } finally { try { in . close ( ) ; } catch ( IOException closeProb ) { throw new StreamIOException ( "Error closing read stream." ) ; } } }
Appends XML to a PrintWriter . Essentially just appends all text content of the inputStream trimming any leading and trailing whitespace . It does his in a streaming fashion with resource consumption entirely comprised of fixed internal buffers .
4,417
protected static void validateAudit ( AuditRecord audit ) throws ObjectIntegrityException { if ( audit . id == null || audit . id . isEmpty ( ) ) { throw new ObjectIntegrityException ( "Audit record must have id." ) ; } if ( audit . date == null ) { throw new ObjectIntegrityException ( "Audit record must have date." ) ; } if ( audit . processType == null || audit . processType . isEmpty ( ) ) { throw new ObjectIntegrityException ( "Audit record must have processType." ) ; } if ( audit . action == null || audit . action . isEmpty ( ) ) { throw new ObjectIntegrityException ( "Audit record must have action." ) ; } if ( audit . componentID == null ) { audit . componentID = "" ; } if ( audit . responsibility == null || audit . responsibility . isEmpty ( ) ) { throw new ObjectIntegrityException ( "Audit record must have responsibility." ) ; } }
The audit record is created by the system so programmatic validation here is o . k . Normally validation takes place via XML Schema and Schematron .
4,418
public String getValue ( boolean asAbsolutePath ) { String path = m_value ; if ( asAbsolutePath ) { if ( path != null && m_isFilePath ) { File f = new File ( path ) ; if ( ! f . isAbsolute ( ) ) { path = FEDORA_HOME + File . separator + path ; } } } return path ; }
Gets the value of the parameter . Prepends the location of FEDORA_HOME if asAbsolutePath is true and the parameter location does not already specify an absolute pathname .
4,419
public void addArgument ( String key , InputStream stream ) throws JournalException { checkOpen ( ) ; if ( stream == null ) { arguments . put ( key , null ) ; } else { try { File tempFile = JournalHelper . copyToTempFile ( stream ) ; arguments . put ( key , tempFile ) ; } catch ( IOException e ) { throw new JournalException ( e ) ; } } }
If handed an InputStream as an argument copy it to a temp file and store that File in the arguments map instead . If the InputStream is null store null in the arguments map .
4,420
public InputStream getStreamArgument ( String name ) throws JournalException { checkOpen ( ) ; File file = ( File ) arguments . get ( name ) ; if ( file == null ) { return null ; } else { try { return new FileInputStream ( file ) ; } catch ( FileNotFoundException e ) { throw new JournalException ( e ) ; } } }
If they ask for an InputStream argument get the File from the arguments map and create an InputStream on that file . If the value from the map is null return null .
4,421
public void close ( ) { checkOpen ( ) ; open = false ; for ( Object arg : arguments . values ( ) ) { if ( arg instanceof File ) { File file = ( File ) arg ; if ( JournalHelper . isTempFile ( file ) ) { if ( file . exists ( ) ) { file . delete ( ) ; } } } } }
This should be called when usage of the object is complete to clean up any temporary files that were created for the journal entry to use .
4,422
private File createTempFilename ( File permanentFile , File journalDirectory ) { String tempFilename = "_" + permanentFile . getName ( ) ; File file2 = new File ( journalDirectory , tempFilename ) ; return file2 ; }
The temporary filename is the permanent name preceded by an underscore .
4,423
private FileWriter createTempFile ( File tempfile ) throws IOException , JournalException { boolean created = tempfile . createNewFile ( ) ; if ( ! created ) { throw new JournalException ( "Unable to create file '" + tempfile . getPath ( ) + "'." ) ; } return new FileWriter ( tempfile ) ; }
Create and open the temporary file .
4,424
private XMLEventWriter createXmlEventWriter ( FileWriter fileWriter ) throws FactoryConfigurationError , XMLStreamException { XMLOutputFactory factory = XMLOutputFactory . newInstance ( ) ; return new IndentingXMLEventWriter ( factory . createXMLEventWriter ( fileWriter ) ) ; }
Create an XMLEventWriter for this file . Make it a pretty indenting writer .
4,425
public void closeIfAppropriate ( ) throws JournalException { synchronized ( JournalWriter . SYNCHRONIZER ) { if ( ! open ) { return ; } long currentSize = tempFile . length ( ) ; if ( sizeLimit > 0 && currentSize > sizeLimit ) { close ( ) ; } } }
Check the size limit and see whether the file is big enough to close . We could also check the age limit here but we trust the timer to handle that .
4,426
public void close ( ) throws JournalException { synchronized ( JournalWriter . SYNCHRONIZER ) { if ( ! open ) { return ; } try { parent . getDocumentTrailer ( xmlWriter ) ; xmlWriter . close ( ) ; fileWriter . close ( ) ; timer . cancel ( ) ; try { FileMovingUtil . move ( tempFile , file ) ; } catch ( IOException e ) { throw new JournalException ( "Failed to rename file from '" + tempFile . getPath ( ) + "' to '" + file . getPath ( ) + "'" , e ) ; } open = false ; } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } catch ( IOException e ) { throw new JournalException ( e ) ; } } }
Write the document trailer clean up everything and rename the file . Set the flag saying we are closed .
4,427
@ SuppressWarnings ( "unchecked" ) public Result combine ( EvaluationCtx context , @ SuppressWarnings ( "rawtypes" ) List parameters , @ SuppressWarnings ( "rawtypes" ) List policyElements ) { logger . info ( "Combining using: " + getIdentifier ( ) ) ; boolean atLeastOneError = false ; boolean atLeastOnePermit = false ; Set < Set < ? > > denyObligations = new HashSet < Set < ? > > ( ) ; Status firstIndeterminateStatus = null ; Set < AbstractPolicy > matchedPolicies = new HashSet < AbstractPolicy > ( ) ; Iterator < ? > it = policyElements . iterator ( ) ; while ( it . hasNext ( ) ) { AbstractPolicy policy = ( ( PolicyCombinerElement ) it . next ( ) ) . getPolicy ( ) ; MatchResult match = policy . match ( context ) ; if ( match . getResult ( ) == MatchResult . INDETERMINATE ) { atLeastOneError = true ; if ( firstIndeterminateStatus == null ) { firstIndeterminateStatus = match . getStatus ( ) ; } } else if ( match . getResult ( ) == MatchResult . MATCH ) { matchedPolicies . add ( policy ) ; } } Set < AbstractPolicy > applicablePolicies = getApplicablePolicies ( context , matchedPolicies ) ; for ( AbstractPolicy policy : applicablePolicies ) { Result result = policy . evaluate ( context ) ; int effect = result . getDecision ( ) ; if ( effect == Result . DECISION_DENY ) { denyObligations . addAll ( result . getObligations ( ) ) ; return new Result ( Result . DECISION_DENY , context . getResourceId ( ) . encode ( ) , denyObligations ) ; } if ( effect == Result . DECISION_PERMIT ) { atLeastOnePermit = true ; } else if ( effect == Result . DECISION_INDETERMINATE ) { atLeastOneError = true ; if ( firstIndeterminateStatus == null ) { firstIndeterminateStatus = result . getStatus ( ) ; } } } if ( atLeastOnePermit ) { return new Result ( Result . DECISION_PERMIT , context . getResourceId ( ) . encode ( ) ) ; } if ( atLeastOneError ) { return new Result ( Result . DECISION_INDETERMINATE , firstIndeterminateStatus , context . getResourceId ( ) . encode ( ) ) ; } return new Result ( Result . DECISION_NOT_APPLICABLE , context . getResourceId ( ) . encode ( ) ) ; }
Applies the combining rule to the set of policies based on the evaluation context .
4,428
private Object invokeTarget ( Object target , Method method , Object [ ] args ) throws Throwable { Object returnValue ; try { returnValue = method . invoke ( target , args ) ; } catch ( InvocationTargetException ite ) { throw ite . getTargetException ( ) ; } return returnValue ; }
Invoke the underlying method catching any InvocationTargetException and rethrowing the target exception
4,429
private void deletePolicy ( String pid ) throws GeneralException { LOG . debug ( "Deleting policy " + pid ) ; try { m_policyIndex . deletePolicy ( pid ) ; } catch ( PolicyIndexException e ) { throw new GeneralException ( "Error deleting policy " + pid + " from policy index: " + e . getMessage ( ) , e ) ; } }
Remove the specified policy from the cache
4,430
private final static int defaultPort ( String scheme ) { if ( scheme == null ) { return - 1 ; } Integer port = defaultPorts . get ( scheme . trim ( ) . toLowerCase ( ) ) ; return ( port != null ) ? port . intValue ( ) : - 1 ; }
Return the default port used by a given scheme .
4,431
public String describeAllowedMimeTypes ( ) { if ( bindingMIMETypes == null || bindingMIMETypes . length == 0 ) { return ANY_MIME_TYPE ; } StringBuffer out = new StringBuffer ( ) ; for ( int i = 0 ; i < bindingMIMETypes . length ; i ++ ) { String allowed = bindingMIMETypes [ i ] ; if ( allowed == null ) { return ANY_MIME_TYPE ; } if ( allowed . equals ( "*/*" ) ) { return ANY_MIME_TYPE ; } if ( allowed . equals ( "*" ) ) { return ANY_MIME_TYPE ; } if ( i > 0 ) { if ( i < bindingMIMETypes . length - 1 ) { out . append ( ", " ) ; } else { if ( i > 1 ) { out . append ( "," ) ; } out . append ( " or " ) ; } } out . append ( allowed ) ; } return out . toString ( ) ; }
In human readable string describe which mime types are allowed .
4,432
public void postInitModule ( ) throws ModuleInitializationException { ManagementDelegate delegate = serverInterface . getManagementDelegate ( ) ; if ( delegate == null ) { throw new ModuleInitializationException ( "Can't get a ManagementDelegate from Server.getModule()" , getRole ( ) ) ; } worker . setManagementDelegate ( delegate ) ; }
Get the ManagementDelegate module and pass it to the worker .
4,433
private void copyPropertiesOverParameters ( Map < String , String > parameters ) { Properties properties = System . getProperties ( ) ; for ( Object object : properties . keySet ( ) ) { String key = ( String ) object ; if ( key . startsWith ( SYSTEM_PROPERTY_PREFIX ) ) { parameters . put ( key . substring ( SYSTEM_PROPERTY_PREFIX . length ( ) ) , properties . getProperty ( key ) ) ; } } }
Augment and perhaps override the server parameters using any System Property whose name begins with fedora . journal . . So for example a System Property of fedora . journal . mode will override a server parameter of mode .
4,434
private void parseParameters ( Map < String , String > parameters ) throws ModuleInitializationException { logger . info ( "Parameters: " + parameters ) ; String mode = parameters . get ( PARAMETER_JOURNAL_MODE ) ; if ( mode == null ) { inRecoveryMode = false ; } else if ( mode . equals ( VALUE_JOURNAL_MODE_NORMAL ) ) { inRecoveryMode = false ; } else if ( mode . equals ( VALUE_JOURNAL_MODE_RECOVER ) ) { inRecoveryMode = true ; } else { throw new ModuleInitializationException ( "'" + PARAMETER_JOURNAL_MODE + "' parameter must be '" + VALUE_JOURNAL_MODE_NORMAL + "'(default) or '" + VALUE_JOURNAL_MODE_RECOVER + "'" , getRole ( ) ) ; } }
Check the parameters for required values and for acceptable values . At this point the only parameter we care about is mode .
4,435
public static JournalReader getInstance ( Map < String , String > parameters , String role , JournalRecoveryLog recoveryLog , ServerInterface server ) throws ModuleInitializationException { try { Object journalReader = JournalHelper . createInstanceAccordingToParameter ( PARAMETER_JOURNAL_READER_CLASSNAME , new Class [ ] { Map . class , String . class , JournalRecoveryLog . class , ServerInterface . class } , new Object [ ] { parameters , role , recoveryLog , server } , parameters ) ; logger . info ( "JournalReader is " + journalReader . toString ( ) ) ; return ( JournalReader ) journalReader ; } catch ( JournalException e ) { String msg = "Can't create JournalReader" ; logger . error ( msg , e ) ; throw new ModuleInitializationException ( msg , role , e ) ; } }
Create an instance of the proper JournalReader child class as determined by the server parameters .
4,436
protected void checkRepositoryHash ( String hash ) throws JournalException { if ( ! server . hasInitialized ( ) ) { throw new IllegalStateException ( "The repository has is not available until " + "the server is fully initialized." ) ; } JournalException hashException = null ; if ( hash == null ) { hashException = new JournalException ( "'" + QNAME_TAG_JOURNAL + "' tag must have a '" + QNAME_ATTR_REPOSITORY_HASH + "' attribute." ) ; } else { try { String currentHash = server . getRepositoryHash ( ) ; if ( hash . equals ( currentHash ) ) { recoveryLog . log ( "Validated repository hash: '" + hash + "'." ) ; } else { hashException = new JournalException ( "'" + QNAME_ATTR_REPOSITORY_HASH + "' attribute in '" + QNAME_TAG_JOURNAL + "' tag does not match current repository hash: '" + hash + "' vs. '" + currentHash + "'." ) ; } } catch ( ServerException e ) { hashException = new JournalException ( e ) ; } } if ( hashException != null ) { if ( ignoreHashErrors ) { recoveryLog . log ( "WARNING: " + hashException . getMessage ( ) ) ; } else { throw hashException ; } } }
Compare the repository hash from the journal file with the current hash obtained from the server . If they do not match either throw an exception or simply log it depending on the parameters . 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,437
private StartElement getJournalEntryStartTag ( XMLEventReader reader ) throws XMLStreamException , JournalException { XMLEvent event = reader . nextTag ( ) ; if ( ! isStartTagEvent ( event , QNAME_TAG_JOURNAL_ENTRY ) ) { throw getNotStartTagException ( QNAME_TAG_JOURNAL_ENTRY , event ) ; } return event . asStartElement ( ) ; }
Get the next event and complain if it isn t a JournalEntry start tag .
4,438
private void readArguments ( XMLEventReader reader , ConsumerJournalEntry cje ) throws XMLStreamException , JournalException { while ( true ) { XMLEvent nextTag = reader . nextTag ( ) ; if ( isStartTagEvent ( nextTag , QNAME_TAG_ARGUMENT ) ) { readArgument ( nextTag , reader , cje ) ; } else if ( isEndTagEvent ( nextTag , QNAME_TAG_JOURNAL_ENTRY ) ) { return ; } else { throw getNotNextMemberOrEndOfGroupException ( QNAME_TAG_JOURNAL_ENTRY , QNAME_TAG_ARGUMENT , nextTag ) ; } } }
Read arguments and add them to the event until we hit the end tag for the event .
4,439
private void readStreamArgument ( XMLEventReader reader , ConsumerJournalEntry journalEntry , String name ) throws XMLStreamException , JournalException { try { File tempFile = JournalHelper . createTempFile ( ) ; DecodingBase64OutputStream decoder = new DecodingBase64OutputStream ( new FileOutputStream ( tempFile ) ) ; while ( true ) { XMLEvent event = reader . nextEvent ( ) ; if ( event . isCharacters ( ) ) { decoder . write ( event . asCharacters ( ) . getData ( ) ) ; } else if ( isEndTagEvent ( event , QNAME_TAG_ARGUMENT ) ) { break ; } else { throw getUnexpectedEventInArgumentException ( name , ARGUMENT_TYPE_STREAM , journalEntry . getMethodName ( ) , event ) ; } } decoder . close ( ) ; journalEntry . addArgument ( name , tempFile ) ; } catch ( IOException e ) { throw new JournalException ( "failed to write stream argument to temp file" , e ) ; } }
An InputStream argument appears as a Base64 - encoded String . It must be decoded and written to a temp file so it can be presented to the management method as an InputStream again .
4,440
private JournalException getUnexpectedEventInArgumentException ( String name , String argumentType , String methodName , XMLEvent event ) { return new JournalException ( "Unexpected event while processing '" + name + "' argument (type = '" + argumentType + "') for '" + methodName + "' method call: event is '" + event + "'" ) ; }
If we encounter an unexpected event when reading the a method argument create an exception with all of the pertinent information .
4,441
public void addDatastream ( Datastream datastream , boolean addNewVersion ) throws ServerException { assertNotInvalidated ( ) ; assertNotPendingRemoval ( ) ; m_obj . addDatastreamVersion ( datastream , addNewVersion ) ; }
Adds a datastream to the object .
4,442
public Date [ ] removeDatastream ( String id , Date start , Date end ) throws ServerException { assertNotInvalidated ( ) ; assertNotPendingRemoval ( ) ; ArrayList < Datastream > removeList = new ArrayList < Datastream > ( ) ; for ( Datastream ds : m_obj . datastreams ( id ) ) { boolean doRemove = false ; if ( start != null ) { if ( end != null ) { if ( ds . DSCreateDT . compareTo ( start ) >= 0 && ds . DSCreateDT . compareTo ( end ) <= 0 ) { doRemove = true ; } } else { if ( ds . DSCreateDT . compareTo ( start ) >= 0 ) { doRemove = true ; } } } else { if ( end != null ) { if ( ds . DSCreateDT . compareTo ( end ) <= 0 ) { doRemove = true ; } } else { doRemove = true ; } } if ( doRemove ) { removeList . add ( ds ) ; } } for ( Datastream toRemove : removeList ) { m_obj . removeDatastreamVersion ( toRemove ) ; } Date [ ] deletedDates = new Date [ removeList . size ( ) ] ; for ( int i = 0 ; i < removeList . size ( ) ; i ++ ) { deletedDates [ i ] = ( removeList . get ( i ) ) . DSCreateDT ; } return deletedDates ; }
Removes a datastream from the object .
4,443
private String resolveSubjectToDatastream ( String subject ) throws ServerException { String pidURI = PID . toURI ( m_obj . getPid ( ) ) ; if ( subject . startsWith ( pidURI ) ) { if ( subject . length ( ) == pidURI . length ( ) ) { return "RELS-EXT" ; } if ( subject . charAt ( pidURI . length ( ) ) == '/' ) { return "RELS-INT" ; } } throw new GeneralException ( "Cannot determine which relationship datastream to update for subject " + subject + ". Relationship subjects must be the URI of the object or the URI of a datastream within the object." ) ; }
from the relationship subject determine which datastream to modify etc
4,444
public void commit ( String logMessage ) throws ServerException { assertNotInvalidated ( ) ; m_mgr . doCommit ( Server . USE_DEFINITIVE_STORE , m_context , m_obj , logMessage , m_pendingRemoval ) ; m_committed = true ; invalidate ( ) ; }
Saves the changes thus far to the permanent copy of the digital object .
4,445
public void write ( char [ ] cbuf , int off , int len ) throws IOException { try { String indexedHash = RmiJournalReceiverHelper . figureIndexedHash ( repositoryHash , itemIndex ) ; receiver . writeText ( indexedHash , new String ( cbuf , off , len ) ) ; itemIndex ++ ; } catch ( JournalException e ) { throw new IOException ( e ) ; } }
Each time characters are written send them to the receiver . Keep track of how many writes so we can create a proper item hash .
4,446
public void close ( ) throws IOException { try { if ( ! m_closed ) { receiver . closeFile ( ) ; m_closed = true ; } } catch ( JournalException e ) { throw new IOException ( e ) ; } }
Time to close the file? Tell the receiver .
4,447
@ SuppressWarnings ( "unchecked" ) public static Map < String , Set < String > > getAttributes ( Subject subject ) { Map < String , Set < String > > attributes = null ; if ( subject . getPublicCredentials ( ) == null ) { return new HashMap < String , Set < String > > ( ) ; } @ SuppressWarnings ( "rawtypes" ) Iterator < HashMap > credentialObjects = subject . getPublicCredentials ( HashMap . class ) . iterator ( ) ; while ( attributes == null && credentialObjects . hasNext ( ) ) { HashMap < ? , ? > credentialObject = credentialObjects . next ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "checking for attributes (class name): " + credentialObject . getClass ( ) . getName ( ) ) ; } Object key = null ; Iterator < ? > keys = null ; keys = credentialObject . keySet ( ) . iterator ( ) ; if ( ! keys . hasNext ( ) ) { continue ; } key = keys . next ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "checking for attributes (key object name): " + key . getClass ( ) . getName ( ) ) ; } if ( ! ( key instanceof String ) ) { continue ; } keys = credentialObject . values ( ) . iterator ( ) ; if ( ! keys . hasNext ( ) ) { continue ; } key = keys . next ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "checking for attributes (value object name): " + key . getClass ( ) . getName ( ) ) ; } if ( ! ( key instanceof HashSet ) ) { continue ; } attributes = ( Map < String , Set < String > > ) credentialObject ; } if ( attributes == null ) { attributes = new HashMap < String , Set < String > > ( ) ; subject . getPublicCredentials ( ) . add ( attributes ) ; } return attributes ; }
Get the attribute map of String keys to Set&lt ; String&gt ; values This method will not return a null
4,448
public void closeAndRename ( File archiveDirectory ) throws JournalException { try { xmlReader . close ( ) ; fileReader . close ( ) ; File archiveFile = new File ( archiveDirectory , file . getName ( ) ) ; try { FileMovingUtil . move ( file , archiveFile ) ; } catch ( IOException e ) { throw new JournalException ( "Failed to rename file from '" + file . getPath ( ) + "' to '" + archiveFile . getPath ( ) + "'" , e ) ; } } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } catch ( IOException e ) { throw new JournalException ( e ) ; } }
When we have processed the file move it to the archive directory .
4,449
public void doNew ( String [ ] dropdownMimeTypes , boolean makeSelected ) { int i = getTabIndex ( "New..." ) ; m_tabbedPane . setComponentAt ( i , new NewDatastreamPane ( dropdownMimeTypes ) ) ; i = getTabIndex ( "New..." ) ; m_tabbedPane . setToolTipTextAt ( i , "Add a new datastream to this object" ) ; m_tabbedPane . setIconAt ( i , newIcon ) ; m_tabbedPane . setBackgroundAt ( i , Administrator . DEFAULT_COLOR ) ; if ( makeSelected ) { m_tabbedPane . setSelectedIndex ( i ) ; } }
Set the content of the New ... JPanel to a fresh new datastream entry panel and switch to it if needed .
4,450
public void updateNewRelsExt ( String pid ) throws Exception { if ( ! hasRelsExt ( ) && getTabIndex ( "New RELS-EXT..." ) == - 1 ) { m_tabbedPane . insertTab ( "New RELS-EXT..." , newIcon , new NewRelsExtDatastreamPane ( m_owner , pid , this ) , "Add a RELS-EXT datastream to this object" , getTabIndex ( "New..." ) ) ; int i = getTabIndex ( "New RELS-EXT..." ) ; m_tabbedPane . setBackgroundAt ( i , Administrator . DEFAULT_COLOR ) ; } else if ( hasRelsExt ( ) && getTabIndex ( "New RELS-EXT..." ) != - 1 ) { m_tabbedPane . remove ( getTabIndex ( "New RELS-EXT..." ) ) ; } }
Set the content of the New Rels - Ext ... JPanel to a fresh new datastream entry panel and switch to it if needed .
4,451
private int getDatastreamPaneIndex ( String id ) { int index = - 1 ; for ( int i = 0 ; i < m_datastreamPanes . length ; i ++ ) { if ( m_datastreamPanes [ i ] . getItemId ( ) . equals ( id ) ) { index = i ; break ; } } return index ; }
Gets the index of the pane containing the datastream with the given id .
4,452
protected void refresh ( String dsID ) { int i = getTabIndex ( dsID ) ; try { List < Datastream > versions = Administrator . APIM . getDatastreamHistory ( m_pid , dsID ) ; m_currentVersionMap . put ( dsID , versions . get ( i ) ) ; logger . debug ( "New create date is: " + versions . get ( i ) . getCreateDate ( ) ) ; DatastreamPane replacement = new DatastreamPane ( m_owner , m_pid , versions , this ) ; m_datastreamPanes [ i ] = replacement ; m_tabbedPane . setComponentAt ( i , replacement ) ; m_tabbedPane . setToolTipTextAt ( i , versions . get ( i ) . getMIMEType ( ) + " - " + versions . get ( i ) . getLabel ( ) + " (" + versions . get ( i ) . getControlGroup ( ) . toString ( ) + ")" ) ; colorTabForState ( dsID , versions . get ( i ) . getState ( ) ) ; setDirty ( dsID , false ) ; } catch ( Exception e ) { Administrator . showErrorDialog ( Administrator . getDesktop ( ) , "Error while refreshing" , e . getMessage ( ) + "\nTry re-opening the object viewer." , e ) ; } }
Refresh the content of the tab for the indicated datastream with the latest information from the server .
4,453
protected void addDatastreamTab ( String dsID , boolean reInitNewPanel ) throws Exception { DatastreamPane [ ] newArray = new DatastreamPane [ m_datastreamPanes . length + 1 ] ; for ( int i = 0 ; i < m_datastreamPanes . length ; i ++ ) { newArray [ i ] = m_datastreamPanes [ i ] ; } List < Datastream > versions = Administrator . APIM . getDatastreamHistory ( m_pid , dsID ) ; m_currentVersionMap . put ( dsID , versions . get ( 0 ) ) ; newArray [ m_datastreamPanes . length ] = new DatastreamPane ( m_owner , m_pid , versions , this ) ; m_datastreamPanes = newArray ; int newIndex = getTabIndex ( "New..." ) ; m_tabbedPane . add ( m_datastreamPanes [ m_datastreamPanes . length - 1 ] , newIndex ) ; m_tabbedPane . setTitleAt ( newIndex , dsID ) ; m_tabbedPane . setToolTipTextAt ( newIndex , versions . get ( 0 ) . getMIMEType ( ) + " - " + versions . get ( 0 ) . getLabel ( ) + " (" + versions . get ( 0 ) . getControlGroup ( ) . toString ( ) + ")" ) ; colorTabForState ( dsID , versions . get ( 0 ) . getState ( ) ) ; if ( reInitNewPanel ) { doNew ( XML_MIMETYPE , false ) ; } updateNewRelsExt ( m_pid ) ; m_tabbedPane . setSelectedIndex ( getTabIndex ( dsID ) ) ; }
Add a new tab with a new datastream .
4,454
private void loginForm ( HttpServletResponse response ) throws IOException { response . reset ( ) ; response . addHeader ( "WWW-Authenticate" , "Basic realm=\"!!Fedora Repository Server\"" ) ; response . setStatus ( HttpServletResponse . SC_UNAUTHORIZED ) ; OutputStream out = response . getOutputStream ( ) ; out . write ( "Fedora: 401 " . getBytes ( ) ) ; out . flush ( ) ; out . close ( ) ; }
Sends a 401 error to the browser . This forces a login box to be displayed allowing the user to login .
4,455
private Subject authenticate ( HttpServletRequest req ) { String authorization = req . getHeader ( "authorization" ) ; if ( authorization == null || authorization . trim ( ) . isEmpty ( ) ) { return null ; } Subject subject = ( Subject ) req . getSession ( ) . getAttribute ( authorization ) ; if ( subject != null ) { return subject ; } String auth = null ; try { byte [ ] data = Base64 . decode ( authorization . substring ( 6 ) ) ; auth = new String ( data ) ; } catch ( IOException e ) { logger . error ( e . toString ( ) ) ; return null ; } String username = auth . substring ( 0 , auth . indexOf ( ':' ) ) ; String password = auth . substring ( auth . indexOf ( ':' ) + 1 ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "auth username: " + username ) ; } LoginContext loginContext = null ; try { CallbackHandler handler = new UsernamePasswordCallbackHandler ( username , password ) ; loginContext = new LoginContext ( jaasConfigName , handler ) ; loginContext . login ( ) ; } catch ( LoginException le ) { logger . error ( le . toString ( ) ) ; return null ; } subject = loginContext . getSubject ( ) ; req . getSession ( ) . setAttribute ( SESSION_SUBJECT_KEY , subject ) ; req . getSession ( ) . setAttribute ( authorization , subject ) ; return subject ; }
Performs the authentication . Once a Subject is obtained it is stored in the users session . Subsequent requests check for the existence of this object before performing the authentication again .
4,456
private Principal getUserPrincipal ( Subject subject ) { Principal userPrincipal = null ; Set < Principal > principals = subject . getPrincipals ( ) ; if ( userClassNames != null && userClassNames . size ( ) > 0 ) { for ( Principal p : principals ) { if ( userPrincipal == null && userClassNames . contains ( p . getClass ( ) . getName ( ) ) ) { userPrincipal = p ; } } } if ( userPrincipal == null ) { Iterator < Principal > i = principals . iterator ( ) ; if ( i . hasNext ( ) ) { userPrincipal = i . next ( ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "found userPrincipal [{}]: {}" , userPrincipal . getClass ( ) . getName ( ) , userPrincipal . getName ( ) ) ; } return userPrincipal ; }
Given a subject obtain the userPrincipal from it . The user principal is defined by a Principal class that can be defined in the web . xml file . If this is undefined the first principal found is assumed to be the userPrincipal .
4,457
private Set < String > getUserRoles ( Subject subject ) { Set < String > userRoles = null ; Set < Principal > principals = subject . getPrincipals ( ) ; if ( roleClassNames != null && roleClassNames . size ( ) > 0 ) { for ( Principal p : principals ) { if ( roleClassNames . contains ( p . getClass ( ) . getName ( ) ) ) { if ( userRoles == null ) userRoles = new HashSet < String > ( ) ; userRoles . add ( p . getName ( ) ) ; } } } Map < String , Set < String > > attributes = SubjectUtils . getAttributes ( subject ) ; for ( String key : attributes . keySet ( ) ) { if ( roleAttributeNames . contains ( key ) ) { if ( userRoles == null ) userRoles = new HashSet < String > ( ) ; userRoles . addAll ( attributes . get ( key ) ) ; } } if ( userRoles == null ) userRoles = Collections . emptySet ( ) ; if ( logger . isDebugEnabled ( ) ) { for ( String r : userRoles ) { logger . debug ( "found role: {}" , r ) ; } } return userRoles ; }
Obtains the roles for the user based on the class names and attribute names provided in the web . xml file .
4,458
private void addRolesToSubject ( Subject subject , Set < String > userRoles ) { if ( userRoles == null ) { userRoles = Collections . emptySet ( ) ; } Map < String , Set < String > > attributes = SubjectUtils . getAttributes ( subject ) ; Set < String > roles = attributes . get ( ROLE_KEY ) ; if ( roles == null ) { roles = new HashSet < String > ( userRoles ) ; attributes . put ( ROLE_KEY , roles ) ; } else { roles . addAll ( userRoles ) ; } if ( logger . isDebugEnabled ( ) ) { for ( String role : userRoles ) { logger . debug ( "added role: {}" , role ) ; } } }
Adds roles to the Subject object .
4,459
private void populateFedoraAttributes ( Subject subject , Set < String > userRoles , HttpServletRequest request ) { Map < String , Set < String > > attributes = SubjectUtils . getAttributes ( subject ) ; Set < String > roles = attributes . get ( FEDORA_ROLE_KEY ) ; if ( roles == null ) { roles = new HashSet < String > ( userRoles ) ; attributes . put ( FEDORA_ROLE_KEY , roles ) ; } else { roles . addAll ( userRoles ) ; } request . setAttribute ( FEDORA_ATTRIBUTES_KEY , attributes ) ; }
Add roles and other subject attributes where Fedora expects them - a Map called FEDORA_AUX_SUBJECT_ATTRIBUTES . Roles will be put in fedoraRole and others will be named as - is .
4,460
private void denyAccess ( HttpServletResponse response , String message ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Fedora: 403 " ) . append ( message . toUpperCase ( ) ) ; response . reset ( ) ; response . setStatus ( HttpServletResponse . SC_FORBIDDEN ) ; response . setContentType ( "text/plain" ) ; response . setContentLength ( sb . length ( ) ) ; ServletOutputStream out = response . getOutputStream ( ) ; out . write ( sb . toString ( ) . getBytes ( ) ) ; out . flush ( ) ; out . close ( ) ; }
Outputs an access denied message .
4,461
private void loginForm ( HttpServletResponse response ) { response . reset ( ) ; response . addHeader ( "WWW-Authenticate" , "Basic realm=\"!!Fedora Repository Server\"" ) ; response . setStatus ( HttpServletResponse . SC_UNAUTHORIZED ) ; }
Sends a 401 error to the browser . This forces a login screen to be displayed allowing the user to login .
4,462
public void shutdown ( ) throws ModuleShutdownException { try { consumerThread . shutdown ( ) ; reader . shutdown ( ) ; recoveryLog . shutdown ( "Server is shutting down." ) ; } catch ( JournalException e ) { throw new ModuleShutdownException ( "Error closing journal reader." , role , e ) ; } }
Tell the thread the reader and the log to shut down .
4,463
public static PID getInstance ( String pidString ) { try { return new PID ( pidString ) ; } catch ( MalformedPIDException e ) { throw new FaultException ( "Malformed PID: " + e . getMessage ( ) , e ) ; } }
Factory method that throws an unchecked exception if it s not well - formed .
4,464
public static String normalize ( String pidString ) throws MalformedPIDException { if ( pidString == null ) { throw new MalformedPIDException ( "PID is null." ) ; } return normalize ( pidString , 0 , pidString . length ( ) ) ; }
Return the normalized form of the given pid string or throw a MalformedPIDException .
4,465
public static SimpleURIReference toURIReference ( String pidString ) { SimpleURIReference ref = null ; try { ref = new SimpleURIReference ( new URI ( toURI ( pidString ) ) ) ; } catch ( URISyntaxException e ) { throw new Error ( e ) ; } return ref ; }
Return a URIReference of some PID string assuming it is well - formed .
4,466
public static void main ( String [ ] args ) throws Exception { if ( args . length > 0 ) { PID p = new PID ( args [ 0 ] ) ; System . out . println ( "Normalized : " + p . toString ( ) ) ; System . out . println ( "To filename : " + p . toFilename ( ) ) ; System . out . println ( "From filename : " + PID . fromFilename ( p . toFilename ( ) ) . toString ( ) ) ; } else { System . out . println ( "--------------------------------------" ) ; System . out . println ( "PID Syntax Checker - Interactive mode" ) ; System . out . println ( "--------------------------------------" ) ; boolean done = false ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( System . in ) ) ; while ( ! done ) { try { System . out . print ( "Enter a PID (ENTER to exit): " ) ; String line = reader . readLine ( ) ; if ( line . isEmpty ( ) ) { done = true ; } else { PID p = new PID ( line ) ; System . out . println ( "Normalized : " + p . toString ( ) ) ; System . out . println ( "To filename : " + p . toFilename ( ) ) ; System . out . println ( "From filename : " + PID . fromFilename ( p . toFilename ( ) ) . toString ( ) ) ; } } catch ( MalformedPIDException e ) { System . out . println ( "ERROR: " + e . getMessage ( ) ) ; } } } }
Command - line interactive tester . If one arg given prints normalized form of that PID and exits . If no args enters interactive mode .
4,467
private ObjectFields getObjectFields ( String pid ) throws UnrecognizedFieldException , ObjectIntegrityException , RepositoryConfigurationException , StreamIOException , ServerException { DOReader r = m_repoReader . getReader ( Server . USE_DEFINITIVE_STORE , ReadOnlyContext . EMPTY , pid ) ; ObjectFields f ; Datastream dcmd = null ; try { dcmd = r . GetDatastream ( "DC" , null ) ; } catch ( ClassCastException cce ) { throw new ObjectIntegrityException ( "Object " + r . GetObjectPID ( ) + " has a DC datastream, but it's not inline XML." ) ; } if ( dcmd != null ) { f = new ObjectFields ( m_resultFields , dcmd . getContentStream ( ) ) ; for ( String element : m_resultFields ) { if ( element . equals ( "dcmDate" ) ) { f . setDCMDate ( dcmd . DSCreateDT ) ; } } } else { f = new ObjectFields ( ) ; } for ( String n : m_resultFields ) { if ( n . equals ( "pid" ) ) { f . setPid ( pid ) ; } if ( n . equals ( "label" ) ) { f . setLabel ( r . GetObjectLabel ( ) ) ; } if ( n . equals ( "state" ) ) { f . setState ( r . GetObjectState ( ) ) ; } if ( n . equals ( "ownerId" ) ) { f . setOwnerId ( r . getOwnerId ( ) ) ; } if ( n . equals ( "cDate" ) ) { f . setCDate ( r . getCreateDate ( ) ) ; } if ( n . equals ( "mDate" ) ) { f . setMDate ( r . getLastModDate ( ) ) ; } } return f ; }
For the given pid get a reader on the object from the repository and return an ObjectFields object with resultFields fields populated .
4,468
private static final boolean isDCProp ( String in ) { if ( in . equals ( "mDate" ) || in . equals ( "dcmDate" ) ) { return false ; } for ( String n : FieldSearchSQLImpl . DB_COLUMN_NAMES ) { if ( n . startsWith ( "dc" ) && n . toLowerCase ( ) . indexOf ( in . toLowerCase ( ) ) == 2 ) { return true ; } } return false ; }
Tell whether a field name as given in the search request is a dublin core field .
4,469
public Set < Triple > getTriplesForObject ( DOReader reader ) throws ResourceIndexException { Set < Triple > objectTriples = new HashSet < Triple > ( ) ; try { for ( String modelRelobject : reader . getContentModels ( ) ) { if ( m_generators . containsKey ( modelRelobject ) ) { objectTriples . addAll ( m_generators . get ( modelRelobject ) . getTriplesForObject ( reader ) ) ; } } } catch ( ServerException e ) { throw new ResourceIndexException ( "Could not read object's content model" , e ) ; } return objectTriples ; }
Gets all triples implied by the object s models .
4,470
public void validate ( StreamSource objectSource ) throws ServerException { DOValidatorSchematronResult result = null ; try { Transformer vtransformer = validatingStyleSheet . newTransformer ( ) ; DOMResult validationResult = new DOMResult ( ) ; vtransformer . transform ( objectSource , validationResult ) ; result = new DOValidatorSchematronResult ( validationResult ) ; } catch ( Exception e ) { Validation validation = new Validation ( "unknown" ) ; String problem = "Schematron validation failed:" . concat ( e . getMessage ( ) ) ; validation . setObjectProblems ( Collections . singletonList ( problem ) ) ; logger . error ( "Schematron validation failed" , e ) ; throw new ObjectValidityException ( e . getMessage ( ) , validation ) ; } if ( ! result . isValid ( ) ) { String msg = null ; try { msg = result . getXMLResult ( ) ; } catch ( Exception e ) { logger . warn ( "Error getting XML result of schematron validation failure" , e ) ; } Validation validation = new Validation ( "unknown" ) ; if ( msg == null ) { msg = "Unknown schematron error. Error getting XML results of schematron validation" ; } validation . setObjectProblems ( Collections . singletonList ( msg ) ) ; throw new ObjectValidityException ( msg , validation ) ; } }
Run the Schematron validation on a Fedora object .
4,471
private Templates setUp ( String preprocessorPath , String fedoraschemaPath , String phase ) throws ObjectValidityException , TransformerException { String key = fedoraschemaPath + "#" + phase ; Templates templates = generatedStyleSheets . get ( key ) ; if ( templates == null ) { rulesSource = fileToStreamSource ( fedoraschemaPath ) ; preprocessorSource = fileToStreamSource ( preprocessorPath ) ; templates = createValidatingStyleSheet ( rulesSource , preprocessorSource , phase ) ; generatedStyleSheets . put ( key , templates ) ; } return templates ; }
Run setup to prepare for Schematron validation . This entails dynamically creating the validating stylesheet using the preprocessor and the schema .
4,472
private Templates createValidatingStyleSheet ( StreamSource rulesSource , StreamSource preprocessorSource , String phase ) throws ObjectValidityException , TransformerException { ReadableCharArrayWriter out = new ReadableCharArrayWriter ( 4096 ) ; try { Transformer ptransformer = XmlTransformUtility . getTransformer ( preprocessorSource ) ; ptransformer . setParameter ( "phase" , phase ) ; ptransformer . transform ( rulesSource , new StreamResult ( out ) ) ; out . close ( ) ; } catch ( Exception e ) { logger . error ( "Schematron validation failed" , e ) ; throw new ObjectValidityException ( e . getMessage ( ) ) ; } return XmlTransformUtility . getTemplates ( new StreamSource ( out . toReader ( ) ) ) ; }
Create the validating stylesheet which will be used to perform the actual Schematron validation . The validating stylesheet is created dynamically using the preprocessor stylesheet and the Schematron schema for Fedora . The phase is key . The stylesheet is created for the appropriate phase as specified in the Schematron rules schema . Valid work flow phases are currently ingest and store . Different schematron rules apply to different phases of the object lifecycle . Some rules are applied when an object is first being ingested into the repository . Other rules apply before the object is put into permanent storage .
4,473
public boolean exists ( String pid ) throws LowlevelStorageException { Connection connection = null ; PreparedStatement statement = null ; ResultSet rs = null ; try { connection = connectionPool . getReadOnlyConnection ( ) ; statement = connection . prepareStatement ( selectByIdQuery ) ; statement . setString ( 1 , pid ) ; rs = statement . executeQuery ( ) ; return rs . next ( ) ; } catch ( SQLException e1 ) { throw new LowlevelStorageException ( true , "sql failure (get)" , e1 ) ; } finally { try { if ( rs != null ) { rs . close ( ) ; } if ( statement != null ) { statement . close ( ) ; } if ( connection != null ) { connectionPool . free ( connection ) ; } } catch ( Exception e2 ) { throw new LowlevelStorageException ( true , "sql failure closing statement, connection, pool (get)" , e2 ) ; } finally { rs = null ; statement = null ; connection = null ; } } }
Checks to see whether a pid exists in the registry . Makes no audits of the number of registrations or the paths registered .
4,474
private void setObjectDefaults ( DigitalObject obj ) { if ( obj . getCreateDate ( ) == null ) obj . setCreateDate ( m_now ) ; if ( obj . getLastModDate ( ) == null ) obj . setLastModDate ( m_now ) ; Iterator < String > dsIds = obj . datastreamIdIterator ( ) ; while ( dsIds . hasNext ( ) ) { String dsid = dsIds . next ( ) ; for ( Datastream ds : obj . datastreams ( dsid ) ) { ds . DSSize = 0 ; if ( ds . DSCreateDT == null ) { ds . DSCreateDT = m_now ; } } } }
- Sets datastream sizes to 0
4,475
public static void main ( String [ ] args ) throws ClassNotFoundException { LogConfig . initMinimal ( ) ; if ( args . length < 4 || args . length > 7 ) { die ( "Expected 4 to 7 arguments" , true ) ; } File sourceDir = new File ( args [ 0 ] ) ; if ( ! sourceDir . isDirectory ( ) ) { die ( "Not a directory: " + sourceDir . getPath ( ) , false ) ; } File destDir = new File ( args [ 1 ] ) ; @ SuppressWarnings ( "unchecked" ) Class < DODeserializer > deserializer = ( Class < DODeserializer > ) Class . forName ( args [ 2 ] ) ; @ SuppressWarnings ( "unchecked" ) Class < DOSerializer > serializer = ( Class < DOSerializer > ) Class . forName ( args [ 3 ] ) ; System . setProperty ( "fedora.hostname" , "localhost" ) ; System . setProperty ( "fedora.port" , "8080" ) ; System . setProperty ( "fedora.appServerContext" , Constants . FEDORA_DEFAULT_APP_CONTEXT ) ; boolean pretty = args . length > 4 && args [ 4 ] . equals ( "true" ) ; String inExt = "xml" ; if ( args . length > 5 ) inExt = args [ 5 ] ; String outExt = "xml" ; if ( args . length > 6 ) outExt = args [ 6 ] ; ConvertObjectSerialization converter = new ConvertObjectSerialization ( deserializer , serializer , pretty , inExt , outExt ) ; converter . convert ( sourceDir , destDir ) ; TripleIteratorFactory . defaultInstance ( ) . shutdown ( ) ; }
Command - line utility to convert objects from one format to another .
4,476
private String objectToString ( Object obj , String xsdType ) { if ( obj == null ) { return "null" ; } String javaType = obj . getClass ( ) . getCanonicalName ( ) ; String term ; if ( javaType != null && javaType . equals ( "java.util.Date" ) ) { term = DateUtility . convertDateToXSDString ( ( Date ) obj ) ; } else if ( xsdType . equals ( "fedora-types:ArrayOfString" ) ) { term = array2string ( obj ) ; } else if ( xsdType . equals ( "xsd:boolean" ) ) { term = obj . toString ( ) ; } else if ( xsdType . equals ( "xsd:nonNegativeInteger" ) ) { term = obj . toString ( ) ; } else if ( xsdType . equals ( "fedora-types:RelationshipTuple" ) ) { RelationshipTuple [ ] tuples = ( RelationshipTuple [ ] ) obj ; TupleArrayTripleIterator iter = new TupleArrayTripleIterator ( new ArrayList < RelationshipTuple > ( Arrays . asList ( tuples ) ) ) ; ReadableByteArrayOutputStream os = new ReadableByteArrayOutputStream ( ) ; try { iter . toStream ( os , RDFFormat . NOTATION_3 , false ) ; } catch ( TrippiException e ) { e . printStackTrace ( ) ; } term = os . getString ( Charset . forName ( "UTF-8" ) ) ; } else if ( javaType != null && javaType . equals ( "java.lang.String" ) ) { term = ( String ) obj ; term = term . replaceAll ( "\"" , "'" ) ; } else { term = "[OMITTED]" ; } return term ; }
Get the String value of an object based on its class or XML Schema Datatype .
4,477
private void encodeAttributes ( List attributes , PrintStream out , Indenter indenter ) { Iterator it = attributes . iterator ( ) ; while ( it . hasNext ( ) ) { Attribute attr = ( Attribute ) ( it . next ( ) ) ; attr . encode ( out , indenter ) ; } }
Private helper function to encode the attribute sets
4,478
private void encodeSubject ( Subject subject , PrintStream out , Indenter indenter ) { char [ ] indent = indenter . makeString ( ) . toCharArray ( ) ; out . print ( indent ) ; out . append ( "<Subject SubjectCategory=\"" ) . append ( subject . getCategory ( ) . toString ( ) ) . append ( '"' ) ; List subjectAttrs = subject . getAttributesAsList ( ) ; if ( subjectAttrs . size ( ) == 0 ) { out . println ( "/>" ) ; } else { out . println ( '>' ) ; encodeAttributes ( subjectAttrs , out , indenter ) ; out . print ( indent ) ; out . println ( "</Subject>" ) ; } }
Private helper function to encode the subjects
4,479
public void init ( FilterConfig filterConfig ) { String m = "L init() " ; try { logger . debug ( m + ">" ) ; super . init ( filterConfig ) ; m = FilterSetup . getFilterNameAbbrev ( FILTER_NAME ) + " init() " ; inited = false ; if ( ! initErrors ) { Set < String > temp = new HashSet < String > ( ) ; if ( ATTRIBUTES2RETURN == null ) { ATTRIBUTES2RETURN = EMPTY_STRING_ARRAY ; } else { for ( String element : ATTRIBUTES2RETURN ) { temp . add ( element ) ; } } if ( AUTHENTICATE && PASSWORD != null && ! PASSWORD . isEmpty ( ) ) { temp . add ( PASSWORD ) ; } DIRECTORY_ATTRIBUTES_NEEDED = ( String [ ] ) temp . toArray ( StringArrayPrototype ) ; boolean haveBindMethod = false ; if ( SECURITY_AUTHENTICATION != null && ! SECURITY_AUTHENTICATION . isEmpty ( ) ) { haveBindMethod = true ; } boolean haveSuperUser = false ; if ( SECURITY_PRINCIPAL != null && ! SECURITY_PRINCIPAL . isEmpty ( ) ) { haveSuperUser = true ; } boolean haveSuperUserPassword = false ; if ( SECURITY_CREDENTIALS != null && ! SECURITY_CREDENTIALS . isEmpty ( ) ) { haveSuperUserPassword = true ; } if ( haveBindMethod && haveSuperUserPassword ) { initErrors = ! haveSuperUser ; } } if ( initErrors ) { logger . error ( m + "not initialized; see previous error" ) ; } inited = true ; } finally { logger . debug ( "{}<" , m ) ; } }
public Boolean REQUIRE_RETURNED_ATTRS = Boolean . FALSE ;
4,480
public String upload ( final File file ) throws IOException { if ( Administrator . INSTANCE == null ) { return fc . uploadFile ( file ) ; } else { String msg = "Uploading " + file . length ( ) + " bytes to " + fc . getUploadURL ( ) ; Dimension d = Administrator . PROGRESS . getSize ( ) ; Administrator . PROGRESS . setString ( msg ) ; Administrator . PROGRESS . setValue ( 100 ) ; Administrator . PROGRESS . paintImmediately ( 0 , 0 , ( int ) d . getWidth ( ) - 1 , ( int ) d . getHeight ( ) - 1 ) ; SwingWorker < String > worker = new SwingWorker < String > ( ) { public String construct ( ) { try { return fc . uploadFile ( file ) ; } catch ( IOException e ) { thrownException = e ; return "" ; } } } ; worker . start ( ) ; int ms = 200 ; while ( ! worker . done ) { try { Administrator . PROGRESS . setValue ( ms ) ; Administrator . PROGRESS . paintImmediately ( 0 , 0 , ( int ) d . getWidth ( ) - 1 , ( int ) d . getHeight ( ) - 1 ) ; Thread . sleep ( 100 ) ; ms = ms + 100 ; if ( ms >= 2000 ) { ms = 200 ; } } catch ( InterruptedException ie ) { } } Administrator . PROGRESS . setValue ( 2000 ) ; Administrator . PROGRESS . paintImmediately ( 0 , 0 , ( int ) d . getWidth ( ) - 1 , ( int ) d . getHeight ( ) - 1 ) ; try { Thread . sleep ( 100 ) ; } catch ( InterruptedException ie ) { } if ( worker . thrownException != null ) { throw ( IOException ) worker . thrownException ; } else { return ( String ) worker . getValue ( ) ; } } }
Send a file to the server getting back the identifier .
4,481
public static void main ( String [ ] args ) { try { if ( args . length == 5 || args . length == 6 ) { String protocol = args [ 0 ] ; int port = Integer . parseInt ( args [ 1 ] ) ; String user = args [ 2 ] ; String password = args [ 3 ] ; String fileName = args [ 4 ] ; String context = Constants . FEDORA_DEFAULT_APP_CONTEXT ; if ( args . length == 6 && ! args [ 5 ] . isEmpty ( ) ) { context = args [ 5 ] ; } Uploader uploader = new Uploader ( protocol , port , context , user , password ) ; File f = new File ( fileName ) ; System . out . println ( uploader . upload ( new FileInputStream ( f ) ) ) ; System . out . println ( uploader . upload ( f ) ) ; uploader = new Uploader ( protocol , port , context , user + "test" , password ) ; System . out . println ( uploader . upload ( f ) ) ; } else { System . err . println ( "Usage: Uploader host port user password file [context]" ) ; } } catch ( Exception e ) { System . err . println ( "ERROR: " + e . getMessage ( ) ) ; } }
Test this class by uploading the given file three times . First with the provided credentials as an InputStream . Second with the provided credentials as a File . Third with bogus credentials as a File .
4,482
private File getFedoraHomeDir ( ) throws ServletException { String fedoraHome = Constants . FEDORA_HOME ; if ( fedoraHome == null ) { failStartup ( "FEDORA_HOME was not configured properly. It must be " + "set via the fedora.home servlet init-param (preferred), " + "the fedora.home system property, or the FEDORA_HOME " + "environment variable." , null ) ; } File fedoraHomeDir = new File ( fedoraHome ) ; if ( ! fedoraHomeDir . isDirectory ( ) ) { failStartup ( "The FEDORA_HOME directory, " + fedoraHomeDir . getPath ( ) + " does not exist" , null ) ; } File writeTest = new File ( fedoraHomeDir , "writeTest.tmp" ) ; String writeErrorMessage = "The FEDORA_HOME directory, " + fedoraHomeDir . getPath ( ) + " is not writable by " + "the current user, " + System . getProperty ( "user.name" ) ; try { writeTest . createNewFile ( ) ; if ( ! writeTest . exists ( ) ) { throw new IOException ( "" ) ; } writeTest . delete ( ) ; } catch ( IOException e ) { failStartup ( writeErrorMessage , null ) ; } return fedoraHomeDir ; }
Validates and returns the value of FEDORA_HOME .
4,483
public Validation validate ( Context context , String pid , Date asOfDateTime ) throws ServerException { try { logger . debug ( "Entered validate" ) ; m_authz . enforceValidate ( context , pid , asOfDateTime ) ; return ecmValidator . validate ( context , pid , asOfDateTime ) ; } finally { if ( logger . isInfoEnabled ( ) ) { StringBuilder logMsg = new StringBuilder ( "Completed validate(" ) ; logMsg . append ( "pid: " ) . append ( pid ) ; logMsg . append ( ", asOfDateTime: " ) . append ( asOfDateTime ) ; logMsg . append ( ")" ) ; logger . info ( logMsg . toString ( ) ) ; } logger . debug ( "Exiting validate" ) ; } }
Validate the object against the datacontracts from the objects content model . This method just delegates the validation to EcmValidator
4,484
private void addAuditRecord ( Context context , DOWriter w , String action , String componentID , String justification , Date nowUTC ) throws ServerException { AuditRecord audit = new AuditRecord ( ) ; audit . id = w . newAuditRecordID ( ) ; audit . processType = "Fedora API-M" ; audit . action = action ; audit . componentID = componentID ; audit . responsibility = context . getSubjectValue ( Constants . SUBJECT . LOGIN_ID . uri ) ; audit . date = nowUTC ; audit . justification = justification ; w . getAuditRecords ( ) . add ( audit ) ; }
Creates a new audit record and adds it to the digital object audit trail .
4,485
private static void appendAltIDs ( StringBuilder logMsg , String [ ] altIDs ) { logMsg . append ( ", altIDs: " ) ; if ( altIDs == null ) { logMsg . append ( "null" ) ; } else { for ( String altID : altIDs ) { logMsg . append ( "'" ) . append ( altID ) . append ( "'" ) ; } } }
Appends alt IDs to the log message .
4,486
public void setValidators ( Map < String , ? extends DOObjectValidator > validators ) { logger . info ( "Adding {} object validators" , validators . size ( ) ) ; m_validators . putAll ( validators ) ; if ( m_validators . size ( ) > 0 ) { m_enabled = true ; } }
spring config of the validators
4,487
public void install ( ) throws InstallationFailedException { installDir . mkdirs ( ) ; try { OutputStream out = new FileOutputStream ( new File ( installDir , "install.properties" ) ) ; _opts . dump ( out ) ; out . close ( ) ; } catch ( Exception e ) { throw new InstallationFailedException ( e . getMessage ( ) , e ) ; } new FedoraHome ( _dist , _opts ) . install ( ) ; if ( ! _opts . getValue ( InstallOptions . INSTALL_TYPE ) . equals ( InstallOptions . INSTALL_CLIENT ) ) { Container container = ContainerFactory . getContainer ( _dist , _opts ) ; container . install ( ) ; container . deploy ( buildWAR ( ) ) ; if ( _opts . getBooleanValue ( InstallOptions . DEPLOY_LOCAL_SERVICES , true ) ) { deployLocalService ( container , Distribution . FOP_WAR ) ; deployLocalService ( container , Distribution . IMAGEMANIP_WAR ) ; deployLocalService ( container , Distribution . SAXON_WAR ) ; deployLocalService ( container , Distribution . DEMO_WAR ) ; } Database database = new Database ( _dist , _opts ) ; database . install ( ) ; } System . out . println ( "Installation complete." ) ; if ( ! _opts . getValue ( InstallOptions . INSTALL_TYPE ) . equals ( InstallOptions . INSTALL_CLIENT ) && _opts . getValue ( InstallOptions . SERVLET_ENGINE ) . equals ( InstallOptions . OTHER ) ) { System . out . println ( "\n" + "----------------------------------------------------------------------\n" + "The Fedora Installer cannot automatically deploy the Web ARchives to \n" + "the selected servlet container. You must deploy the WAR files \n" + "manually. You can find fedora.war plus several sample back-end \n" + "services and a demonstration object package in: \n" + "\t" + fedoraHome . getAbsolutePath ( ) + File . separator + "install" ) ; } System . out . println ( "\n" + "----------------------------------------------------------------------\n" + "Before starting Fedora, please ensure that any required environment\n" + "variables are correctly defined\n" + "\t(e.g. FEDORA_HOME, JAVA_HOME, JAVA_OPTS, CATALINA_HOME).\n" + "For more information, please consult the Installation & Configuration\n" + "Guide in the online documentation.\n" + "----------------------------------------------------------------------\n" ) ; }
Install the distribution based on the options .
4,488
public static void main ( String [ ] args ) { LogConfig . initMinimal ( ) ; try { Distribution dist = new ClassLoaderDistribution ( ) ; InstallOptions opts = null ; if ( args . length == 0 ) { opts = new InstallOptions ( dist ) ; } else { Map < String , String > props = new HashMap < String , String > ( ) ; for ( String file : args ) { props . putAll ( FileUtils . loadMap ( new File ( file ) ) ) ; } opts = new InstallOptions ( dist , props ) ; } System . setProperty ( "fedora.home" , opts . getValue ( InstallOptions . FEDORA_HOME ) ) ; new Installer ( dist , opts ) . install ( ) ; } catch ( Exception e ) { printException ( e ) ; System . exit ( 1 ) ; } }
Command - line entry point .
4,489
private static void printException ( Exception e ) { if ( e instanceof InstallationCancelledException ) { System . out . println ( "Installation cancelled." ) ; return ; } boolean recognized = false ; String msg = "ERROR: " ; if ( e instanceof InstallationFailedException ) { msg += "Installation failed: " + e . getMessage ( ) ; recognized = true ; } else if ( e instanceof OptionValidationException ) { OptionValidationException ove = ( OptionValidationException ) e ; msg += "Bad value for '" + ove . getOptionId ( ) + "': " + e . getMessage ( ) ; recognized = true ; } if ( recognized ) { System . err . println ( msg ) ; if ( e . getCause ( ) != null ) { System . err . println ( "Caused by: " ) ; e . getCause ( ) . printStackTrace ( System . err ) ; } } else { System . err . println ( msg + "Unexpected error; installation aborted." ) ; e . printStackTrace ( ) ; } }
Print a message appropriate for the given exception in as human - readable way as possible .
4,490
public void run ( ) { try { waitUntilServerIsInitialized ( ) ; recoveryLog . log ( "Start recovery." ) ; while ( true ) { if ( shutdown ) { break ; } ConsumerJournalEntry cje = reader . readJournalEntry ( ) ; if ( cje == null ) { break ; } cje . invokeMethod ( delegate , recoveryLog ) ; cje . close ( ) ; } reader . shutdown ( ) ; recoveryLog . log ( "Recovery complete." ) ; } catch ( Throwable e ) { logger . error ( "Error during Journal recovery" , e ) ; String stackTrace = JournalHelper . captureStackTrace ( e ) ; recoveryLog . log ( "PROBLEM: " + stackTrace ) ; recoveryLog . log ( "Recovery terminated prematurely." ) ; } finally { recoveryLog . shutdown ( ) ; } }
Wait until the server completes its initialization then process journal entries until the reader says there are no more or until a shutdown is requested .
4,491
private void waitUntilServerIsInitialized ( ) { int i = 0 ; for ( ; i < 60 ; i ++ ) { if ( server . hasInitialized ( ) || shutdown ) { return ; } try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { logger . warn ( "Thread was interrupted" ) ; } } logger . error ( "Can't recover from the Journal - " + "the server hasn't initialized after " + i + " seconds." ) ; shutdown = true ; }
Wait for the server to initialize . If we wait too long give up and shut down the thread .
4,492
private static Schema getSchema ( InputStream schemaStream ) throws SAXException { Schema result ; synchronized ( SCHEMA_FACTORY ) { result = SCHEMA_FACTORY . newSchema ( new StreamSource ( schemaStream ) ) ; } return result ; }
Schema Factory is not thread safe
4,493
public AbstractPolicy parse ( InputStream policyStream , boolean schemaValidate ) throws ValidationException { Document doc = null ; DocumentBuilder domParser = null ; try { domParser = XmlTransformUtility . borrowDocumentBuilder ( ) ; domParser . setErrorHandler ( THROW_ALL ) ; doc = domParser . parse ( policyStream ) ; } catch ( Exception e ) { throw new ValidationException ( "Policy invalid; malformed XML" , e ) ; } finally { if ( domParser != null ) { XmlTransformUtility . returnDocumentBuilder ( domParser ) ; } } if ( schemaValidate ) { Validator validator = null ; try { validator = m_validators . borrowObject ( ) ; validator . validate ( new DOMSource ( doc ) ) ; } catch ( Exception e ) { throw new ValidationException ( "Policy invalid; schema" + " validation failed" , e ) ; } finally { if ( validator != null ) try { m_validators . returnObject ( validator ) ; } catch ( Exception e ) { logger . warn ( e . getMessage ( ) , e ) ; } } } Element root = doc . getDocumentElement ( ) ; String rootName = root . getTagName ( ) ; try { if ( rootName . equals ( "Policy" ) ) { return Policy . getInstance ( root ) ; } else if ( rootName . equals ( "PolicySet" ) ) { return PolicySet . getInstance ( root ) ; } else { throw new ValidationException ( "Policy invalid; root element is " + rootName + ", but should be " + "Policy or PolicySet" ) ; } } catch ( ParsingException e ) { throw new ValidationException ( "Policy invalid; failed parsing by " + "Sun XACML implementation" , e ) ; } }
Parses the given policy and optionally schema validates it .
4,494
public void exportAndBind ( ) throws RemoteException , AlreadyBoundException , InterruptedException { Registry registry = LocateRegistry . createRegistry ( arguments . getRegistryPortNumber ( ) ) ; registry . rebind ( RMI_BINDING_NAME , this ) ; Thread . sleep ( 2000 ) ; logger . info ( "RmiJournalReceiver is ready - journal directory is '" + arguments . getDirectoryPath ( ) . getAbsolutePath ( ) + "'" ) ; }
Create an RMI registry and bind this object to the expected name .
4,495
private void updateTriples ( Set < Triple > set , boolean delete ) throws ResourceIndexException { try { if ( delete ) { _writer . delete ( getTripleIterator ( set ) , _syncUpdates ) ; } else { _writer . add ( getTripleIterator ( set ) , _syncUpdates ) ; } } catch ( Exception e ) { throw new ResourceIndexException ( "Error updating triples" , e ) ; } }
Applies the given adds or deletes to the triplestore . If _syncUpdates is true changes will be flushed before returning .
4,496
private void updateTripleDiffs ( Set < Triple > existing , Set < Triple > desired ) throws ResourceIndexException { HashSet < Triple > obsoleteTriples = new HashSet < Triple > ( existing ) ; obsoleteTriples . removeAll ( desired ) ; updateTriples ( obsoleteTriples , true ) ; HashSet < Triple > newTriples = new HashSet < Triple > ( desired ) ; newTriples . removeAll ( existing ) ; updateTriples ( newTriples , false ) ; }
Computes the difference between the given sets and applies the appropriate deletes and adds to the triplestore . If _syncUpdates is true changes will be flushed before returning .
4,497
private TripleIterator getTripleIterator ( final Set < Triple > set ) { return new TripleIterator ( ) { private final Iterator < Triple > _iter = set . iterator ( ) ; public boolean hasNext ( ) { return _iter . hasNext ( ) ; } public Triple next ( ) { return getLocalizedTriple ( _iter . next ( ) ) ; } public void close ( ) { } } ; }
Gets a Trippi TripleIterator for the given set .
4,498
private Triple getLocalizedTriple ( Triple triple ) { try { return _connector . getElementFactory ( ) . createTriple ( getLocalizedResource ( triple . getSubject ( ) ) , getLocalizedResource ( triple . getPredicate ( ) ) , getLocalizedObject ( triple . getObject ( ) ) ) ; } catch ( GraphElementFactoryException e ) { throw new RuntimeException ( "Error localizing triple" , e ) ; } }
Gets a Triple appropriate for writing to the store .
4,499
private URIReference getLocalizedResource ( Node n ) throws GraphElementFactoryException { if ( n instanceof URIReference ) { URIReference u = ( URIReference ) n ; return _connector . getElementFactory ( ) . createResource ( u . getURI ( ) ) ; } else { throw new RuntimeException ( "Error localizing triple; " + n . getClass ( ) . getName ( ) + " is not a URIReference" ) ; } }
Gets a localized URIReference based on the given Node .