idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
4,500
private ObjectNode getLocalizedObject ( Node n ) throws GraphElementFactoryException { if ( n instanceof URIReference ) { return getLocalizedResource ( n ) ; } else if ( n instanceof Literal ) { Literal l = ( Literal ) n ; GraphElementFactory elementFactory = _connector . getElementFactory ( ) ; if ( l . getDatatypeURI ( ) != null ) { return elementFactory . createLiteral ( l . getLexicalForm ( ) , l . getDatatypeURI ( ) ) ; } else if ( l . getLanguage ( ) != null ) { return elementFactory . createLiteral ( l . getLexicalForm ( ) , l . getLanguage ( ) ) ; } else { return elementFactory . createLiteral ( l . getLexicalForm ( ) ) ; } } else { throw new RuntimeException ( "Error localizing triple; " + n . getClass ( ) . getName ( ) + " is not a URIReference " + "or a Literal" ) ; } }
Gets a localized URIReference or Literal based on the given Node .
4,501
private void scanThroughFilesForNextJournalEntry ( ) throws JournalException { try { while ( true ) { if ( currentFile != null ) { advancePastWhitespace ( currentFile . getReader ( ) ) ; XMLEvent next = currentFile . getReader ( ) . peek ( ) ; if ( isStartTagEvent ( next , QNAME_TAG_JOURNAL_ENTRY ) ) { return ; } else if ( isEndTagEvent ( next , QNAME_TAG_JOURNAL ) ) { closeCurrentFile ( ) ; } else { throw getNotNextMemberOrEndOfGroupException ( QNAME_TAG_JOURNAL , QNAME_TAG_JOURNAL_ENTRY , next ) ; } } if ( currentFile == null ) { currentFile = openNextFile ( ) ; } if ( currentFile == null ) { return ; } advanceIntoFile ( currentFile . getReader ( ) ) ; } } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } }
Advance to the next journal entry if there is one . If we find one the current file will be pointing to it . If we don t find one there will be no current file .
4,502
protected JournalInputFile openNextFile ( ) throws JournalException { File [ ] journalFiles = MultiFileJournalHelper . getSortedArrayOfJournalFiles ( journalDirectory , filenamePrefix ) ; if ( journalFiles . length == 0 ) { return null ; } JournalInputFile nextFile = new JournalInputFile ( journalFiles [ 0 ] ) ; recoveryLog . log ( "Opening journal file: '" + nextFile . getFilename ( ) + "'" ) ; return nextFile ; }
Look in the directory for files that match the prefix . If there are none leave with currentFile still null . If we find one advance into it .
4,503
public static boolean sameResource ( URIReference u1 , String u2 ) { return u1 . getURI ( ) . toString ( ) . equals ( u2 ) ; }
Tells whether the given resources are equivalent with one given as a URI string .
4,504
public static boolean sameLiteral ( Literal l1 , String l2 , URI type , String lang ) { if ( l1 . getLexicalForm ( ) . equals ( l2 ) && eq ( l1 . getLanguage ( ) , lang ) ) { if ( l1 . getDatatypeURI ( ) == null ) { return type == null ; } else { return type != null && type . equals ( l1 . getDatatypeURI ( ) ) ; } } else { return false ; } }
Tells whether the given literals are equivalent with one given as a set of simple values .
4,505
public static boolean sameSubject ( SubjectNode s1 , String s2 ) { if ( s1 instanceof URIReference ) { return sameResource ( ( URIReference ) s1 , s2 ) ; } else { return false ; } }
Tells whether the given subjects are equivalent with one given as a URI string .
4,506
public static boolean sameObject ( ObjectNode o1 , String o2 , boolean isLiteral , URI type , String lang ) { if ( o1 instanceof URIReference ) { return sameResource ( ( URIReference ) o1 , o2 ) ; } else if ( o1 instanceof Literal || isLiteral ) { return sameLiteral ( ( Literal ) o1 , o2 , type , lang ) ; } else { return false ; } }
Tells whether the given objects are equivalent with one given as a set of simple values .
4,507
public void close ( ) throws IOException { if ( open ) { if ( residual . length ( ) > 0 ) { throw new IOException ( "Base64 error - data is not properly" + "padded to 4-character groups." ) ; } stream . close ( ) ; open = false ; } }
Close the writer . If there are any residual characters at this point the data stream was not a valid Base64 encoding .
4,508
private int countRelations ( String relationName , Set < RelationshipTuple > objectRelations ) { int count = 0 ; if ( objectRelations == null ) { return 0 ; } for ( RelationshipTuple objectRelation : objectRelations ) { if ( objectRelation . predicate . equals ( relationName ) ) { count ++ ; } } return count ; }
Private utility method . Counts the number of relations with a given name in a list of relatiosn
4,509
public void setXMLContent ( byte [ ] xmlContent ) { if ( m_dsType == DS_TYPE . INLINE_XML ) { ( ( DatastreamXMLMetadata ) m_ds ) . xmlContent = xmlContent ; ( ( DatastreamXMLMetadata ) m_ds ) . DSSize = ( xmlContent != null ) ? xmlContent . length : - 1 ; } else if ( m_dsType == DS_TYPE . MANAGED ) { ByteArrayInputStream bais = new ByteArrayInputStream ( xmlContent ) ; MIMETypedStream s = new MIMETypedStream ( "text/xml" , bais , null , xmlContent . length ) ; try { ( ( DatastreamManagedContent ) m_ds ) . putContentStream ( s ) ; } catch ( StreamIOException e ) { throw new RuntimeException ( "Unable to update managed datastream contents" , e ) ; } } else throw new RuntimeException ( "XML datastreams must be of type Managed or Inline" ) ; }
Update the XML content of the datastream wrapped by this class
4,510
public void setDSMDClass ( int DSMDClass ) { if ( m_dsType == DS_TYPE . INLINE_XML ) ( ( DatastreamXMLMetadata ) m_ds ) . DSMDClass = DSMDClass ; else if ( m_dsType == DS_TYPE . MANAGED ) ( ( DatastreamManagedContent ) m_ds ) . DSMDClass = DSMDClass ; else throw new RuntimeException ( "XML datastreams must be of type Managed or Inline" ) ; }
Set the DSMDClass of the datastream wrapped by this class
4,511
public Map < RDFName , List < DCField > > getMap ( ) { Map < RDFName , List < DCField > > map = new HashMap < RDFName , List < DCField > > ( 15 ) ; if ( m_titles != null ) map . put ( DC . TITLE , m_titles ) ; if ( m_creators != null ) map . put ( DC . CREATOR , m_creators ) ; if ( m_subjects != null ) map . put ( DC . SUBJECT , m_subjects ) ; if ( m_descriptions != null ) map . put ( DC . DESCRIPTION , m_descriptions ) ; if ( m_publishers != null ) map . put ( DC . PUBLISHER , m_publishers ) ; if ( m_contributors != null ) map . put ( DC . CONTRIBUTOR , m_contributors ) ; if ( m_dates != null ) map . put ( DC . DATE , m_dates ) ; if ( m_types != null ) map . put ( DC . TYPE , m_types ) ; if ( m_formats != null ) map . put ( DC . FORMAT , m_formats ) ; if ( m_identifiers != null ) map . put ( DC . IDENTIFIER , m_identifiers ) ; if ( m_sources != null ) map . put ( DC . SOURCE , m_sources ) ; if ( m_languages != null ) map . put ( DC . LANGUAGE , m_languages ) ; if ( m_relations != null ) map . put ( DC . RELATION , m_relations ) ; if ( m_coverages != null ) map . put ( DC . COVERAGE , m_coverages ) ; if ( m_rights != null ) map . put ( DC . RIGHTS , m_rights ) ; return map ; }
Returns a Map with RDFName keys each value containing List of String values for that field .
4,512
public void setSecuritySpec ( String serviceRoleID , String methodName , Hashtable < String , String > properties ) throws GeneralException { logger . debug ( ">>>>>> setSecuritySpec: " + " serviceRoleID=" + serviceRoleID + " methodName=" + methodName + " property count=" + properties . size ( ) ) ; if ( serviceRoleID == null || serviceRoleID . isEmpty ( ) ) { throw new GeneralException ( "serviceRoleID is missing." ) ; } if ( methodName == null || methodName . isEmpty ( ) ) { rolePropertiesTable . put ( serviceRoleID , properties ) ; } else { Hashtable < String , String > serviceProps = rolePropertiesTable . get ( serviceRoleID ) ; if ( serviceProps == null ) { throw new GeneralException ( "Cannot add method-level security properties" + " if there are no properties defined for the backend service that the " + " method is part of. " ) ; } String roleKey = serviceRoleID + "/" + methodName ; rolePropertiesTable . put ( roleKey , properties ) ; } }
Set the security properties at the backend service or for a method of that backend service .
4,513
public Hashtable < String , String > getSecuritySpec ( String serviceRoleID , String methodName ) { if ( serviceRoleID == null || serviceRoleID . isEmpty ( ) ) { return getDefaultSecuritySpec ( ) ; } else if ( methodName == null || methodName . isEmpty ( ) ) { return rolePropertiesTable . get ( serviceRoleID ) ; } else { String roleKey = serviceRoleID + "/" + methodName ; Hashtable < String , String > properties = rolePropertiesTable . get ( roleKey ) ; if ( properties == null ) { properties = rolePropertiesTable . get ( serviceRoleID ) ; } if ( properties == null ) { properties = getDefaultSecuritySpec ( ) ; } return properties ; } }
Get security properties for either the a backend service or a method within that backend service .
4,514
public static String getElementNodeValue ( Node node ) { StringWriter sw = new StringWriter ( 2000 ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { NodeList all = node . getChildNodes ( ) ; for ( int i = 0 ; i < all . getLength ( ) ; i ++ ) { if ( all . item ( i ) . getNodeType ( ) == Node . TEXT_NODE || all . item ( i ) . getNodeType ( ) == Node . CDATA_SECTION_NODE ) { sw . append ( all . item ( i ) . getNodeValue ( ) ) ; } } } return sw . toString ( ) ; }
Extracts all textual and CDATA content from the given node and its children .
4,515
public static Document stringToDOM ( String xmlString , boolean namespaceAware ) { try { InputSource in = new InputSource ( ) ; in . setCharacterStream ( new StringReader ( xmlString ) ) ; DocumentBuilderFactory dbFact = DocumentBuilderFactory . newInstance ( ) ; dbFact . setNamespaceAware ( namespaceAware ) ; return dbFact . newDocumentBuilder ( ) . parse ( in ) ; } catch ( IOException e ) { log . warn ( "I/O error when parsing XML :" + e . getMessage ( ) + "\n" + xmlString , e ) ; } catch ( SAXException e ) { log . warn ( "Parse error when parsing XML :" + e . getMessage ( ) + "\n" + xmlString , e ) ; } catch ( ParserConfigurationException e ) { log . warn ( "Parser configuration error when parsing XML :" + e . getMessage ( ) + "\n" + xmlString , e ) ; } return null ; }
Parses an XML document from a String to a DOM .
4,516
public static final ReadOnlyContext getContext ( String messageProtocol , String subjectId , String password , boolean noOp ) throws Exception { MultiValueMap < URI > environmentMap = beginEnvironmentMap ( messageProtocol ) ; environmentMap . lock ( ) ; return getContext ( null , environmentMap , subjectId , password , null , noOp ) ; }
needed only for rebuild
4,517
public static boolean copy ( InputStream source , ByteBuffer destination ) { try { byte [ ] buffer = new byte [ 4096 ] ; int n = 0 ; while ( - 1 != ( n = source . read ( buffer ) ) ) { destination . put ( buffer , 0 , n ) ; } return true ; } catch ( IOException e ) { return false ; } }
This method should only be used when the ByteBuffer is known to be able to accomodate the input!
4,518
public static boolean copy ( File source , File destination ) { boolean result = true ; if ( source . isDirectory ( ) ) { if ( destination . exists ( ) ) { result = result && destination . isDirectory ( ) ; } else { result = result && destination . mkdirs ( ) ; } File [ ] children = source . listFiles ( ) ; for ( File element : children ) { result = result && copy ( new File ( source , element . getName ( ) ) , new File ( destination , element . getName ( ) ) ) ; } return result ; } else { try { InputStream in = new FileInputStream ( source ) ; OutputStream out = new FileOutputStream ( destination ) ; result = result && copy ( in , out ) ; in . close ( ) ; out . close ( ) ; return result ; } catch ( IOException e ) { return false ; } } }
Copy a file or directory .
4,519
public static boolean delete ( File file ) { boolean result = true ; if ( file == null ) { return false ; } if ( file . exists ( ) ) { if ( file . isDirectory ( ) ) { File [ ] children = file . listFiles ( ) ; for ( File child : children ) { result = result && delete ( child ) ; } } result = result && file . delete ( ) ; } return result ; }
Delete a File .
4,520
public static Map < String , String > loadMap ( File f ) throws IOException { Properties props = new Properties ( ) ; FileInputStream in = new FileInputStream ( f ) ; try { props . load ( in ) ; Map < String , String > map = new HashMap < String , String > ( ) ; Set < Entry < Object , Object > > entrySet = props . entrySet ( ) ; for ( Entry < Object , Object > entry : entrySet ) { map . put ( ( String ) entry . getKey ( ) , ( String ) entry . getValue ( ) ) ; } return map ; } finally { try { in . close ( ) ; } catch ( IOException e ) { } } }
Loads a Map from the given Properties file .
4,521
public void init ( ServletConfig config ) throws ServletException { m_cache = new HashMap < String , Templates > ( ) ; m_creds = new HashMap < String , UsernamePasswordCredentials > ( ) ; m_cManager = new PoolingClientConnectionManager ( ) ; m_cManager . getSchemeRegistry ( ) . register ( new Scheme ( "https" , 443 , SSLSocketFactory . getSocketFactory ( ) ) ) ; m_cManager . getSchemeRegistry ( ) . register ( new Scheme ( "https-tomcat" , 8443 , SSLSocketFactory . getSocketFactory ( ) ) ) ; m_cManager . getSchemeRegistry ( ) . register ( new Scheme ( "http" , 80 , PlainSocketFactory . getSocketFactory ( ) ) ) ; m_cManager . getSchemeRegistry ( ) . register ( new Scheme ( "http-tomcat" , 8080 , PlainSocketFactory . getSocketFactory ( ) ) ) ; Enumeration < ? > enm = config . getInitParameterNames ( ) ; while ( enm . hasMoreElements ( ) ) { String name = ( String ) enm . nextElement ( ) ; if ( name . startsWith ( CRED_PARAM_START ) ) { String value = config . getInitParameter ( name ) ; if ( value . indexOf ( ":" ) == - 1 ) { throw new ServletException ( "Malformed credentials for " + name + " -- expected ':' user/pass delimiter" ) ; } String [ ] parts = value . split ( ":" ) ; String user = parts [ 0 ] ; StringBuffer pass = new StringBuffer ( ) ; for ( int i = 1 ; i < parts . length ; i ++ ) { if ( i > 1 ) { pass . append ( ':' ) ; } pass . append ( parts [ i ] ) ; } m_creds . put ( name . substring ( CRED_PARAM_START . length ( ) ) , new UsernamePasswordCredentials ( user , pass . toString ( ) ) ) ; } } }
Initialize the servlet by setting up the stylesheet cache the http connection manager and configuring credentials for the http client .
4,522
private void apply ( String style , String source , HttpServletRequest req , HttpServletResponse res ) throws Exception { if ( style == null ) { throw new TransformerException ( "No style parameter supplied" ) ; } if ( source == null ) { throw new TransformerException ( "No source parameter supplied" ) ; } InputStream sourceStream = null ; try { Templates pss = tryCache ( style ) ; Transformer transformer = pss . newTransformer ( ) ; Enumeration < ? > p = req . getParameterNames ( ) ; while ( p . hasMoreElements ( ) ) { String name = ( String ) p . nextElement ( ) ; if ( ! ( name . equals ( "style" ) || name . equals ( "source" ) ) ) { String value = req . getParameter ( name ) ; transformer . setParameter ( name , new StringValue ( value ) ) ; } } sourceStream = getInputStream ( source ) ; String mime = pss . getOutputProperties ( ) . getProperty ( OutputKeys . MEDIA_TYPE ) ; if ( mime == null ) { res . setContentType ( "text/html" ) ; } else { res . setContentType ( mime ) ; } StreamSource ss = new StreamSource ( sourceStream ) ; ss . setSystemId ( source ) ; transformer . transform ( ss , new StreamResult ( res . getOutputStream ( ) ) ) ; } finally { if ( sourceStream != null ) { try { sourceStream . close ( ) ; } catch ( Exception e ) { } } } }
Apply stylesheet to source document
4,523
private Templates tryCache ( String url ) throws Exception { Templates x = ( Templates ) m_cache . get ( url ) ; if ( x == null ) { synchronized ( m_cache ) { if ( ! m_cache . containsKey ( url ) ) { TransformerFactory factory = TransformerFactory . newInstance ( ) ; if ( factory . getClass ( ) . getName ( ) . equals ( "net.sf.saxon.TransformerFactoryImpl" ) ) { factory . setAttribute ( FeatureKeys . VERSION_WARNING , Boolean . FALSE ) ; } StreamSource ss = new StreamSource ( getInputStream ( url ) ) ; ss . setSystemId ( url ) ; x = factory . newTemplates ( ss ) ; m_cache . put ( url , x ) ; } } } return x ; }
Maintain prepared stylesheets in memory for reuse
4,524
private UsernamePasswordCredentials getCreds ( String url ) throws Exception { url = normalizeURL ( url ) ; url = url . substring ( url . indexOf ( "/" ) + 2 ) ; UsernamePasswordCredentials longestMatch = null ; int longestMatchLength = 0 ; Iterator < String > iter = m_creds . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String realmPath = ( String ) iter . next ( ) ; if ( url . startsWith ( realmPath ) ) { int matchLength = realmPath . length ( ) ; if ( matchLength > longestMatchLength ) { longestMatchLength = matchLength ; longestMatch = ( UsernamePasswordCredentials ) m_creds . get ( realmPath ) ; } } } return longestMatch ; }
Return the credentials for the realmPath that most closely matches the given url or null if none found .
4,525
private static String normalizeURL ( String urlString ) throws MalformedURLException { URL url = new URL ( urlString ) ; if ( url . getPort ( ) == - 1 ) { return url . getProtocol ( ) + "://" + url . getHost ( ) + ":" + url . getDefaultPort ( ) + url . getFile ( ) + ( url . getRef ( ) != null ? "#" + url . getRef ( ) : "" ) ; } else { return urlString ; } }
Return a URL string in which the port is always specified .
4,526
protected static Document getDocument ( InputStream in ) throws Exception { DocumentBuilder builder = XmlTransformUtility . borrowDocumentBuilder ( ) ; Document doc = null ; try { doc = builder . parse ( in ) ; } finally { XmlTransformUtility . returnDocumentBuilder ( builder ) ; } return doc ; }
Get a new DOM Document object from parsing the specified InputStream .
4,527
public void init ( String type , InputStream data , boolean viewOnly ) throws IOException { setContent ( data ) ; }
Initializes the handler . This should only be called once per instance and is guaranteed to have been called when this component is provided by the ContentHandlerFactory . The viewOnly parameter signals to ContentEditor implementations that editing capabilities are not desired by the caller .
4,528
public void init ( ServletConfig config ) throws ServletException { super . init ( config ) ; m_management = ( Management ) m_server . getModule ( "org.fcrepo.server.management.Management" ) ; if ( m_management == null ) { throw new ServletException ( "Unable to get Management module from server." ) ; } }
Initialize servlet . Gets a reference to the fedora Server object .
4,529
public static List < MethodDefinition > getMethodDefinitions ( String sDefPID ) throws IOException { return MethodDefinition . parse ( Administrator . DOWNLOADER . getDatastreamDissemination ( sDefPID , "METHODMAP" , null ) ) ; }
Get the list of MethodDefinition objects defined by the indicated service definition .
4,530
public static ObjectFields getObjectFields ( String pid , String [ ] fields ) throws IOException { FieldSearchQuery query = new FieldSearchQuery ( ) ; Condition condition = new Condition ( ) ; condition . setProperty ( "pid" ) ; condition . setOperator ( ComparisonOperator . fromValue ( "eq" ) ) ; condition . setValue ( pid ) ; FieldSearchQuery . Conditions conds = new FieldSearchQuery . Conditions ( ) ; conds . getCondition ( ) . add ( condition ) ; ObjectFactory factory = new ObjectFactory ( ) ; query . setConditions ( factory . createFieldSearchQueryConditions ( conds ) ) ; FieldSearchResult result = Administrator . APIA . findObjects ( TypeUtility . convertStringtoAOS ( fields ) , new BigInteger ( "1" ) , query ) ; ResultList resultList = result . getResultList ( ) ; if ( resultList == null || resultList . getObjectFields ( ) == null && resultList . getObjectFields ( ) . size ( ) == 0 ) { throw new IOException ( "Object not found in repository" ) ; } return resultList . getObjectFields ( ) . get ( 0 ) ; }
Get the indicated fields of the indicated object from the repository .
4,531
private final Map < String , String > getFormFields ( Node parent ) { String method = "getFormFields(Node parent)" ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( enter ( method ) ) ; } Map < String , String > formfields = new Hashtable < String , String > ( ) ; getFormFields ( parent , formfields ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( exit ( method ) ) ; } return formfields ; }
initial setup call
4,532
private final void getFormFields ( Node parent , Map < String , String > formfields ) { String method = "getFormFields(Node parent, Map formfields)" ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( enter ( method ) ) ; } NodeList children = parent . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node child = children . item ( i ) ; String tag = child . getNodeName ( ) ; if ( "input" . equalsIgnoreCase ( tag ) ) { NamedNodeMap attributes = child . getAttributes ( ) ; Node typeNode = attributes . getNamedItem ( "type" ) ; String type = typeNode . getNodeValue ( ) ; Node nameNode = attributes . getNamedItem ( "name" ) ; String name = nameNode . getNodeValue ( ) ; Node valueNode = attributes . getNamedItem ( "value" ) ; String value = "" ; if ( valueNode != null ) { value = valueNode . getNodeValue ( ) ; } if ( "hidden" . equalsIgnoreCase ( type ) && value != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( format ( "capturing hidden fields" , name , value ) ) ; } formfields . put ( name , value ) ; } } getFormFields ( child , formfields ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( exit ( method ) ) ; } }
inner recursive call
4,533
public void setData ( byte [ ] data ) throws IOException { output = new ByteArrayOutputStream ( ) ; output . write ( data ) ; output . flush ( ) ; setContentLength ( output . size ( ) ) ; }
Sets the body of this response .
4,534
public String getResponseHeaderValue ( String name , String defaultVal ) { if ( m_response . containsHeader ( name ) ) { return m_response . getFirstHeader ( name ) . getValue ( ) ; } else { return defaultVal ; } }
Return the first value of a header or the default if the fighter is not present
4,535
private void addMethodDefTriples ( URIReference objURI , DOReader reader , Set < Triple > set ) throws ResourceIndexException { try { for ( MethodDef element : getAbstractMethods ( reader ) ) { add ( objURI , MODEL . DEFINES_METHOD , element . methodName , set ) ; } } catch ( ResourceIndexException e ) { throw e ; } catch ( Exception e ) { throw new ResourceIndexException ( "Error adding method def " + "triples" , e ) ; } }
Add a defines statement for the given sDef for each abstract method it defines .
4,536
private Map < String , Map < String , String > > parseTransportParameters ( Map < String , String > parameters ) throws JournalException { Map < String , Map < String , String > > allTransports = new LinkedHashMap < String , Map < String , String > > ( ) ; for ( String key : parameters . keySet ( ) ) { if ( isTransportParameter ( key ) ) { Map < String , String > thisTransport = getThisTransportMap ( allTransports , getTransportName ( key ) ) ; thisTransport . put ( getTransportParameterName ( key ) , parameters . get ( key ) ) ; } } return allTransports ; }
Create a Map of Maps holding parameters for all of the transports .
4,537
private Map < String , String > getThisTransportMap ( Map < String , Map < String , String > > allTransports , String transportName ) { if ( ! allTransports . containsKey ( transportName ) ) { allTransports . put ( transportName , new HashMap < String , String > ( ) ) ; } return allTransports . get ( transportName ) ; }
If we don t yet have a map for this transport name create one .
4,538
private Timer createTimer ( ) { Timer fileTimer = new Timer ( ) ; if ( ageLimit >= 0 ) { fileTimer . schedule ( new CloseFileTimerTask ( ) , ageLimit ) ; } return fileTimer ; }
Create the timer and schedule a task that will let us know when the file is too old to continue . If the age limit is 0 or negative we treat it as no limit .
4,539
public void writeJournalEntry ( CreatorJournalEntry journalEntry , XMLEventWriter writer ) throws JournalException { super . writeJournalEntry ( journalEntry , writer ) ; }
make this public so the TransportRequest class can call it .
4,540
public void writeDocumentHeader ( XMLEventWriter writer , String repositoryHash , Date currentDate ) throws JournalException { super . writeDocumentHeader ( writer , repositoryHash , currentDate ) ; }
make this public so the Transport classes can call it via TransportParent .
4,541
private void sendRequestToAllTransports ( TransportRequest request ) throws JournalException { Map < String , JournalException > crucialExceptions = new LinkedHashMap < String , JournalException > ( ) ; Map < String , JournalException > nonCrucialExceptions = new LinkedHashMap < String , JournalException > ( ) ; for ( String transportName : transports . keySet ( ) ) { Transport transport = transports . get ( transportName ) ; try { logger . debug ( "Sending " + request . getClass ( ) . getSimpleName ( ) + " to transport '" + transportName + "'" ) ; request . performRequest ( transport ) ; } catch ( JournalException e ) { if ( transport . isCrucial ( ) ) { crucialExceptions . put ( transportName , e ) ; } else { nonCrucialExceptions . put ( transportName , e ) ; } } } reportNonCrucialExceptions ( nonCrucialExceptions ) ; reportCrucialExceptions ( crucialExceptions ) ; }
Send a request for some operation to the Transports . Send it to all of them even if one or more throws an Exception . Report any exceptions when all Transports have been attempted .
4,542
public MIMETypedStream viewObjectProfile ( ) throws ServerException { try { ObjectProfile profile = m_access . getObjectProfile ( context , reader . GetObjectPID ( ) , asOfDateTime ) ; Reader in = null ; try { ReadableCharArrayWriter out = new ReadableCharArrayWriter ( 1024 ) ; DefaultSerializer . objectProfileToXML ( profile , asOfDateTime , out ) ; out . close ( ) ; in = out . toReader ( ) ; } catch ( IOException ioe ) { throw new GeneralException ( "[DefaultDisseminatorImpl] An error has occurred. " + "The error was a \"" + ioe . getClass ( ) . getName ( ) + "\" . The " + "Reason was \"" + ioe . getMessage ( ) + "\" ." ) ; } ReadableByteArrayOutputStream bytes = new ReadableByteArrayOutputStream ( 4096 ) ; PrintWriter out = new PrintWriter ( new OutputStreamWriter ( bytes , Charset . forName ( "UTF-8" ) ) ) ; File xslFile = new File ( reposHomeDir , "access/viewObjectProfile.xslt" ) ; Templates template = XmlTransformUtility . getTemplates ( xslFile ) ; Transformer transformer = template . newTransformer ( ) ; transformer . setParameter ( "fedora" , context . getEnvironmentValue ( Constants . FEDORA_APP_CONTEXT_NAME ) ) ; transformer . transform ( new StreamSource ( in ) , new StreamResult ( out ) ) ; out . close ( ) ; return new MIMETypedStream ( "text/html" , bytes . toInputStream ( ) , null , bytes . length ( ) ) ; } catch ( Exception e ) { throw new DisseminationException ( "[DefaultDisseminatorImpl] had an error " + "in transforming xml for viewObjectProfile. " + "Underlying exception was: " + e . getMessage ( ) ) ; } }
Returns an HTML rendering of the object profile which contains key metadata from the object plus URLs for the object s Dissemination Index and Item Index . The data is returned as HTML in a presentation - oriented format . This is accomplished by doing an XSLT transform on the XML that is obtained from getObjectProfile in API - A .
4,543
public MIMETypedStream viewMethodIndex ( ) throws ServerException { if ( reader . hasContentModel ( Models . SERVICE_DEFINITION_3_0 ) || reader . hasContentModel ( Models . SERVICE_DEPLOYMENT_3_0 ) ) { return noMethodIndexMsg ( ) ; } ObjectMethodsDef [ ] methods = m_access . listMethods ( context , reader . GetObjectPID ( ) , asOfDateTime ) ; ReadableCharArrayWriter buffer = new ReadableCharArrayWriter ( 1024 ) ; ObjectInfoAsXML . getMethodIndex ( reposBaseURL , reader . GetObjectPID ( ) , methods , asOfDateTime , buffer ) ; buffer . close ( ) ; Reader in = buffer . toReader ( ) ; try { ReadableByteArrayOutputStream bytes = new ReadableByteArrayOutputStream ( 2048 ) ; PrintWriter out = new PrintWriter ( new OutputStreamWriter ( bytes , Charset . forName ( "UTF-8" ) ) ) ; File xslFile = new File ( reposHomeDir , "access/listMethods.xslt" ) ; Templates template = XmlTransformUtility . getTemplates ( xslFile ) ; Transformer transformer = template . newTransformer ( ) ; transformer . setParameter ( "fedora" , context . getEnvironmentValue ( Constants . FEDORA_APP_CONTEXT_NAME ) ) ; transformer . transform ( new StreamSource ( in ) , new StreamResult ( out ) ) ; out . close ( ) ; return new MIMETypedStream ( "text/html" , bytes . toInputStream ( ) , null , bytes . length ( ) ) ; } catch ( Exception e ) { throw new DisseminationException ( "[DefaultDisseminatorImpl] had an error " + "in transforming xml for viewItemIndex. " + "Underlying exception was: " + e . getMessage ( ) ) ; } }
Returns an HTML rendering of the Dissemination Index for the object . The Dissemination Index is a list of method definitions that represent all disseminations possible on the object . The Dissemination Index is returned as HTML in a presentation - oriented format . This is accomplished by doing an XSLT transform on the XML that is obtained from listMethods in API - A .
4,544
public MIMETypedStream viewItemIndex ( ) throws ServerException { Reader in = null ; try { ReadableCharArrayWriter out = new ReadableCharArrayWriter ( 4096 ) ; ObjectInfoAsXML . getItemIndex ( reposBaseURL , context . getEnvironmentValue ( Constants . FEDORA_APP_CONTEXT_NAME ) , reader , asOfDateTime , out ) ; out . close ( ) ; in = out . toReader ( ) ; } catch ( Exception e ) { throw new GeneralException ( "[DefaultDisseminatorImpl] An error has occurred. " + "The error was a \"" + e . getClass ( ) . getName ( ) + "\" . The " + "Reason was \"" + e . getMessage ( ) + "\" ." ) ; } try { ReadableByteArrayOutputStream bytes = new ReadableByteArrayOutputStream ( 2048 ) ; PrintWriter out = new PrintWriter ( new OutputStreamWriter ( bytes , Charset . forName ( "UTF-8" ) ) ) ; File xslFile = new File ( reposHomeDir , "access/viewItemIndex.xslt" ) ; Templates template = XmlTransformUtility . getTemplates ( xslFile ) ; Transformer transformer = template . newTransformer ( ) ; transformer . setParameter ( "fedora" , context . getEnvironmentValue ( Constants . FEDORA_APP_CONTEXT_NAME ) ) ; transformer . transform ( new StreamSource ( in ) , new StreamResult ( out ) ) ; out . close ( ) ; return new MIMETypedStream ( "text/html" , bytes . toInputStream ( ) , null , bytes . length ( ) ) ; } catch ( Exception e ) { throw new DisseminationException ( "[DefaultDisseminatorImpl] had an error " + "in transforming xml for viewItemIndex. " + "Underlying exception was: " + e . getMessage ( ) ) ; } }
Returns an HTML rendering of the Item Index for the object . The Item Index is a list of all datastreams in the object . The datastream items can be data or metadata . The Item Index is returned as HTML in a presentation - oriented format . This is accomplished by doing an XSLT transform on the XML that is obtained from listDatastreams in API - A .
4,545
public MIMETypedStream viewDublinCore ( ) throws ServerException { Datastream dcmd = null ; Reader in = null ; try { ReadableCharArrayWriter out = new ReadableCharArrayWriter ( 512 ) ; dcmd = reader . GetDatastream ( "DC" , asOfDateTime ) ; ObjectInfoAsXML . getOAIDublinCore ( dcmd , out ) ; out . close ( ) ; in = out . toReader ( ) ; } catch ( ClassCastException cce ) { throw new ObjectIntegrityException ( "Object " + reader . GetObjectPID ( ) + " has a DC datastream, but it's not inline XML." ) ; } try { ReadableByteArrayOutputStream bytes = new ReadableByteArrayOutputStream ( 1024 ) ; PrintWriter out = new PrintWriter ( new OutputStreamWriter ( bytes , Charset . forName ( "UTF-8" ) ) ) ; File xslFile = new File ( reposHomeDir , "access/viewDublinCore.xslt" ) ; Templates template = XmlTransformUtility . getTemplates ( xslFile ) ; Transformer transformer = template . newTransformer ( ) ; transformer . setParameter ( "fedora" , context . getEnvironmentValue ( Constants . FEDORA_APP_CONTEXT_NAME ) ) ; transformer . transform ( new StreamSource ( in ) , new StreamResult ( out ) ) ; out . close ( ) ; return new MIMETypedStream ( "text/html" , bytes . toInputStream ( ) , null , bytes . length ( ) ) ; } catch ( Exception e ) { throw new DisseminationException ( "[DefaultDisseminatorImpl] had an error " + "in transforming xml for viewDublinCore. " + "Underlying exception was: " + e . getMessage ( ) ) ; } }
Returns the Dublin Core record for the object if one exists . The record is returned as HTML in a presentation - oriented format .
4,546
public static MethodDef [ ] reflectMethods ( ) { ArrayList < MethodDef > methodList = new ArrayList < MethodDef > ( ) ; MethodDef method = null ; method = new MethodDef ( ) ; method . methodName = "viewObjectProfile" ; method . methodLabel = "View description of the object" ; method . methodParms = new MethodParmDef [ 0 ] ; methodList . add ( method ) ; method = new MethodDef ( ) ; method . methodName = "viewMethodIndex" ; method . methodLabel = "View a list of dissemination methods in the object" ; method . methodParms = new MethodParmDef [ 0 ] ; methodList . add ( method ) ; method = new MethodDef ( ) ; method . methodName = "viewItemIndex" ; method . methodLabel = "View a list of items in the object" ; method . methodParms = new MethodParmDef [ 0 ] ; methodList . add ( method ) ; method = new MethodDef ( ) ; method . methodName = "viewDublinCore" ; method . methodLabel = "View the Dublin Core record for the object" ; method . methodParms = new MethodParmDef [ 0 ] ; methodList . add ( method ) ; return methodList . toArray ( new MethodDef [ 0 ] ) ; }
Method implementation of reflectMethods from the InternalService interface . This will return an array of method definitions that constitute the behaviors of the Default Disseminator which is associated with every Fedora object . These will be the methods promulgated by the DefaultDisseminator interface .
4,547
public static Connection getDefaultConnection ( ServerConfiguration serverConfig ) { ModuleConfiguration poolConfig = serverConfig . getModuleConfiguration ( "org.fcrepo.server.storage.ConnectionPoolManager" ) ; String datastoreID = poolConfig . getParameter ( "defaultPoolName" , Parameter . class ) . getValue ( ) ; DatastoreConfiguration dbConfig = serverConfig . getDatastoreConfiguration ( datastoreID ) ; return getConnection ( dbConfig . getParameter ( "jdbcDriverClass" , Parameter . class ) . getValue ( ) , dbConfig . getParameter ( "jdbcURL" , Parameter . class ) . getValue ( ) , dbConfig . getParameter ( "dbUsername" , Parameter . class ) . getValue ( ) , dbConfig . getParameter ( "dbPassword" , Parameter . class ) . getValue ( ) ) ; }
Gets a connection to the database specified in connection pool module s defaultPoolName config value . This allows us to the connect to the database without the server running .
4,548
public void close ( ) { readLock . lock ( ) ; try { if ( container != null ) { try { container . close ( ) ; container = null ; log . info ( "Closed container" ) ; } catch ( XmlException e ) { log . warn ( "close failed: " + e . getMessage ( ) , e ) ; } } if ( manager != null ) { try { manager . close ( ) ; manager = null ; log . info ( "Closed manager" ) ; } catch ( XmlException e ) { log . warn ( "close failed: " + e . getMessage ( ) , e ) ; } } } finally { readLock . unlock ( ) ; } }
Closes the dbxml container and manager .
4,549
public void addNamespace ( String prefix , String namespaceURI ) { if ( prefix == null || namespaceURI == null ) { throw new IllegalArgumentException ( "null arguments not allowed." ) ; } if ( namespaceURI . equals ( XMLConstants . XML_NS_URI ) ) { throw new IllegalArgumentException ( "Adding a new namespace for " + XMLConstants . XML_NS_URI + "not allowed." ) ; } else if ( namespaceURI . equals ( XMLConstants . XMLNS_ATTRIBUTE_NS_URI ) ) { throw new IllegalArgumentException ( "Adding a new namespace for " + XMLConstants . XMLNS_ATTRIBUTE_NS_URI + "not allowed." ) ; } prefix2ns . put ( prefix , namespaceURI ) ; }
Add a prefix to namespace mapping .
4,550
public ValidationResult validate ( ObjectInfo object ) { if ( object == null ) { throw new NullPointerException ( "object may not be null." ) ; } ValidationResult result = new ValidationResult ( object ) ; Collection < String > contentmodels = object . getContentModels ( ) ; if ( contentmodels . size ( ) == 0 ) { result . addNote ( ValidationResultNotation . noContentModel ( ) ) ; return result ; } for ( String contentmodel : contentmodels ) { validateAgainstContentModel ( result , contentmodel , object ) ; } return result ; }
Each object is expected to have at least one content model . Validate each of the content models .
4,551
private void confirmMatchForDsTypeModel ( ValidationResult result , DsTypeModel typeModel , String contentModelPid , ObjectInfo object ) { String id = typeModel . getId ( ) ; DatastreamInfo dsInfo = object . getDatastreamInfo ( id ) ; if ( dsInfo == null ) { result . addNote ( ValidationResultNotation . noMatchingDatastreamId ( contentModelPid , id ) ) ; return ; } Collection < Form > forms = typeModel . getForms ( ) ; if ( forms . isEmpty ( ) ) { return ; } for ( Form form : forms ) { if ( meetsConstraint ( dsInfo . getMimeType ( ) , form . getMimeType ( ) ) && meetsConstraint ( dsInfo . getFormatUri ( ) , form . getFormatUri ( ) ) ) { return ; } } result . addNote ( ValidationResultNotation . datastreamDoesNotMatchForms ( contentModelPid , id ) ) ; }
The object must have a datastream to match each dsTypeModel in the content model . Matching a dsTypeModel means equal IDs and an acceptable form .
4,552
private boolean meetsConstraint ( String value , String constraint ) { return ( constraint == null ) || constraint . equals ( value ) ; }
If the constraint is not null the value must match it .
4,553
private static File createTempFile ( File baseFile ) { File parentDirectory = baseFile . getParentFile ( ) ; String filename = baseFile . getName ( ) ; return new File ( parentDirectory , '_' + filename ) ; }
Create a temporary File object . Prefix the name of the base file with an underscore .
4,554
public void doGet ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { String api = request . getParameter ( "api" ) ; if ( api == null || api . length ( ) == 0 ) { response . setContentType ( "text/html; charset=UTF-8" ) ; getIndex ( response . getWriter ( ) ) ; } else { response . setContentType ( "text/xml; charset=UTF-8" ) ; getWSDL ( api . toUpperCase ( ) , request . getRequestURL ( ) . toString ( ) , response . getWriter ( ) ) ; } response . flushBuffer ( ) ; }
Respond to an HTTP GET request . The single parameter api indicates which WSDL file to provide . If no parameters are given a simple HTML index is given instead .
4,555
private void getIndex ( PrintWriter out ) { out . append ( "<html><body>WSDL Index<ul>\n" ) ; Iterator < String > names = _WSDL_PATHS . keySet ( ) . iterator ( ) ; while ( names . hasNext ( ) ) { String name = names . next ( ) ; out . append ( "<li> <a href=\"?api=" + name + "\">" + name + "</a></li>\n" ) ; } out . append ( "</ul></body></html>" ) ; }
Get a simple HTML index pointing to each WSDL file provided by the servlet .
4,556
private void getWSDL ( String api , String requestURL , PrintWriter out ) throws IOException , ServletException { String wsdlPath = ( String ) _WSDL_PATHS . get ( api ) ; if ( wsdlPath != null ) { File schemaFile = new File ( _serverDir , _XSD_PATH ) ; File sourceWSDL = new File ( _serverDir , wsdlPath ) ; String baseURL = getFedoraBaseURL ( requestURL ) ; String svcPath = ( String ) _SERVICE_PATHS . get ( api ) ; RuntimeWSDL wsdl = new RuntimeWSDL ( schemaFile , sourceWSDL , baseURL + "/" + svcPath ) ; wsdl . serialize ( out ) ; } else { throw new ServletException ( "No such api: '" + api + "'" ) ; } }
Get the self - contained WSDL given the api name and request URL .
4,557
private String getFedoraBaseURL ( String requestURL ) throws ServletException { int i = requestURL . lastIndexOf ( _SERVLET_PATH ) ; if ( i != - 1 ) { return requestURL . substring ( 0 , i ) ; } else { throw new ServletException ( "Unable to determine Fedora baseURL " + "from request URL. Request URL does not contain the " + "string '" + _SERVLET_PATH + "', as expected." ) ; } }
Determine the base URL of the Fedora webapp given the request URL to this servlet .
4,558
public void init ( ) throws ServletException { String fedoraHome = Constants . FEDORA_HOME ; if ( fedoraHome == null || fedoraHome . length ( ) == 0 ) { throw new ServletException ( "FEDORA_HOME is not defined" ) ; } else { _serverDir = new File ( new File ( fedoraHome ) , "server" ) ; if ( ! _serverDir . isDirectory ( ) ) { throw new ServletException ( "No such directory: " + _serverDir . getPath ( ) ) ; } } }
Initialize by setting serverDir based on FEDORA_HOME .
4,559
static Node parseInput ( InputStream input , String rootTag ) throws ParsingException { NodeList nodes = null ; try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setIgnoringComments ( true ) ; DocumentBuilder builder = null ; factory . setNamespaceAware ( true ) ; if ( ipReference == null ) { factory . setValidating ( false ) ; builder = factory . newDocumentBuilder ( ) ; } else { factory . setValidating ( true ) ; factory . setAttribute ( JAXP_SCHEMA_LANGUAGE , W3C_XML_SCHEMA ) ; factory . setAttribute ( JAXP_SCHEMA_SOURCE , ipReference . schemaFile ) ; builder = factory . newDocumentBuilder ( ) ; builder . setErrorHandler ( ipReference ) ; } Document doc = builder . parse ( input ) ; nodes = doc . getElementsByTagName ( rootTag ) ; } catch ( Exception e ) { throw new ParsingException ( "Error tring to parse " + rootTag + "Type" , e ) ; } if ( nodes . getLength ( ) != 1 ) throw new ParsingException ( "Only one " + rootTag + "Type allowed " + "at the root of a Context doc" ) ; return nodes . item ( 0 ) ; }
Tries to Parse the given output as a Context document .
4,560
private MethodParmDef [ ] getParms ( MethodDef [ ] methods , String methodName ) throws MethodNotFoundException , ServerException { for ( MethodDef element : methods ) { if ( element . methodName . equalsIgnoreCase ( methodName ) ) { return element . methodParms ; } } throw new MethodNotFoundException ( "[getParms] The service deployment object, " + m_obj . getPid ( ) + ", does not have a service method named '" + methodName ) ; }
Get the parms out of a particular service method definition .
4,561
public ServerConfiguration copy ( ) throws IOException { ReadableByteArrayOutputStream out = new ReadableByteArrayOutputStream ( ) ; serialize ( out ) ; return new ServerConfigurationParser ( out . toInputStream ( ) ) . parse ( ) ; }
Make an exact copy of this ServerConfiguration .
4,562
public void applyProperties ( Properties props ) { Iterator < ? > iter = props . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String fullName = ( String ) iter . next ( ) ; String value = props . getProperty ( fullName ) . trim ( ) ; if ( fullName . indexOf ( ":" ) != - 1 && value != null && value . length ( ) > 0 ) { String name = fullName . substring ( fullName . lastIndexOf ( ":" ) + 1 ) ; if ( fullName . startsWith ( "server:" ) ) { if ( name . endsWith ( ".class" ) ) { m_className = value ; } else { setParameterValue ( name , value , true ) ; } } else if ( fullName . startsWith ( "module." ) ) { String role = fullName . substring ( 7 , fullName . lastIndexOf ( ":" ) ) ; ModuleConfiguration module = getModuleConfiguration ( role ) ; if ( module == null ) { module = new ModuleConfiguration ( new ArrayList < Parameter > ( ) , role , null , null ) ; m_moduleConfigurations . add ( module ) ; } if ( name . endsWith ( ".class" ) ) { module . setClassName ( value ) ; } else { module . setParameterValue ( name , value , true ) ; } } else if ( fullName . startsWith ( "datastore." ) ) { String id = fullName . substring ( 10 , fullName . lastIndexOf ( ":" ) ) ; DatastoreConfiguration datastore = getDatastoreConfiguration ( id ) ; if ( datastore == null ) { datastore = new DatastoreConfiguration ( new ArrayList < Parameter > ( ) , id , null ) ; m_datastoreConfigurations . add ( datastore ) ; } datastore . setParameterValue ( name , value , true ) ; } } } }
Apply the given properties to this ServerConfiguration . Trims leading and trailing spaces from the property values before applying them .
4,563
private static String strip ( String in ) { if ( in == null ) { return null ; } String out = in . trim ( ) ; if ( out . length ( ) == 0 ) { return null ; } else { return out ; } }
resulting string is empty in incoming string is null .
4,564
public static void main ( String [ ] args ) throws Exception { if ( args . length < 1 || args . length > 2 ) { throw new IOException ( "One or two arguments expected." ) ; } ServerConfiguration config = new ServerConfigurationParser ( new FileInputStream ( new File ( args [ 0 ] ) ) ) . parse ( ) ; if ( args . length == 2 ) { Properties props = new Properties ( ) ; props . load ( new FileInputStream ( new File ( args [ 1 ] ) ) ) ; config . applyProperties ( props ) ; } ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; config . serialize ( out ) ; String content = new String ( out . toByteArray ( ) , "UTF-8" ) ; System . out . println ( content ) ; }
Deserialize then output the given configuration . If two parameters are given the first one is the filename and the second is the properties file to apply before re - serializing .
4,565
protected StreamSource resolveRepositoryURI ( String path ) throws TransformerException { StreamSource resolvedSource = null ; try { if ( path != null ) { URL url = new URL ( path ) ; InputStream in = url . openStream ( ) ; if ( in != null ) { resolvedSource = new StreamSource ( in ) ; } } else { throw new TransformerException ( "Resource does not exist. \"" + path + "\" is not accessible." ) ; } } catch ( MalformedURLException mfue ) { throw new TransformerException ( "Error accessing resource using servlet context: " + path , mfue ) ; } catch ( IOException ioe ) { throw new TransformerException ( "Unable to access resource at: " + path , ioe ) ; } return resolvedSource ; }
Resolves the repository URI .
4,566
public Writer open ( ) throws IOException { switch ( state ) { case OPEN : throw new IllegalStateException ( "File " + tempFile + " is already open." ) ; case CLOSED : throw new IllegalStateException ( "File " + tempFile + " has been closed already." ) ; default : state = State . OPEN ; tempFile . createNewFile ( ) ; fileWriter = new FileWriter ( tempFile ) ; return fileWriter ; } }
Create the file with its in progress filename .
4,567
public void close ( ) throws IOException { switch ( state ) { case READY : throw new IllegalStateException ( "File " + tempFile + " hasn't been opened yet." ) ; case CLOSED : throw new IllegalStateException ( "File " + tempFile + " has been closed already." ) ; default : fileWriter . close ( ) ; tempFile . renameTo ( file ) ; state = State . CLOSED ; } }
Close the writer and rename the file .
4,568
public BackendSecuritySpec parseBeSecurity ( ) throws BackendSecurityParserException { try { BackendSecurityDeserializer bsd = new BackendSecurityDeserializer ( m_encoding , m_validate ) ; return bsd . deserialize ( m_beSecurityPath ) ; } catch ( Throwable th ) { throw new BackendSecurityParserException ( "[DefaultBackendSecurity] " + "An error has occured in parsing the backend security " + "configuration file located at \"" + m_beSecurityPath + "\". " + "The underlying error was a " + th . getClass ( ) . getName ( ) + "The message was \"" + th . getMessage ( ) + "\"." ) ; } }
Parses the beSecurity configuration file .
4,569
public void setExtProperty ( String propName , String propValue ) { if ( m_extProperties == null ) { m_extProperties = new HashMap < String , String > ( ) ; } m_extProperties . put ( propName , propValue ) ; }
Sets an extended property on the object .
4,570
public String getExtProperty ( String propName ) { if ( m_extProperties == null ) { return null ; } return m_extProperties . get ( propName ) ; }
Gets an extended property value given the property name .
4,571
public boolean hasRelationship ( PredicateNode predicate , ObjectNode object ) { return hasRelationship ( PID . toURIReference ( m_pid ) , predicate , object ) ; }
assumes m_pid as subject ; ie RELS - EXT only
4,572
public Set < RelationshipTuple > getRelationships ( PredicateNode predicate , ObjectNode object ) { return getRelationships ( PID . toURIReference ( m_pid ) , predicate , object ) ; }
assume m_pid as subject ; ie RELS - EXT only
4,573
private Set < RelationshipTuple > getRels ( String relsDatastreamName ) { List < Datastream > relsDatastreamVersions = m_datastreams . get ( relsDatastreamName ) ; if ( relsDatastreamVersions == null || relsDatastreamVersions . size ( ) == 0 ) { return new HashSet < RelationshipTuple > ( ) ; } Datastream latestRels = relsDatastreamVersions . get ( 0 ) ; for ( Datastream v : relsDatastreamVersions ) { if ( v . DSCreateDT == null ) { latestRels = v ; break ; } if ( v . DSCreateDT . getTime ( ) > latestRels . DSCreateDT . getTime ( ) ) { latestRels = v ; } } try { return RDFRelationshipReader . readRelationships ( latestRels ) ; } catch ( ServerException e ) { throw new RuntimeException ( "Error reading object relationships in " + relsDatastreamName , e ) ; } }
Given a relationships datastream name return the relationships contained in that datastream
4,574
public boolean isHostProxyable ( String host ) { return getProxyHost ( ) != null && getProxyPort ( ) > 0 && ( nonProxyPattern == null || ! nonProxyPattern . matcher ( host ) . matches ( ) ) ; }
Checks whether a proxy has been configured and the given host is not in the nonProxyHost list or the nonProxyList is empty .
4,575
public static String fileExtensionForMIMEType ( String mimeType ) { loadMappings ( ) ; String ext = mimeTypeToExtensionMap . get ( mimeType ) ; if ( ext == null ) ext = "dat" ; return ext ; }
Get an appropriate extension for a MIME type .
4,576
private static HashMap < String , String > loadMappings ( ) { HashMap < String , String > mimeTypeToExtensionMap = new HashMap < String , String > ( ) ; String fileSep = System . getProperty ( "file.separator" ) ; StringBuffer buf = new StringBuffer ( ) ; buf . append ( System . getProperty ( "user.home" ) ) ; buf . append ( fileSep ) ; buf . append ( ".mime.types" ) ; loadMIMETypesFile ( buf . toString ( ) ) ; String pathSep = System . getProperty ( "path.separator" ) ; String [ ] pathComponents = pathSep . split ( " " ) ; int i ; for ( i = 0 ; i < pathComponents . length ; i ++ ) { buf . setLength ( 0 ) ; buf . append ( pathComponents [ i ] ) ; buf . append ( fileSep ) ; buf . append ( "mime.types" ) ; loadMIMETypesFile ( buf . toString ( ) ) ; } ResourceBundle bundle = ResourceBundle . getBundle ( MIME_MAPPINGS_BUNDLE ) ; for ( Enumeration < ? > e = bundle . getKeys ( ) ; e . hasMoreElements ( ) ; ) { String type = ( String ) e . nextElement ( ) ; try { String [ ] extensions = bundle . getString ( type ) . split ( " " ) ; if ( mimeTypeToExtensionMap . get ( type ) == null ) { logger . debug ( "Internal: " + type + " -> \"" + extensions [ 0 ] + "\"" ) ; mimeTypeToExtensionMap . put ( type , extensions [ 0 ] ) ; } } catch ( MissingResourceException ex ) { logger . error ( "While reading internal bundle \"" + MIME_MAPPINGS_BUNDLE + "\", got unexpected error on key \"" + type + "\"" , ex ) ; } } return mimeTypeToExtensionMap ; }
Load the MIME type mappings into memory .
4,577
private static void loadMIMETypesFile ( String path ) { try { File f = new File ( path ) ; logger . debug ( "Attempting to load MIME types file \"" + path + "\"" ) ; if ( ! ( f . exists ( ) && f . isFile ( ) ) ) logger . debug ( "Regular file \"" + path + "\" does not exist." ) ; else { LineNumberReader r = new LineNumberReader ( new FileReader ( f ) ) ; String line ; while ( ( line = r . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( ( line . length ( ) == 0 ) || ( line . startsWith ( "#" ) ) ) continue ; String [ ] fields = line . split ( " " ) ; if ( fields . length < 2 ) continue ; List < String > extensions = new ArrayList < String > ( ) ; for ( int i = 1 ; i < fields . length ; i ++ ) { if ( fields [ i ] . indexOf ( '=' ) != - 1 ) continue ; if ( fields [ i ] . indexOf ( '"' ) != - 1 ) continue ; if ( fields [ i ] . startsWith ( "." ) ) { if ( fields [ i ] . length ( ) == 1 ) continue ; fields [ i ] = fields [ i ] . substring ( 1 ) ; } extensions . add ( fields [ i ] ) ; } if ( extensions . size ( ) == 0 ) continue ; String mimeType = fields [ 0 ] ; String extension ; if ( mimeType . indexOf ( '/' ) == - 1 ) continue ; if ( mimeTypeToExtensionMap . get ( mimeType ) == null ) { extension = extensions . get ( 0 ) ; logger . debug ( "File \"" + path + "\": " + mimeType + " -> \"" + extension + "\"" ) ; mimeTypeToExtensionMap . put ( mimeType , extension ) ; } } r . close ( ) ; } } catch ( IOException ex ) { logger . debug ( "Error reading \"" + path + "\"" , ex ) ; } }
Attempt to load a MIME types file . Throws no exceptions .
4,578
public static String figureIndexedHash ( String repositoryHash , long entryIndex ) { return String . valueOf ( ( entryIndex + repositoryHash ) . hashCode ( ) ) ; }
The writer and the receiver each use this method to figure the hash on each journal entry . If the receiver calculates a different hash from the one that appears on the entry it will throw an exception .
4,579
public String ingest ( Context context , InputStream serialization , String logMessage , String format , String encoding , String pid ) throws ServerException { try { CreatorJournalEntry cje = new CreatorJournalEntry ( METHOD_INGEST , context ) ; cje . addArgument ( ARGUMENT_NAME_SERIALIZATION , serialization ) ; cje . addArgument ( ARGUMENT_NAME_LOG_MESSAGE , logMessage ) ; cje . addArgument ( ARGUMENT_NAME_FORMAT , format ) ; cje . addArgument ( ARGUMENT_NAME_ENCODING , encoding ) ; cje . addArgument ( ARGUMENT_NAME_NEW_PID , pid ) ; return ( String ) cje . invokeAndClose ( delegate , writer ) ; } catch ( JournalException e ) { throw new GeneralException ( "Problem creating the Journal" , e ) ; } }
Let the delegate do it and then write a journal entry .
4,580
private URIReference addCommonTriples ( DOReader reader , Set < Triple > set ) throws ResourceIndexException { try { URIReference objURI = new SimpleURIReference ( new URI ( PID . toURI ( reader . GetObjectPID ( ) ) ) ) ; addCoreObjectTriples ( reader , objURI , set ) ; Datastream [ ] datastreams = reader . GetDatastreams ( null , null ) ; for ( Datastream ds : datastreams ) { addCoreDatastreamTriples ( ds , objURI , set ) ; if ( ds . DatastreamID . equals ( "DC" ) ) { addDCTriples ( ds , objURI , set ) ; } } addRelationshipTriples ( reader , objURI , set ) ; return objURI ; } catch ( ResourceIndexException e ) { throw e ; } catch ( Exception e ) { throw new ResourceIndexException ( "Error generating triples" , e ) ; } }
Add the common core and datastream triples for the given object .
4,581
private void addDCTriples ( Datastream ds , URIReference objURI , Set < Triple > set ) throws Exception { DCFields dc = new DCFields ( ds . getContentStream ( ) ) ; Map < RDFName , List < DCField > > map = dc . getMap ( ) ; for ( RDFName predicate : map . keySet ( ) ) { for ( DCField dcField : map . get ( predicate ) ) { String lang = dcField . getLang ( ) ; if ( lang == null ) { add ( objURI , predicate , dcField . getValue ( ) , set ) ; } else { add ( objURI , predicate , dcField . getValue ( ) , lang , set ) ; } } } }
Add a statement about the object for each predicate value pair expressed in the DC datastream .
4,582
public void doFilter ( ServletRequest request , ServletResponse response , FilterChain filterChain ) throws IOException , ServletException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Entering FilterRestApiFlash.doThisSubclass()" ) ; } HttpServletRequest httpRequest = ( HttpServletRequest ) request ; HttpServletResponse httpResponse = ( HttpServletResponse ) response ; String queryString = httpRequest . getQueryString ( ) ; if ( queryString != null && queryString . contains ( "flash=true" ) ) { StatusHttpServletResponseWrapper sHttpResponse = new StatusHttpServletResponseWrapper ( httpResponse ) ; filterChain . doFilter ( request , sHttpResponse ) ; if ( sHttpResponse . status != sHttpResponse . realStatus ) { try { ServletOutputStream out = sHttpResponse . getOutputStream ( ) ; out . print ( "::ERROR(" + sHttpResponse . realStatus + ")" ) ; } catch ( IllegalStateException ise ) { PrintWriter out = sHttpResponse . getWriter ( ) ; out . print ( "::ERROR(" + sHttpResponse . realStatus + ")" ) ; } } } else { filterChain . doFilter ( request , response ) ; } }
Perform flash client response filtering
4,583
public void copy ( Datastream target ) { target . isNew = isNew ; target . DatastreamID = DatastreamID ; if ( DatastreamAltIDs != null ) { target . DatastreamAltIDs = new String [ DatastreamAltIDs . length ] ; for ( int i = 0 ; i < DatastreamAltIDs . length ; i ++ ) { target . DatastreamAltIDs [ i ] = DatastreamAltIDs [ i ] ; } } target . DSFormatURI = DSFormatURI ; target . DSMIME = DSMIME ; target . DSControlGrp = DSControlGrp ; target . DSInfoType = DSInfoType ; target . DSState = DSState ; target . DSVersionable = DSVersionable ; target . DSVersionID = DSVersionID ; target . DSLabel = DSLabel ; target . DSCreateDT = DSCreateDT ; target . DSSize = DSSize ; target . DSLocation = DSLocation ; target . DSLocationType = DSLocationType ; target . DSChecksumType = DSChecksumType ; target . DSChecksum = DSChecksum ; }
Copy this instance into target
4,584
public void println ( String str ) { super . println ( str ) ; if ( Administrator . WATCH_AREA != null ) { String buf = m_out . toString ( ) ; m_out . reset ( ) ; Administrator . WATCH_AREA . append ( buf ) ; } }
Every time this is called the buffer is cleared an output is sent to the JTextArea .
4,585
private void setNumeric ( PreparedStatement stmt , int varIndex , String columnName , String value ) throws SQLException { try { stmt . setInt ( varIndex , Integer . parseInt ( value ) ) ; } catch ( NumberFormatException e ) { try { stmt . setLong ( varIndex , Long . parseLong ( value ) ) ; } catch ( NumberFormatException e2 ) { throw new SQLException ( "Value specified for " + columnName + ", '" + value + "' was" + " specified as numeric, but is not" ) ; } } }
Sets a numeric value in the prepared statement . Parsing the string is attempted as an int then a long and if that fails a SQLException is thrown .
4,586
private String getSelector ( String [ ] columns , String [ ] values , String uniqueColumn ) throws SQLException { String selector = null ; for ( int i = 0 ; i < columns . length ; i ++ ) { if ( columns [ i ] . equals ( uniqueColumn ) ) { selector = values [ i ] ; } } if ( selector != null ) { return selector ; } else { throw new SQLException ( "Unique column does not exist in given " + "column array" ) ; } }
Gets the value in the given array whose associated column name matches the given uniqueColumn name .
4,587
public static boolean pingServer ( String protocol , String user , String pass ) { try { getServerResponse ( protocol , user , pass , "/describe" ) ; return true ; } catch ( Exception e ) { logger . debug ( "Assuming the server isn't running because " + "describe request failed" , e ) ; return false ; } }
Tell whether the server is running by pinging it as a client .
4,588
public static void reloadPolicies ( String protocol , String user , String pass ) throws IOException { getServerResponse ( protocol , user , pass , "/management/control?action=reloadPolicies" ) ; }
Signals for the server to reload its policies .
4,589
public static boolean isURLFedoraServer ( String url ) { URI uri = URI . create ( url ) ; String scheme = uri . getScheme ( ) ; if ( ! scheme . equals ( "http" ) && ! scheme . equals ( "https" ) ) { return false ; } String fHost = CONFIG . getParameter ( FEDORA_SERVER_HOST , Parameter . class ) . getValue ( ) ; String host = uri . getHost ( ) ; if ( ! host . equals ( fHost ) && ! host . equals ( "localhost" ) ) { return false ; } String path = uri . getPath ( ) ; String fedoraContext = CONFIG . getParameter ( FEDORA_SERVER_CONTEXT , Parameter . class ) . getValue ( ) ; if ( ! path . startsWith ( "/" + fedoraContext + "/" ) ) { return false ; } String httpPort = CONFIG . getParameter ( FEDORA_SERVER_PORT , Parameter . class ) . getValue ( ) ; String httpsPort = CONFIG . getParameter ( FEDORA_REDIRECT_PORT , Parameter . class ) . getValue ( ) ; if ( uri . getPort ( ) == - 1 ) { if ( scheme . equals ( "http" ) ) { return httpPort . equals ( "80" ) ; } else { return httpsPort . equals ( "443" ) ; } } else { String port = "" + uri . getPort ( ) ; if ( scheme . equals ( "http" ) ) { return port . equals ( httpPort ) ; } else { return port . equals ( httpsPort ) ; } } }
Tell whether the given URL appears to be referring to somewhere within the Fedora webapp .
4,590
private static boolean getArgBoolean ( String [ ] args , int position , boolean defaultValue ) { if ( args . length > position ) { String lowerArg = args [ position ] . toLowerCase ( ) ; if ( lowerArg . equals ( "true" ) || lowerArg . equals ( "yes" ) ) { return true ; } else if ( lowerArg . equals ( "false" ) || lowerArg . equals ( "no" ) ) { return false ; } else { throw new IllegalArgumentException ( args [ position ] + " not a valid value. Specify true or false" ) ; } } else { return defaultValue ; } }
Get boolean argument from list of arguments at position ; use defaultValue if not present
4,591
public void setHTTPPort ( ) throws InstallationFailedException { Element httpConnector = ( Element ) getDocument ( ) . selectSingleNode ( HTTP_CONNECTOR_XPATH ) ; if ( httpConnector == null ) { throw new InstallationFailedException ( "Unable to set server.xml HTTP Port. XPath for Connector element failed." ) ; } httpConnector . addAttribute ( "port" , options . getValue ( InstallOptions . TOMCAT_HTTP_PORT ) ) ; httpConnector . addAttribute ( "enableLookups" , "true" ) ; httpConnector . addAttribute ( "acceptCount" , "100" ) ; httpConnector . addAttribute ( "maxThreads" , "150" ) ; httpConnector . addAttribute ( "minSpareThreads" , "25" ) ; httpConnector . addAttribute ( "maxSpareThreads" , "75" ) ; }
Sets the http port and Fedora default http connector options .
4,592
private void fillNextLine ( ) { try { while ( nextLine == null && ! eof ) { String line = reader . readLine ( ) ; if ( line == null ) { eof = true ; reader . close ( ) ; } else if ( isBlank ( line ) ) { continue ; } else if ( isComment ( line ) ) { continue ; } else { nextLine = line ; } } } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }
Scan through the file until we get an EOF or a good line .
4,593
public String getLemma ( ) { StringBuilder builder = new StringBuilder ( ) ; int i = 0 ; for ( TermWord tw : this . term . getWords ( ) ) { if ( i > 0 ) builder . append ( TermSuiteConstants . WHITESPACE ) ; builder . append ( tw . getWord ( ) . getLemma ( ) ) ; i ++ ; } return builder . toString ( ) ; }
Returns the concatenation of inner words lemmas .
4,594
public static AEADBlockCipher getNewCipher ( Mode blockMode ) { AESEngine aesEngine = new AESEngine ( ) ; switch ( blockMode ) { case GCM : return new GCMBlockCipher ( aesEngine ) ; default : throw new RuntimeException ( "Block cipher not found" ) ; } }
Retrieve a new instance of the block mode provided
4,595
public byte [ ] encrypt ( final byte [ ] iv , final byte [ ] message ) throws RuntimeException { AEADParameters aeadParams = new AEADParameters ( new KeyParameter ( key ) , TAG_LENGTH , iv , authData ) ; cipher . init ( true , aeadParams ) ; byte [ ] cipherText = newBuffer ( cipher . getOutputSize ( message . length ) ) ; int outputOffset = cipher . processBytes ( message , 0 , message . length , cipherText , 0 ) ; try { cipher . doFinal ( cipherText , outputOffset ) ; } catch ( InvalidCipherTextException e ) { throw new RuntimeException ( "Error: " , e ) ; } return cipherText ; }
Given the iv encrypt the provided data
4,596
public byte [ ] encrypt ( String iv , String message , Encoder encoder ) { return encrypt ( encoder . decode ( iv ) , encoder . decode ( message ) ) ; }
Given the iv encrypt and encode the provided data
4,597
public void addToMap ( Map < String , String > properties , Map < String , List < Float > > rawHistogramData ) { for ( Entry < String , String > entrySet : properties . entrySet ( ) ) { String key = entrySet . getKey ( ) ; String value = entrySet . getValue ( ) ; try { Float floatValue = Float . parseFloat ( value ) ; if ( floatValue > - 900.0f ) { List < Float > rawDataForSingleProperty = rawHistogramData . get ( key ) ; if ( rawDataForSingleProperty == null ) { rawDataForSingleProperty = new ArrayList < Float > ( ) ; } rawDataForSingleProperty . add ( floatValue ) ; rawHistogramData . put ( key , rawDataForSingleProperty ) ; } } catch ( NumberFormatException e ) { } } }
Overriding this to weed out the - 999 . 0 values in the dataset
4,598
public void append ( String firstVal , String ... otherVals ) throws IOException { output . append ( firstVal ) ; for ( String v : otherVals ) output . append ( valSep ) . append ( v ) ; output . append ( lineSep ) ; }
Appends a line to the writer . The values are separated using the current separator an line separator is appended at the end .
4,599
public static byte [ ] checkLength ( byte [ ] data , int size ) { if ( data == null ) { throw new IllegalArgumentException ( "Data to check the length of are null." ) ; } if ( data . length < size ) { throw new IllegalArgumentException ( "Invalid length: " + data . length ) ; } return data ; }
Validate the length of the data provided