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 ) ; return true ; } catch ( IOException io ) { return false ; } } | 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 < String > response = Unirest . post ( url ) . header ( "Content-Type" , "application/json" ) . body ( body ) . asString ( ) ; return true ; } | 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 . openNextFile ( ) ; if ( nextFile != null ) { return nextFile ; } } try { wait ( pollingIntervalMillis ) ; } catch ( InterruptedException e ) { } } return null ; } | 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 '" + lockAcceptedFile . getPath ( ) + "'" ) ; } locked = true ; } else { if ( lockAcceptedFile . exists ( ) ) { lockAcceptedFile . delete ( ) ; } locked = false ; } if ( locked && ! wasLocked ) { recoveryLog . log ( "Lock request detected: " + lockRequestedFile . getPath ( ) + ", Lock accepted: " + lockAcceptedFile . getPath ( ) ) ; } else if ( wasLocked && ! locked ) { recoveryLog . log ( "Lock request removed: " + lockRequestedFile . getPath ( ) ) ; } wasLocked = locked ; return locked ; } | 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 ++ ) ) ; } else { builder . append ( c ) ; } } builder . append ( '/' ) ; } | 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-generated datastream to preserve METS DMDID/ADMID relationships." ; ds . DSCreateDT = new Date ( ) ; ds . DSMIME = "application/rdf+xml" ; ds . DSControlGrp = "X" ; ds . DSState = "A" ; ds . DSLocation = m_obj . getPid ( ) + "+" + ds . DatastreamID + "+" + ds . DSVersionID ; ds . DSLocationType = Datastream . DS_LOCATION_TYPE_INTERNAL ; ds . DSInfoType = "DATA" ; ds . DSMDClass = DatastreamXMLMetadata . TECHNICAL ; try { ds . xmlContent = buf . toString ( ) . getBytes ( m_characterEncoding ) ; ds . DSSize = ds . xmlContent . length ; } catch ( UnsupportedEncodingException uee ) { logger . error ( "Encoding error when creating RELS-INT datastream" , uee ) ; } m_obj . addDatastreamVersion ( ds , true ) ; } | 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 ( ) . selectSingleNode ( "/Server/Service[@name='Catalina']" ) ; httpsConnector = service . addElement ( "Connector" ) ; httpsConnector . addAttribute ( "maxThreads" , "150" ) ; httpsConnector . addAttribute ( "minSpareThreads" , "25" ) ; httpsConnector . addAttribute ( "maxSpareThreads" , "75" ) ; httpsConnector . addAttribute ( "disableUploadTimeout" , "true" ) ; httpsConnector . addAttribute ( "acceptCount" , "100" ) ; httpsConnector . addAttribute ( "debug" , "0" ) ; httpsConnector . addAttribute ( "scheme" , "https" ) ; httpsConnector . addAttribute ( "secure" , "true" ) ; httpsConnector . addAttribute ( "clientAuth" , "false" ) ; httpsConnector . addAttribute ( "sslProtocol" , "TLS" ) ; } httpsConnector . addAttribute ( "port" , options . getValue ( InstallOptions . TOMCAT_SSL_PORT ) ) ; httpsConnector . addAttribute ( "enableLookups" , "true" ) ; String keystore = options . getValue ( InstallOptions . KEYSTORE_FILE ) ; if ( keystore . equals ( InstallOptions . INCLUDED ) ) { keystore = KEYSTORE_LOCATION ; } addAttribute ( httpsConnector , "keystoreFile" , keystore , InstallOptions . DEFAULT ) ; addAttribute ( httpsConnector , "keystorePass" , options . getValue ( InstallOptions . KEYSTORE_PASSWORD ) , KEYSTORE_PASSWORD_DEFAULT ) ; addAttribute ( httpsConnector , "keystoreType" , options . getValue ( InstallOptions . KEYSTORE_TYPE ) , KEYSTORE_TYPE_DEFAULT ) ; Element httpConnector = ( Element ) getDocument ( ) . selectSingleNode ( HTTP_CONNECTOR_XPATH ) ; if ( httpConnector != null ) { httpConnector . addAttribute ( "redirectPort" , options . getValue ( InstallOptions . TOMCAT_SSL_PORT ) ) ; } else { throw new InstallationFailedException ( "Unable to set server.xml SSL Port. XPath for Connector element failed." ) ; } } else if ( httpsConnector != null ) { httpsConnector . getParent ( ) . remove ( httpsConnector ) ; } } | 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 ( attribute ) ; } } else { element . addAttribute ( attributeName , attributeValue ) ; } } | 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 ( ) ) ; } return sdefs . toArray ( EMPTY_STRING_ARRAY ) ; } | 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 > ( ) ; for ( String element : sDefPIDs ) { MethodDef [ ] methodDefs = getMethods ( context , PID , element , asOfDateTime ) ; for ( MethodDef element2 : methodDefs ) { ObjectMethodsDef method = new ObjectMethodsDef ( ) ; method . PID = PID ; method . asOfDate = versDateTime ; method . sDefPID = element ; method . methodName = element2 . methodName ; method . methodParmDefs = element2 . methodParms ; objectMethods . add ( method ) ; } } return objectMethods . toArray ( OBJ_METHOD_DEF_ARRAY_TYPE ) ; } | 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 > 0 ) { if ( h > 0 ) { out . append ( ", " ) ; } out . append ( m + " minute" ) ; if ( m > 1 ) { out . append ( 's' ) ; } } if ( s > 0 || h == 0 && m == 0 ) { if ( h > 0 || m > 0 ) { out . append ( ", " ) ; } out . append ( s + " second" ) ; if ( s != 1 ) { out . append ( 's' ) ; } } return out . toString ( ) ; } | 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 File ( new File ( new File ( fedoraHome ) , "client" ) , "logs" ) ; if ( ! logDir . exists ( ) ) { logDir . mkdir ( ) ; } outFile = new File ( logDir , fileName ) ; } s_logPath = outFile . getPath ( ) ; s_log = new PrintStream ( new FileOutputStream ( outFile ) , true , "UTF-8" ) ; s_log . println ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ) ; s_log . println ( "<" + s_rootName + ">" ) ; } | 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 ) { buffer . append ( ( char ) ch ) ; } in . close ( ) ; return buffer . toString ( ) ; } | 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 ( ) . substring ( 0 , policyFile . getName ( ) . lastIndexOf ( ".xml" ) ) ) . toString ( ) ; } catch ( MalformedPIDException e ) { throw new PolicyIndexException ( "Invalid policy file name. Filename cannot be converted to a valid PID - " + policyFile . getName ( ) ) ; } } | 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 != null ) { logger . debug ( "Using POLICY for {}" , pid ) ; return policyParser . parse ( ds . getContentStream ( ) , validate ) ; } else { return null ; } } catch ( ObjectNotInLowlevelStorageException e ) { return null ; } } | 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 ( ) . createXMLEventWriter ( new BufferedWriter ( writer , bufferSize ) ) ) ; parent . writeDocumentHeader ( xmlWriter , repositoryHash , currentDate ) ; super . setState ( State . FILE_OPEN ) ; } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } catch ( FactoryConfigurationError e ) { throw new JournalException ( e ) ; } } | 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 , true ) ; } | 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 . newInstance ( type , data , false ) ; } | 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 ( getBetwixtMapping ( ) ) ; wx = ( WebXML ) reader . parse ( new File ( webxml ) . toURI ( ) . toString ( ) ) ; } catch ( IntrospectionException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( SAXException e ) { e . printStackTrace ( ) ; } return wx ; } | 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 old system object: {}" , pid ) ; Context context = ReadOnlyContext . getContext ( null , null , null , false ) ; DOWriter w = doManager . getWriter ( USE_DEFINITIVE_STORE , context , pid . toString ( ) ) ; w . remove ( ) ; try { w . commit ( "Purged by Fedora at startup (to be re-ingested)" ) ; exists = false ; } finally { doManager . releaseWriter ( w ) ; } } if ( ! exists ) { logger . info ( "Ingesting new system object: {}" , pid ) ; InputStream xml = getStream ( "org/fcrepo/server/resources/" + pid . toFilename ( ) + ".xml" ) ; Context context = ReadOnlyContext . getContext ( null , null , null , false ) ; DOWriter w = doManager . getIngestWriter ( USE_DEFINITIVE_STORE , context , xml , Constants . FOXML1_1 . uri , "UTF-8" , null ) ; try { w . commit ( "Pre-ingested by Fedora at startup" ) ; } finally { doManager . releaseWriter ( w ) ; } } } | 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 ( Exception e ) { logger . error ( "VALIDATE: ERROR - failed XML Schema validation." , e ) ; throw new ObjectValidityException ( "[DOValidatorImpl]: validateXMLSchema. " + e . getMessage ( ) ) ; } logger . debug ( "VALIDATE: SUCCESS - passed XML Schema validation." ) ; } | 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 ( objectAsStream ) ; } catch ( ObjectValidityException e ) { logger . error ( "VALIDATE: ERROR - failed Schematron rules validation." , e ) ; throw e ; } catch ( Exception e ) { logger . error ( "VALIDATE: ERROR - failed Schematron rules validation." , e ) ; throw new ObjectValidityException ( "[DOValidatorImpl]: " + "failed Schematron rules validation. " + e . getMessage ( ) ) ; } logger . debug ( "VALIDATE: SUCCESS - passed Schematron rules validation." ) ; } | 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 ) { logger . warn ( "Resource must contain only one resource-id Attribute" ) ; } else { this . resourceId = resourceId . get ( 0 ) . getValue ( ) ; } } if ( this . resourceId == null ) this . resourceId = new StringAttribute ( "" ) ; List < Attribute > resourceScope = resourceMap . get ( RESOURCE_SCOPE ) ; if ( resourceScope != null && ! resourceScope . isEmpty ( ) ) { if ( resourceScope . size ( ) > 1 ) { System . err . println ( "Resource may contain only one " + "resource-scope Attribute" ) ; throw new ParsingException ( "too many resource-scope attrs" ) ; } AttributeValue attrValue = resourceScope . get ( 0 ) . getValue ( ) ; if ( ! attrValue . getType ( ) . toString ( ) . equals ( StringAttribute . identifier ) ) throw new ParsingException ( "scope attr must be a string" ) ; String value = ( ( StringAttribute ) attrValue ) . getValue ( ) ; if ( value . equals ( "Immediate" ) ) { scope = SCOPE_IMMEDIATE ; } else if ( value . equals ( "Children" ) ) { scope = SCOPE_CHILDREN ; } else if ( value . equals ( "Descendants" ) ) { scope = SCOPE_DESCENDANTS ; } else { System . err . println ( "Unknown scope type: " + value ) ; throw new ParsingException ( "invalid scope type: " + value ) ; } } else { scope = SCOPE_IMMEDIATE ; } } | 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 > list = output . get ( id ) ; list . add ( attr ) ; } else { List list = new ArrayList < Attribute > ( ) ; list . add ( attr ) ; output . put ( id , list ) ; } } } | 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 , issuer , category , designatorType ) ; if ( contextValue != null ) { attrList = Collections . singletonList ( contextValue ) ; map . put ( id . toString ( ) , attrList ) ; } else { attrList = Collections . emptyList ( ) ; } } final List < AttributeValue > attributes ; Attribute attr = null ; switch ( attrList . size ( ) ) { case 0 : attributes = Collections . emptyList ( ) ; break ; case 1 : attr = attrList . get ( 0 ) ; if ( ( attr . getType ( ) . equals ( type ) ) && ( ( issuer == null ) || ( ( attr . getIssuer ( ) != null ) && ( attr . getIssuer ( ) . equals ( issuer . toString ( ) ) ) ) ) ) { attributes = new ArrayList < AttributeValue > ( attrList . get ( 0 ) . getValues ( ) ) ; } else { attributes = Collections . emptyList ( ) ; } break ; default : Iterator it = attrList . iterator ( ) ; attributes = new ArrayList < AttributeValue > ( ) ; while ( it . hasNext ( ) ) { attr = ( Attribute ) ( it . next ( ) ) ; if ( ( attr . getType ( ) . equals ( type ) ) && ( ( issuer == null ) || ( ( attr . getIssuer ( ) != null ) && ( attr . getIssuer ( ) . equals ( issuer . toString ( ) ) ) ) ) ) { attributes . addAll ( attr . getValues ( ) ) ; } } } if ( attributes . size ( ) == 0 ) { logger . debug ( "Attribute not in request: {} ... querying AttributeFinder" , id ) ; return callHelper ( type , id , issuer , category , designatorType ) ; } else { return new EvaluationResult ( new BagAttribute ( type , attributes ) ) ; } } | 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 . toString ( ) ) ; break ; case AttributeDesignator . RESOURCE_TARGET : values = context . getResourceValues ( id ) ; break ; case AttributeDesignator . ACTION_TARGET : values = context . getActionValues ( id ) ; break ; case AttributeDesignator . ENVIRONMENT_TARGET : values = context . getEnvironmentValues ( id ) ; break ; } if ( values == null || values . length == 0 ) return null ; String iString = ( issuer == null ) ? null : issuer . toString ( ) ; String tString = type . toString ( ) ; if ( values . length == 1 ) { AttributeValue val = stringToValue ( values [ 0 ] , tString ) ; return ( val == null ) ? null : new SingletonAttribute ( id , iString , getCurrentDateTime ( ) , val ) ; } else { ArrayList < AttributeValue > valCollection = new ArrayList < AttributeValue > ( values . length ) ; for ( int i = 0 ; i < values . length ; i ++ ) { AttributeValue val = stringToValue ( values [ i ] , tString ) ; if ( val != null ) valCollection . add ( val ) ; } return new BasicAttribute ( id , type , iString , getCurrentDateTime ( ) , valCollection ) ; } } | 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 . get ( pid ) ; } if ( reader == null ) { reader = new SimpleDOReader ( context , this , m_translator , m_defaultExportFormat , m_defaultStorageFormat , m_storageCharacterEncoding , m_permanentStore . retrieveObject ( pid ) ) ; source = "filesystem" ; if ( m_readerCache != null ) { m_readerCache . put ( reader , getReaderStartTime ) ; } } else { source = "memory" ; } return reader ; } } finally { if ( logger . isDebugEnabled ( ) ) { long dur = System . currentTimeMillis ( ) - getReaderStartTime ; logger . debug ( "Got DOReader (source={}) for {} in {}ms." , source , pid , dur ) ; } } } | 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 . retrieveObject ( pid ) ) ; } } | 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 . retrieveObject ( pid ) ) ; } } | 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 ( ) ; getWriteLock ( pid ) ; boolean clean = false ; try { m_translator . deserialize ( m_permanentStore . retrieveObject ( pid ) , obj , m_defaultStorageFormat , m_storageCharacterEncoding , DOTranslationUtility . DESERIALIZE_INSTANCE ) ; DOWriter w = new SimpleDOWriter ( context , this , m_translator , m_defaultStorageFormat , m_storageCharacterEncoding , obj ) ; clean = true ; return w ; } finally { if ( ! clean ) { releaseWriteLock ( pid ) ; } } } } | 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 ) { dcxml = new XMLDatastreamProcessor ( "DC" ) ; dc = dcxml . getDatastream ( ) ; dc . DatastreamID = "DC" ; dc . DSVersionID = "DC1.0" ; dc . DSCreateDT = nowUTC ; dc . DSLabel = "Dublin Core Record for this object" ; dc . DSMIME = "text/xml" ; dc . DSFormatURI = OAI_DC2_0 . uri ; dc . DSSize = 0 ; dc . DSState = "A" ; dc . DSVersionable = true ; dcf = new DCFields ( ) ; if ( obj . getLabel ( ) != null && ! obj . getLabel ( ) . isEmpty ( ) ) { dcf . titles ( ) . add ( new DCField ( obj . getLabel ( ) ) ) ; } w . addDatastream ( dc , dc . DSVersionable ) ; } else { dcxml = new XMLDatastreamProcessor ( dc ) ; dcf = new DCFields ( dc . getContentStream ( ctx ) ) ; } ByteArrayOutputStream bytes = new ByteArrayOutputStream ( 512 ) ; PrintWriter out = new PrintWriter ( new OutputStreamWriter ( bytes , Charset . forName ( "UTF-8" ) ) ) ; dcf . getAsXML ( obj . getPid ( ) , out ) ; out . close ( ) ; dcxml . setXMLContent ( bytes . toByteArray ( ) ) ; } | 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 new StorageDeviceException ( e . getMessage ( ) , e ) ; } } if ( exists && ! registered ) { logger . warn ( "{} was not in the registry, but appears to be in store." + " Registry db may be in inconsistent state." , pid ) ; } return registered || exists ; } | 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 ( query ) ; st . setString ( 1 , pid ) ; st . executeUpdate ( ) ; if ( obj . hasContentModel ( Models . SERVICE_DEPLOYMENT_3_0 ) ) { updateDeploymentMap ( obj , conn , true ) ; } } catch ( SQLException sqle ) { throw new StorageDeviceException ( "Unexpected error from SQL database while unregistering object: " + sqle . getMessage ( ) , sqle ) ; } finally { try { if ( st != null ) { st . close ( ) ; } if ( conn != null ) { m_connectionPool . free ( conn ) ; } } catch ( Exception sqle ) { throw new StorageDeviceException ( "Unexpected error from SQL database while unregistering object: " + sqle . getMessage ( ) , sqle ) ; } finally { st = null ; } } } | 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 ( query ) ; logger . debug ( "Executing db query: {}" , query ) ; results = s . executeQuery ( ) ; if ( results . next ( ) ) { ArrayList < String > pidList = new ArrayList < String > ( ) ; do { pidList . add ( results . getString ( "doPID" ) ) ; } while ( results . next ( ) ) ; return pidList . toArray ( EMPTY_STRING_ARRAY ) ; } else { return EMPTY_STRING_ARRAY ; } } catch ( SQLException sqle ) { throw new StorageDeviceException ( "Unexpected error from SQL database: " + sqle . getMessage ( ) , sqle ) ; } finally { try { if ( results != null ) { results . close ( ) ; } if ( s != null ) { s . close ( ) ; } if ( conn != null ) { m_connectionPool . free ( conn ) ; } } catch ( SQLException sqle ) { throw new StorageDeviceException ( "Unexpected error from SQL database: " + sqle . getMessage ( ) , sqle ) ; } finally { results = null ; s = null ; } } } | 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 = conn . prepareStatement ( query ) ; ResultSet results = st . executeQuery ( ) ; results . next ( ) ; return results . getInt ( 1 ) ; } finally { if ( st != null ) { st . close ( ) ; } } } | 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 = borrowTransformerFactory ( ) ; Templates template = factory . newTemplates ( new StreamSource ( src ) ) ; entry = new TimestampedCacheEntry < Templates > ( src . lastModified ( ) , template ) ; } catch ( Exception e ) { throw new TransformerException ( e . getMessage ( ) , e ) ; } finally { if ( factory != null ) returnTransformerFactory ( factory ) ; } TEMPLATES_CACHE . put ( key , entry ) ; } return entry . value ( ) ; } | 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 + "/" + DateUtility . convertDateToString ( obj . getCreateDate ( ) ) ; Entry dsEntry = feed . addEntry ( ) ; dsEntry . setId ( dsId ) ; dsEntry . setTitle ( "AUDIT" ) ; dsEntry . setUpdated ( obj . getCreateDate ( ) ) ; dsEntry . addCategory ( MODEL . STATE . uri , "A" , null ) ; dsEntry . addCategory ( MODEL . CONTROL_GROUP . uri , "X" , null ) ; dsEntry . addCategory ( MODEL . VERSIONABLE . uri , "false" , null ) ; dsEntry . addLink ( dsvId , Link . REL_ALTERNATE ) ; Entry dsvEntry = feed . addEntry ( ) ; dsvEntry . setId ( dsvId ) ; dsvEntry . setTitle ( "AUDIT.0" ) ; dsvEntry . setUpdated ( obj . getCreateDate ( ) ) ; ThreadHelper . addInReplyTo ( dsvEntry , PID . toURI ( obj . getPid ( ) ) + "/AUDIT" ) ; dsvEntry . addCategory ( MODEL . FORMAT_URI . uri , AUDIT1_0 . uri , null ) ; dsvEntry . addCategory ( MODEL . LABEL . uri , "Audit Trail for this object" , null ) ; if ( m_format . equals ( ATOM_ZIP1_1 ) ) { String name = "AUDIT.0.xml" ; try { zout . putNextEntry ( new ZipEntry ( name ) ) ; ReadableCharArrayWriter buf = new ReadableCharArrayWriter ( 512 ) ; PrintWriter pw = new PrintWriter ( buf ) ; DOTranslationUtility . appendAuditTrail ( obj , pw ) ; pw . close ( ) ; IOUtils . copy ( buf . toReader ( ) , zout , encoding ) ; zout . closeEntry ( ) ; } catch ( IOException e ) { throw new StreamIOException ( e . getMessage ( ) , e ) ; } IRI iri = new IRI ( name ) ; dsvEntry . setSummary ( "AUDIT.0" ) ; dsvEntry . setContent ( iri , "text/xml" ) ; } else { dsvEntry . setContent ( DOTranslationUtility . getAuditTrail ( obj ) , "text/xml" ) ; } } | 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 = params . getTranslator ( ) . makeAbsoluteURLs ( url ) ; if ( ServerUtility . isURLFedoraServer ( url ) && ! params . isBypassBackend ( ) ) { BackendSecuritySpec m_beSS ; BackendSecurity m_beSecurity = ( BackendSecurity ) getServer ( ) . getModule ( "org.fcrepo.server.security.BackendSecurity" ) ; try { m_beSS = m_beSecurity . getBackendSecuritySpec ( ) ; } catch ( Exception e ) { throw new ModuleInitializationException ( "Can't intitialize BackendSecurity module (in default access) from Server.getModule" , getRole ( ) ) ; } Hashtable < String , String > beHash = m_beSS . getSecuritySpec ( BackendPolicies . FEDORA_INTERNAL_CALL ) ; username = beHash . get ( "callUsername" ) ; password = beHash . get ( "callPassword" ) ; backendSSL = Boolean . parseBoolean ( beHash . get ( "callSSL" ) ) ; if ( backendSSL ) { if ( params . getProtocol ( ) . equals ( "http" ) ) { url = url . replaceFirst ( "http:" , "https:" ) ; } url = url . replaceFirst ( ":" + fedoraServerPort + "/" , ":" + fedoraServerRedirectPort + "/" ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "************************* backendUsername: " + username + " backendPassword: " + password + " backendSSL: " + backendSSL ) ; logger . debug ( "************************* doAuthnGetURL: " + url ) ; } } return getFromWeb ( url , username , password , params . getMimeType ( ) , isHEADRequest ( params ) , params . getContext ( ) ) ; } | 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 ( "Failed to initialize " + "the ValidatorProcess: " , e ) ; } } | 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 ( parms . getPidfile ( ) ) ; } } | 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 ) ; JTextArea methodParametersTextArea = new JTextArea ( " with parm(s)" ) ; methodParametersTextArea . setLineWrap ( false ) ; methodParametersTextArea . setEditable ( false ) ; methodParametersTextArea . setBackground ( Administrator . BACKGROUND_COLOR ) ; JComponent [ ] left = new JComponent [ ] { supportsMethodsTextArea , methodParametersTextArea } ; List < MethodDefinition > methodDefs = Util . getMethodDefinitions ( sDefPID ) ; String [ ] methodSelections = new String [ methodDefs . size ( ) ] ; for ( int i = 0 ; i < methodDefs . size ( ) ; i ++ ) { MethodDefinition def = ( MethodDefinition ) methodDefs . get ( i ) ; StringBuffer buf = new StringBuffer ( ) ; buf . append ( def . getName ( ) ) ; if ( def . getLabel ( ) != null ) { buf . append ( " - " ) ; buf . append ( def . getLabel ( ) ) ; } methodSelections [ i ] = buf . toString ( ) ; } final JComboBox < String > methodComboBox = new JComboBox < String > ( methodSelections ) ; Administrator . constrainHeight ( methodComboBox ) ; final ParameterPanel parameterPanel = new ParameterPanel ( methodDefs ) ; methodComboBox . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent evt ) { String [ ] parts = ( ( String ) methodComboBox . getSelectedItem ( ) ) . split ( " - " ) ; parameterPanel . show ( parts [ 0 ] ) ; parameterPanel . revalidate ( ) ; } } ) ; JComponent [ ] right = new JComponent [ ] { methodComboBox , parameterPanel } ; GridBagLayout gb = new GridBagLayout ( ) ; JPanel panel = new JPanel ( gb ) ; panel . setBorder ( BorderFactory . createEmptyBorder ( 4 , 0 , 0 , 0 ) ) ; Util . addRows ( left , right , gb , panel , true , false ) ; return panel ; } | 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 ByteArrayInputStream ( bytes ) ) ; } catch ( ParserConfigurationException e ) { throw new InvalidContentModelException ( pid , "Failed to parse " + DS_COMPOSITE_MODEL , e ) ; } catch ( SAXException e ) { throw new InvalidContentModelException ( pid , "Failed to parse " + DS_COMPOSITE_MODEL , e ) ; } catch ( IOException e ) { throw new InvalidContentModelException ( pid , "Failed to parse " + DS_COMPOSITE_MODEL , e ) ; } } | 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 ) ; DSLocation = TEMP_SCHEME + tempFile . getAbsolutePath ( ) ; } catch ( Exception e ) { throw new StreamIOException ( "Error creating new temp file for updated managed content (existing content is:" + oldDSLocation + ")" , e ) ; } if ( oldDSLocation != null && oldDSLocation . startsWith ( TEMP_SCHEME ) ) { File oldFile ; try { oldFile = new File ( oldDSLocation . substring ( TEMP_SCHEME . length ( ) ) ) ; } catch ( Exception e ) { throw new StreamIOException ( "Error removing old temp file while updating managed content (location: " + oldDSLocation + ")" , e ) ; } if ( oldFile . exists ( ) ) { if ( ! oldFile . delete ( ) ) { logger . warn ( "Failed to delete temp file, marked for deletion when VM closes " + oldFile . getAbsolutePath ( ) ) ; oldFile . deleteOnExit ( ) ; } } else logger . warn ( "Cannot delete temp file as it no longer exists " + oldFile . getAbsolutePath ( ) ) ; } } | 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 ; } } rs . close ( ) ; return false ; } | 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 + "' attribute." ) ; } return mapNameAttribute . getValue ( ) ; } | 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 [ userParms . length ] ; for ( int i = 0 ; i < userParms . length ; i ++ ) { parmValues [ i ] = userParms [ i ] . value == null ? "" : userParms [ i ] . value ; parmClassTypes [ i ] = parmValues [ i ] . getClass ( ) ; } try { method = service_object . getClass ( ) . getMethod ( methodName , parmClassTypes ) ; return method . invoke ( service_object , parmValues ) ; } catch ( Exception e ) { throw new MethodNotFoundException ( "Error executing method: " + methodName , e ) ; } } | 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 . utilities . TypeUtility . convertStringtoAOS ( OBJECT_RESULT_FIELDS ) , MAX_FIND_RESULTS , genFieldSearchQuery ) ; FieldSearchResult fsr = TypeUtility . convertGenFieldSearchResultToFieldSearchResult ( searchResult ) ; for ( ObjectFields fields : fsr . objectFieldsList ( ) ) { stash . add ( fields . getPid ( ) ) ; } token = fsr . getToken ( ) ; } | 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 ( ) ) { stash . add ( fields . getPid ( ) ) ; } token = fsr . getToken ( ) ; } | 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 . setEntity ( entity ) ; HttpResponse response = getHttpClient ( ) . execute ( post ) ; int responseCode = response . getStatusLine ( ) . getStatusCode ( ) ; String body = null ; try { if ( response . getEntity ( ) != null ) { body = EntityUtils . toString ( response . getEntity ( ) ) ; } } catch ( Exception e ) { logger . warn ( "Error reading response body" , e ) ; } if ( body == null ) { body = "[empty response body]" ; } body = body . trim ( ) ; if ( responseCode != HttpStatus . SC_CREATED ) { throw new IOException ( "Upload failed: " + response . getStatusLine ( ) . getReasonPhrase ( ) + ": " + replaceNewlines ( body , " " ) ) ; } else { return replaceNewlines ( body , "" ) ; } } finally { if ( post != null ) { post . releaseConnection ( ) ; } } } | 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 = redirectURL . toString ( ) ; } } return m_uploadURL ; } } | 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 new IOException ( "Could not find repositoryVersion element in content of /describe?xml=true" ) ; } int i = parts [ 1 ] . indexOf ( "<" ) ; if ( i == - 1 ) { throw new IOException ( "Could not find end of repositoryVersion element in content of /describe?xml=true" ) ; } m_serverVersion = parts [ 1 ] . substring ( 0 , i ) . trim ( ) ; logger . debug ( "Server version is " + m_serverVersion ) ; } return m_serverVersion ; } | 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 + "describe" ) ; } dateString = header . getValue ( ) ; SimpleDateFormat format = new SimpleDateFormat ( "EEE, dd MMM yyyy HH:mm:ss z" , Locale . US ) ; format . setTimeZone ( TimeZone . getTimeZone ( "UTC" ) ) ; return format . parse ( dateString ) ; } catch ( ParseException e ) { throw new IOException ( "Unparsable date (" + dateString + ") in HTTP response header for " + m_baseURL + "describe" ) ; } finally { in . close ( ) ; } } | 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 . close ( ) ; } catch ( Exception e ) { } } } | 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 ( fTransacted , ackMode ) ; } catch ( JMSException e ) { throw new MessagingException ( e . getMessage ( ) , e ) ; } Destination destination = null ; try { destination = ( Destination ) jndiLookup ( name ) ; } catch ( MessagingException me ) { logger . debug ( "JNDI lookup for destination " + name + " failed. " + "Destination must be created." ) ; destination = null ; } if ( destination == null ) { try { if ( type . equals ( DestinationType . Queue ) ) { logger . debug ( "setupDestination() - creating Queue" + name ) ; destination = session . createQueue ( name ) ; } else { logger . debug ( "setupDestination() - creating Topic " + name ) ; destination = session . createTopic ( name ) ; } } catch ( JMSException e ) { throw new MessagingException ( e . getMessage ( ) , e ) ; } } jmsDest = new JMSDestination ( destination , session , null , null ) ; jmsDestinations . put ( name , jmsDest ) ; return destination ; } | 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 . isDebugEnabled ( ) ) { logger . debug ( "send() - message sent to destination " + destName ) ; } } | 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 . getMessage ( ) , e ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "send() - message sent to destination " + dest ) ; } } | 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 ) { jmsDest . consumer . close ( ) ; logger . debug ( "Closed consumer for " + destName ) ; } if ( jmsDest . session != null ) { jmsDest . session . close ( ) ; logger . debug ( "Closed session for " + destName ) ; } jmsDest . destination = null ; jmsDest . session = null ; jmsDest . producer = null ; jmsDest . consumer = null ; jmsDestinations . remove ( destName ) ; jmsDest = null ; } } catch ( JMSException e ) { throw new MessagingException ( e . getMessage ( ) , e ) ; } } | 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 encountered attempting to " + "stop durable subscription with name: " + subscriptionName + ". Exception message: " + jmse . getMessage ( ) , jmse ) ; } } | 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 . unsubscribe ( subscriptionName ) ; } catch ( JMSException jmse ) { String errMsg = "Unable to unsubscribe from subscription with name: " + subscriptionName + " due to exception: " + jmse . getMessage ( ) ; logger . debug ( errMsg , jmse ) ; throw new MessagingException ( errMsg , jmse ) ; } } | 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 ( ) . destination ) ; } return destinations ; } | 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 ( JMSException e ) { connected = false ; logger . error ( "JMSManager.connectToJMS - Exception occurred:" ) ; throw new MessagingException ( e . getMessage ( ) , e ) ; } } | 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 = convertClearTextToByteArray ( clearText ) ; byte [ ] cipherBytes = applyCipher ( keyBytes , clearTextBytes ) ; return Base64 . encodeToString ( cipherBytes ) ; } | 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 [ ] keyBytes = convertKeyToByteArray ( key ) ; byte [ ] cipherBytes = Base64 . decode ( cipherText ) ; sanityCheckOnCipherBytes ( cipherText , cipherBytes ) ; byte [ ] clearTextBytes = applyCipher ( keyBytes , cipherBytes ) ; return convertByteArrayToClearText ( clearTextBytes ) ; } else { throw new IllegalArgumentException ( "Unrecognized cipher type: '" + cipherType + "'" ) ; } } | 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 + 1 ] = ( byte ) ( thisChar & 0xFF ) ; } return result ; } | 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 ( ) || userFileBytesLoaded != userFile . length ( ) ) { userDoc = DataUtils . getDocumentFromFile ( userFile ) ; userFileParsed = userFile . lastModified ( ) ; userFileBytesLoaded = userFile . length ( ) ; } } } return userDoc ; } | 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]+)([HM]?)" ) ; Matcher m = p . matcher ( intervalString ) ; if ( ! m . matches ( ) ) { throw new JournalException ( "Parameter '" + PARAMETER_FOLLOW_POLLING_INTERVAL + "' must be an positive integer number of seconds, " + "optionally followed by 'H'(hours), or 'M'(minutes)" ) ; } long interval = Long . parseLong ( m . group ( 1 ) ) * 1000 ; String factor = m . group ( 2 ) ; if ( "H" . equals ( factor ) ) { interval *= 60 * 60 ; } else if ( "M" . equals ( factor ) ) { interval *= 60 ; } return interval ; } | 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" ) ; } assertInvalid ( ) ; if ( errorMessage != null ) { logger . error ( m + "errorMessage==" + errorMessage ) ; throw new Exception ( errorMessage ) ; } else { validate ( authenticated , map ) ; } } catch ( Throwable t ) { logger . error ( m + "invalidating to be sure" ) ; this . invalidate ( errorMessage ) ; } finally { logger . debug ( "{}<" , m ) ; } } | 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 , String . class , ServerInterface . class } , new Object [ ] { parameters , role , server } , parameters ) ; logger . info ( "JournalRecoveryLog is " + recoveryLog . toString ( ) ) ; return ( JournalRecoveryLog ) recoveryLog ; } catch ( JournalException e ) { throw new ModuleInitializationException ( "Can't create JournalRecoveryLog" , role , e ) ; } } | Create an instance of the proper JournalRecoveryLog child class as determined by the server parameters . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.