idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
4,200
public void logHeaderInfo ( Map < String , String > parameters ) { StringBuffer buffer = new StringBuffer ( "Recovery parameters:" ) ; for ( Iterator < String > keys = parameters . keySet ( ) . iterator ( ) ; keys . hasNext ( ) ; ) { Object key = keys . next ( ) ; Object value = parameters . get ( key ) ; buffer . append ( "\n " ) . append ( key ) . append ( "=" ) . append ( value ) ; } log ( buffer . toString ( ) ) ; }
Concrete sub - classes should call this method from their constructor or as soon as the log is ready for writing .
4,201
public void log ( ConsumerJournalEntry journalEntry ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "Event: method='" ) . append ( journalEntry . getMethodName ( ) ) . append ( "', " ) . append ( journalEntry . getIdentifier ( ) ) . append ( "\n" ) ; if ( logLevel == LEVEL_HIGH ) { JournalEntryContext context = journalEntry . getContext ( ) ; buffer . append ( " context=" ) . append ( context . getClass ( ) . getName ( ) ) . append ( "\n" ) ; buffer . append ( writeMapValues ( "environmentAttributes" , context . getEnvironmentAttributes ( ) ) ) ; buffer . append ( writeMapValues ( "subjectAttributes" , context . getSubjectAttributes ( ) ) ) ; buffer . append ( writeMapValues ( "actionAttributes" , context . getActionAttributes ( ) ) ) ; buffer . append ( writeMapValues ( "resourceAttributes" , context . getResourceAttributes ( ) ) ) ; buffer . append ( writeMapValues ( "recoveryAttributes" , context . getRecoveryAttributes ( ) ) ) ; buffer . append ( " password='*********'\n" ) ; buffer . append ( " noOp=" ) . append ( context . getNoOp ( ) ) . append ( "\n" ) ; } if ( logLevel == LEVEL_HIGH || logLevel == LEVEL_MEDIUM ) { buffer . append ( " now=" + journalEntry . getContext ( ) . getNoOp ( ) + "\n" ) ; buffer . append ( " arguments\n" ) ; Map < String , Object > argumentsMap = journalEntry . getArgumentsMap ( ) ; for ( Iterator < String > names = argumentsMap . keySet ( ) . iterator ( ) ; names . hasNext ( ) ; ) { String name = names . next ( ) ; Object value = argumentsMap . get ( name ) ; if ( value instanceof String [ ] ) { buffer . append ( writeStringArray ( name , ( String [ ] ) value ) ) ; } else { buffer . append ( " " + name + "='" + value + "'\n" ) ; } } } log ( buffer . toString ( ) ) ; }
Format a journal entry for writing to the logger . Take logging level into account .
4,202
protected void log ( String message , Writer writer ) { try { writer . write ( JournalHelper . formatDate ( new Date ( ) ) + ": " + message + "\n" ) ; } catch ( IOException e ) { logger . error ( "Error writing journal log entry" , e ) ; } }
Concrete sub - classes call this method to perform the final formatting if a log entry .
4,203
private static final String getExtension ( String MIMETYPE ) throws Exception { if ( m_extensionMappings == null ) { m_extensionMappings = readExtensionMappings ( Server . FEDORA_HOME + "/server/" + Server . CONFIG_DIR + "/" + DATASTREAM_MAPPING_SOURCE_FILE ) ; } String extension = m_extensionMappings . get ( MIMETYPE ) ; if ( extension != null ) { return extension ; } else { return "" ; } }
Get the file extension for a given MIMETYPE from the extensions mappings
4,204
private static synchronized final HashMap < String , String > readExtensionMappings ( String mappingFile ) throws Exception { HashMap < String , String > extensionMappings = new HashMap < String , String > ( ) ; DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; Document doc = factory . newDocumentBuilder ( ) . parse ( new File ( mappingFile ) ) ; Element root = doc . getDocumentElement ( ) ; NodeList mappingNodes = root . getChildNodes ( ) ; for ( int i = 0 ; i < mappingNodes . getLength ( ) ; i ++ ) { Node mappingNode = mappingNodes . item ( i ) ; if ( mappingNode . getNodeType ( ) == Node . ELEMENT_NODE && mappingNode . getNodeName ( ) . equals ( "mime-mapping" ) ) { String extension = null ; String mimeType = null ; NodeList nl = mappingNode . getChildNodes ( ) ; for ( int j = 0 ; j < nl . getLength ( ) ; j ++ ) { Node n = nl . item ( j ) ; if ( n . getNodeType ( ) == Node . ELEMENT_NODE ) { if ( n . getNodeName ( ) . equals ( "extension" ) ) { extension = n . getFirstChild ( ) . getNodeValue ( ) ; } else { if ( n . getNodeName ( ) . equals ( "mime-type" ) ) { mimeType = n . getFirstChild ( ) . getNodeValue ( ) ; } } } } if ( extension != null && mimeType != null ) { if ( ! extensionMappings . containsKey ( mimeType ) ) { extensionMappings . put ( mimeType , extension ) ; } else { logger . warn ( "Duplicate extension " + extension + " found for mime-type " + mimeType + " in " + mappingFile ) ; } } else { logger . warn ( "Element mime-mapping is missing child elements mime-type and/or extension in " + mappingFile ) ; } } } return extensionMappings ; }
Read the extensions mappings from config file
4,205
public final void addContentDispositionHeader ( Context context , String pid , String dsID , String download , Date asOfDateTime , MIMETypedStream stream ) throws Exception { String headerValue = null ; String filename = null ; if ( download != null && download . equals ( "true" ) ) { filename = getFilename ( context , pid , dsID , asOfDateTime , stream . getMIMEType ( ) ) ; headerValue = attachmentHeader ( filename ) ; } else { if ( m_datastreamContentDispositionInlineEnabled . equals ( "true" ) ) { filename = getFilename ( context , pid , dsID , asOfDateTime , stream . getMIMEType ( ) ) ; headerValue = inlineHeader ( filename ) ; } } Property [ ] header = { new Property ( "content-disposition" , headerValue ) } ; if ( stream . header != null ) { Property headers [ ] = new Property [ stream . header . length + 1 ] ; System . arraycopy ( stream . header , 0 , headers , 0 , stream . header . length ) ; headers [ headers . length - 1 ] = header [ 0 ] ; stream . header = headers ; } else { stream . header = header ; } }
Add a content disposition header to a MIMETypedStream based on configuration preferences . Header by default specifies inline ; if download = true then attachment is specified .
4,206
private final String getFilename ( Context context , String pid , String dsid , Date asOfDateTime , String MIMETYPE ) throws Exception { String filename = "" ; String extension = "" ; for ( String source : m_datastreamFilenameSource . split ( " " ) ) { if ( source . equals ( "rels" ) ) { filename = getFilenameFromRels ( context , pid , dsid , MIMETYPE ) ; if ( ! filename . isEmpty ( ) ) extension = getExtension ( filename , m_datastreamExtensionMappingRels , MIMETYPE ) ; } else { if ( source . equals ( "id" ) ) { filename = getFilenameFromId ( pid , dsid , MIMETYPE ) ; if ( ! filename . isEmpty ( ) ) extension = getExtension ( filename , m_datastreamExtensionMappingId , MIMETYPE ) ; } else { if ( source . equals ( "label" ) ) { filename = getFilenameFromLabel ( context , pid , dsid , asOfDateTime , MIMETYPE ) ; if ( ! filename . isEmpty ( ) ) extension = getExtension ( filename , m_datastreamExtensionMappingLabel , MIMETYPE ) ; } else { logger . warn ( "Unknown datastream filename source specified in datastreamFilenameSource in fedora.fcfg: " + source + ". Please specify zero or more of: rels id label" ) ; } } } if ( ! filename . isEmpty ( ) ) break ; } if ( filename . isEmpty ( ) ) { filename = m_datastreamDefaultFilename ; extension = getExtension ( m_datastreamDefaultFilename , m_datastreamExtensionMappingDefault , MIMETYPE ) ; } if ( extension . isEmpty ( ) ) { return ILLEGAL_FILENAME_REGEX . matcher ( filename ) . replaceAll ( "" ) ; } else { return ILLEGAL_FILENAME_REGEX . matcher ( filename + "." + extension ) . replaceAll ( "" ) ; } }
Generate a filename and extension for a datastream based on configuration preferences . Filename can be based on a definition in RELS - INT the datastream label or the datastream ID . These sources can be specified in order of preference together with using a default filename . The extension is based on a mime - type - to - extension mapping configuration file ; alternatively if the filename determined already includes an extension that can be specified instead .
4,207
private final String getFilenameFromRels ( Context context , String pid , String dsid , String MIMETYPE ) throws Exception { String filename = "" ; DOReader reader = m_doManager . getReader ( false , context , pid ) ; Datastream relsInt = reader . GetDatastream ( "RELS-INT" , null ) ; if ( relsInt == null ) return "" ; Set < RelationshipTuple > relsIntTuples = RDFRelationshipReader . readRelationships ( relsInt . getContentStream ( ) ) ; if ( relsIntTuples . size ( ) == 0 ) return "" ; int matchingTuples = 0 ; String dsSubject = Constants . FEDORA . uri + pid + "/" + dsid ; for ( RelationshipTuple tuple : relsIntTuples ) { if ( tuple . subject . equals ( dsSubject ) && tuple . predicate . equals ( FILENAME_REL ) ) { if ( matchingTuples == 0 ) { if ( tuple . isLiteral ) { filename = tuple . object ; } else { logger . warn ( "Object " + pid + " datastream " + dsid + " specifies a filename which is not a literal in RELS-INT" ) ; filename = "" ; } } matchingTuples ++ ; } } if ( matchingTuples > 1 ) { logger . warn ( "Object " + pid + " datastream " + dsid + " specifies more than one filename in RELS-INT." ) ; } return filename ; }
Get datastream filename as defined in RELS - INT
4,208
private final String getFilenameFromLabel ( Context context , String pid , String dsid , Date asOfDateTime , String MIMETYPE ) throws Exception { DOReader reader = m_doManager . getReader ( false , context , pid ) ; Datastream ds = reader . GetDatastream ( dsid , asOfDateTime ) ; return ( ds == null ) ? "" : ds . DSLabel ; }
Get filename based on datastream label
4,209
private static final String getFilenameFromId ( String pid , String dsid , String MIMETYPE ) throws Exception { return dsid ; }
Get filename from datastream id
4,210
public synchronized ServerStatusMessage [ ] getMessages ( ServerStatusMessage afterMessage ) throws Exception { boolean sawAfterMessage ; String afterMessageString = null ; if ( afterMessage == null ) { sawAfterMessage = true ; } else { sawAfterMessage = false ; afterMessageString = afterMessage . toString ( ) ; } FileInputStream in = null ; try { in = new FileInputStream ( _file ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; List < ServerStatusMessage > messages = new ArrayList < ServerStatusMessage > ( ) ; ServerStatusMessage message = getNextMessage ( reader ) ; while ( message != null ) { if ( ! sawAfterMessage ) { if ( message . toString ( ) . equals ( afterMessageString ) ) { sawAfterMessage = true ; } } else { messages . add ( message ) ; } message = getNextMessage ( reader ) ; } return messages . toArray ( STATUS_MSG_ARRAY_TYPE ) ; } catch ( IOException ioe ) { throw new Exception ( "Error opening server status file for reading: " + _file . getPath ( ) , ioe ) ; } finally { if ( in != null ) { try { in . close ( ) ; } catch ( Exception e ) { } } } }
Get all messages in the status file or only those after the given message if it is non - null . If the status file doesn t exist or can t be parsed throw an exception .
4,211
private ServerStatusMessage getNextMessage ( BufferedReader reader ) throws Exception { boolean messageStarted = false ; String line = reader . readLine ( ) ; while ( line != null && ! messageStarted ) { if ( line . equals ( BEGIN_LINE ) ) { messageStarted = true ; } else { line = reader . readLine ( ) ; } } if ( messageStarted ) { ServerState state = ServerState . fromString ( getNextLine ( reader ) ) ; Date time = ServerStatusMessage . stringToDate ( getNextLine ( reader ) ) ; String detail = null ; line = getNextLine ( reader ) ; if ( ! line . equals ( END_LINE ) ) { StringBuffer buf = new StringBuffer ( ) ; while ( ! line . equals ( END_LINE ) ) { buf . append ( line + "\n" ) ; line = getNextLine ( reader ) ; } detail = buf . toString ( ) ; } return new ServerStatusMessage ( state , time , detail ) ; } else { return null ; } }
return the next message or null if there are no more messages in the file
4,212
private String getNextLine ( BufferedReader reader ) throws Exception { String line = reader . readLine ( ) ; if ( line != null ) { return line ; } else { throw new Exception ( "Error parsing server status file (unexpectedly ended): " + _file . getPath ( ) ) ; } }
get the next line or throw an exception if eof was reached
4,213
private String makeHash ( String request ) throws CacheException { RequestCtx reqCtx = null ; try { reqCtx = m_contextUtil . makeRequestCtx ( request ) ; } catch ( MelcoeXacmlException pe ) { throw new CacheException ( "Error converting request" , pe ) ; } byte [ ] hash = null ; synchronized ( digest ) { digest . reset ( ) ; hashSubjectList ( reqCtx . getSubjectsAsList ( ) , digest ) ; hashAttributeList ( reqCtx . getResourceAsList ( ) , digest ) ; hashAttributeList ( reqCtx . getActionAsList ( ) , digest ) ; hashAttributeList ( reqCtx . getEnvironmentAttributesAsList ( ) , digest ) ; hash = digest . digest ( ) ; } return byte2hex ( hash ) ; }
Given a request this method generates a hash .
4,214
private static void hashAttribute ( Attribute a , MessageDigest dig ) { dig . update ( a . getId ( ) . toString ( ) . getBytes ( ) ) ; dig . update ( a . getType ( ) . toString ( ) . getBytes ( ) ) ; dig . update ( a . getValue ( ) . encode ( ) . getBytes ( ) ) ; if ( a . getIssuer ( ) != null ) { dig . update ( a . getIssuer ( ) . getBytes ( ) ) ; } if ( a . getIssueInstant ( ) != null ) { dig . update ( a . getIssueInstant ( ) . encode ( ) . getBytes ( ) ) ; } }
Utility function to add an attribute to the hash digest .
4,215
public void watchStartup ( int startingTimeout , int startupTimeout ) throws Exception { long startTime = System . currentTimeMillis ( ) ; ServerStatusMessage [ ] messages = getAllMessages ( ) ; ServerStatusMessage lastMessage = messages [ messages . length - 1 ] ; boolean starting = false ; boolean started = false ; while ( ! started ) { showStartup ( messages ) ; for ( ServerStatusMessage element : messages ) { ServerState state = element . getState ( ) ; if ( state == ServerState . STARTING ) { starting = true ; } else if ( state == ServerState . STARTED ) { started = true ; } else if ( state == ServerState . STARTUP_FAILED ) { throw new Exception ( "Fedora startup failed (see above)" ) ; } } if ( ! started ) { try { Thread . sleep ( 500 ) ; } catch ( Throwable th ) { } long now = System . currentTimeMillis ( ) ; if ( ! starting ) { if ( ( now - startTime ) / 1000 > startingTimeout ) { throw new Exception ( "Server startup did not begin within " + startingTimeout + " seconds" ) ; } } if ( ( now - startTime ) / 1000 > startupTimeout ) { throw new Exception ( "Server startup did not complete within " + startupTimeout + " seconds" ) ; } messages = _statusFile . getMessages ( lastMessage ) ; if ( messages . length > 0 ) { lastMessage = messages [ messages . length - 1 ] ; } } } }
Watch the status file and print details to standard output until the STARTED or STARTUP_FAILED state is encountered . If there are any problems reading the status file a timeout is reached or STARTUP_FAILED is encountered this will throw an exception .
4,216
public void watchShutdown ( int stoppingTimeout , int shutdownTimeout ) throws Exception { if ( ! _statusFile . exists ( ) ) { _statusFile . append ( ServerState . STOPPING , "WARNING: Server status file did not exist; re-created" ) ; } long startTime = System . currentTimeMillis ( ) ; ServerStatusMessage [ ] messages = getAllMessages ( ) ; ServerStatusMessage lastMessage = messages [ messages . length - 1 ] ; boolean stopping = false ; boolean stopped = false ; while ( ! stopped ) { showShutdown ( messages ) ; for ( ServerStatusMessage element : messages ) { ServerState state = element . getState ( ) ; if ( state == ServerState . STOPPING ) { stopping = true ; } else if ( state == ServerState . STOPPED ) { stopped = true ; } else if ( state == ServerState . STOPPED_WITH_ERR ) { throw new Exception ( "Fedora shutdown finished with error (see above)" ) ; } } if ( ! stopped ) { try { Thread . sleep ( 500 ) ; } catch ( Throwable th ) { } long now = System . currentTimeMillis ( ) ; if ( ! stopping ) { if ( ( now - startTime ) / 1000 > stoppingTimeout ) { throw new Exception ( "Server shutdown did not begin within " + stoppingTimeout + " seconds" ) ; } } if ( ( now - startTime ) / 1000 > shutdownTimeout ) { throw new Exception ( "Server shutdown did not complete within " + shutdownTimeout + " seconds" ) ; } messages = _statusFile . getMessages ( lastMessage ) ; if ( messages . length > 0 ) { lastMessage = messages [ messages . length - 1 ] ; } } } }
Watch the status file and print details to standard output until the STOPPED or STOPPED_WITH_ERR state is encountered . If there are any problems reading the status file a timeout is reached or STOPPED_WITH_ERR is encountered this will throw an exception .
4,217
public void showStatus ( ) throws Exception { ServerStatusMessage message ; if ( _statusFile . exists ( ) ) { ServerStatusMessage [ ] messages = getAllMessages ( ) ; message = messages [ messages . length - 1 ] ; } else { message = ServerStatusMessage . NEW_SERVER_MESSAGE ; } System . out . println ( message . toString ( ) ) ; }
Show a human - readable form of the latest message in the server status file . If the status file doesn t yet exist this will print a special status message indicating the server is new . The response will have the following form .
4,218
private ServerStatusMessage [ ] getAllMessages ( ) throws Exception { ServerStatusMessage [ ] messages = _statusFile . getMessages ( null ) ; if ( messages . length == 0 ) { System . out . println ( "WARNING: Server status file is empty; re-creating" ) ; init ( ) ; messages = _statusFile . getMessages ( null ) ; } ServerState firstState = messages [ 0 ] . getState ( ) ; if ( firstState != ServerState . NOT_STARTING ) { System . out . println ( "WARNING: Server status file is missing one or more messages" ) ; } return messages ; }
print a warning
4,219
public void cascadeFrames ( ) { restoreFrames ( ) ; int x = 0 ; int y = 0 ; JInternalFrame allFrames [ ] = getAllFrames ( ) ; manager . setNormalSize ( ) ; int frameHeight = getBounds ( ) . height - 5 - allFrames . length * FRAME_OFFSET ; int frameWidth = getBounds ( ) . width - 5 - allFrames . length * FRAME_OFFSET ; for ( int i = allFrames . length - 1 ; i >= 0 ; i -- ) { allFrames [ i ] . setSize ( frameWidth , frameHeight ) ; allFrames [ i ] . setLocation ( x , y ) ; x = x + FRAME_OFFSET ; y = y + FRAME_OFFSET ; } }
Cascade all internal frames un - iconfying any minimized first
4,220
public void tileFrames ( ) { restoreFrames ( ) ; java . awt . Component allFrames [ ] = getAllFrames ( ) ; manager . setNormalSize ( ) ; int frameHeight = getBounds ( ) . height / allFrames . length ; int y = 0 ; for ( Component element : allFrames ) { element . setSize ( getBounds ( ) . width , frameHeight ) ; element . setLocation ( 0 , y ) ; y = y + frameHeight ; } }
Tile all internal frames un - iconifying any minimized first
4,221
public JournalEntryContext readContext ( XMLEventReader reader ) throws JournalException , XMLStreamException { JournalEntryContext context = new JournalEntryContext ( ) ; XMLEvent event = reader . nextTag ( ) ; if ( ! isStartTagEvent ( event , QNAME_TAG_CONTEXT ) ) { throw getNotStartTagException ( QNAME_TAG_CONTEXT , event ) ; } context . setPassword ( readContextPassword ( reader ) ) ; context . setNoOp ( readContextNoOp ( reader ) ) ; context . setNow ( readContextNow ( reader ) ) ; context . setEnvironmentAttributes ( convertStringMap ( readMultiMap ( reader , CONTEXT_MAPNAME_ENVIRONMENT ) ) ) ; context . setSubjectAttributes ( readMultiMap ( reader , CONTEXT_MAPNAME_SUBJECT ) ) ; context . setActionAttributes ( convertStringMap ( readMultiMap ( reader , CONTEXT_MAPNAME_ACTION ) ) ) ; context . setResourceAttributes ( convertStringMap ( readMultiMap ( reader , CONTEXT_MAPNAME_RESOURCE ) ) ) ; context . setRecoveryAttributes ( convertStringMap ( readMultiMap ( reader , CONTEXT_MAPNAME_RECOVERY ) ) ) ; event = reader . nextTag ( ) ; if ( ! isEndTagEvent ( event , QNAME_TAG_CONTEXT ) ) { throw getNotEndTagException ( QNAME_TAG_CONTEXT , event ) ; } decipherPassword ( context ) ; return context ; }
Read the context tax and populate a JournalEntryContext object .
4,222
private boolean readContextNoOp ( XMLEventReader reader ) throws XMLStreamException , JournalException { readStartTag ( reader , QNAME_TAG_NOOP ) ; String value = readCharactersUntilEndTag ( reader , QNAME_TAG_NOOP ) ; return Boolean . valueOf ( value ) . booleanValue ( ) ; }
Read the context no - op flag from XML .
4,223
private Date readContextNow ( XMLEventReader reader ) throws XMLStreamException , JournalException { readStartTag ( reader , QNAME_TAG_NOW ) ; String value = readCharactersUntilEndTag ( reader , QNAME_TAG_NOW ) ; return JournalHelper . parseDate ( value ) ; }
Read the context date from XML .
4,224
private MultiValueMap < String > readMultiMap ( XMLEventReader reader , String mapName ) throws JournalException , XMLStreamException { MultiValueMap < String > map = new MultiValueMap < String > ( ) ; XMLEvent event = reader . nextTag ( ) ; if ( ! isStartTagEvent ( event , QNAME_TAG_MULTI_VALUE_MAP ) ) { throw getNotStartTagException ( QNAME_TAG_MULTI_VALUE_MAP , event ) ; } String value = getRequiredAttributeValue ( event . asStartElement ( ) , QNAME_ATTR_NAME ) ; if ( ! mapName . equals ( value ) ) { throw new JournalException ( "Expecting a '" + mapName + "' multi-map, but found a '" + value + "' multi-map instead" ) ; } readMultiMapKeys ( reader , map ) ; return map ; }
Read a multi - map with its nested tags .
4,225
private void readMultiMapKeys ( XMLEventReader reader , MultiValueMap < String > map ) throws XMLStreamException , JournalException { while ( true ) { XMLEvent event2 = reader . nextTag ( ) ; if ( isStartTagEvent ( event2 , QNAME_TAG_MULTI_VALUE_MAP_KEY ) ) { String key = getRequiredAttributeValue ( event2 . asStartElement ( ) , QNAME_ATTR_NAME ) ; String [ ] values = readMultiMapValuesForKey ( reader ) ; storeInMultiMap ( map , key , values ) ; } else if ( isEndTagEvent ( event2 , QNAME_TAG_MULTI_VALUE_MAP ) ) { break ; } else { throw getNotNextMemberOrEndOfGroupException ( QNAME_TAG_MULTI_VALUE_MAP , QNAME_TAG_MULTI_VALUE_MAP_KEY , event2 ) ; } } }
Read through the keys of the multi - map adding to the map as we go .
4,226
private String [ ] readMultiMapValuesForKey ( XMLEventReader reader ) throws XMLStreamException , JournalException { List < String > values = new ArrayList < String > ( ) ; while ( true ) { XMLEvent event = reader . nextTag ( ) ; if ( isStartTagEvent ( event , QNAME_TAG_MULTI_VALUE_MAP_VALUE ) ) { values . add ( readCharactersUntilEndTag ( reader , QNAME_TAG_MULTI_VALUE_MAP_VALUE ) ) ; } else if ( isEndTagEvent ( event , QNAME_TAG_MULTI_VALUE_MAP_KEY ) ) { return values . toArray ( new String [ values . size ( ) ] ) ; } else { throw getNotNextMemberOrEndOfGroupException ( QNAME_TAG_MULTI_VALUE_MAP_KEY , QNAME_TAG_MULTI_VALUE_MAP_VALUE , event ) ; } } }
Read the list of values for one key of the multi - map .
4,227
private void decipherPassword ( JournalEntryContext context ) { String key = JournalHelper . formatDate ( context . now ( ) ) ; String passwordCipher = context . getPassword ( ) ; String clearPassword = PasswordCipher . decipher ( key , passwordCipher , passwordType ) ; context . setPassword ( clearPassword ) ; }
The password as read was not correct . It needs to be deciphered .
4,228
public String [ ] getServiceDefinitions ( Context context , String PID , Date asOfDateTime ) throws ServerException { return da . getServiceDefinitions ( context , PID , asOfDateTime ) ; }
Get a list of service definition identifiers for dynamic disseminators associated with the digital object .
4,229
public ObjectMethodsDef [ ] listMethods ( Context context , String PID , Date asOfDateTime ) throws ServerException { return da . listMethods ( context , PID , asOfDateTime ) ; }
Get the definitions for all dynamic disseminations on the object .
4,230
public ObjectProfile getObjectProfile ( Context context , String PID , Date asOfDateTime ) throws ServerException { return null ; }
Get the profile information for the digital object . This contain key metadata and URLs for the Dissemination Index and Item Index of the object .
4,231
private static void safeOverwrite ( Blob origBlob , InputStream content ) { BlobStoreConnection connection = origBlob . getConnection ( ) ; String origId = origBlob . getId ( ) . toString ( ) ; Blob newBlob = null ; try { newBlob = connection . getBlob ( new URI ( origId + "/new" ) , null ) ; copy ( content , newBlob . openOutputStream ( - 1 , false ) ) ; } catch ( Throwable th ) { throw new FaultException ( th ) ; } Blob oldBlob = null ; try { oldBlob = rename ( origBlob , origId + "/old" ) ; } finally { if ( oldBlob == null ) { try { delete ( newBlob ) ; } catch ( Throwable th ) { logger . error ( "Failed to delete " + newBlob . getId ( ) + " while" + " recovering from rename failure during safe" + " overwrite" , th ) ; } } } boolean successful = false ; try { rename ( newBlob , origId ) ; successful = true ; } finally { if ( ! successful ) { try { rename ( oldBlob , origId ) ; } catch ( Throwable th ) { logger . error ( "Failed to rename " + oldBlob . getId ( ) + " to " + origId + " while recovering from rename" + " failure during safe overwrite" , th ) ; } try { newBlob . delete ( ) ; } catch ( Throwable th ) { logger . error ( "Failed to delete " + newBlob . getId ( ) + " while recovering from rename" + " failure during safe overwrite" , th ) ; } } } try { delete ( oldBlob ) ; } catch ( Throwable th ) { logger . error ( "Failed to delete " + oldBlob . getId ( ) + " while cleaning up after committed" + " safe overwrite" , th ) ; } }
Overwrites the content of the given blob in a way that guarantees the original content is not destroyed until the replacement is successfully put in its place .
4,232
private static String getToken ( URI blobId ) { String [ ] parts = blobId . getSchemeSpecificPart ( ) . split ( "/" ) ; if ( parts . length == 2 ) { return parts [ 1 ] ; } else if ( parts . length == 4 ) { return parts [ 1 ] + "+" + uriDecode ( parts [ 2 ] ) + "+" + uriDecode ( parts [ 3 ] ) ; } else { throw new IllegalArgumentException ( "Malformed token-as-blobId: " + blobId ) ; } }
Converts a token - as - blobId back to a token .
4,233
protected static byte [ ] nodeToByte ( Node node ) throws PolicyIndexException { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; Writer output = new OutputStreamWriter ( out , Charset . forName ( "UTF-8" ) ) ; try { SunXmlSerializers . writePrettyPrintWithDecl ( node , output ) ; output . close ( ) ; } catch ( IOException e ) { throw new PolicyIndexException ( "Failed to serialise node " + e . getMessage ( ) , e ) ; } return out . toByteArray ( ) ; }
get XML document supplied as w3c dom Node as bytes
4,234
protected static String [ ] sortDescending ( String [ ] s ) { Arrays . sort ( s , new Comparator < String > ( ) { public int compare ( String o1 , String o2 ) { if ( o1 . length ( ) < o2 . length ( ) ) return 1 ; if ( o1 . length ( ) > o2 . length ( ) ) return - 1 ; return 0 ; } } ) ; return s ; }
sorts a string array in descending order of length
4,235
protected Collection createCollectionPath ( String collectionPath , Collection rootCollection ) throws PolicyIndexException { try { if ( rootCollection . getParentCollection ( ) != null ) { throw new PolicyIndexException ( "Collection supplied is not a root collection" ) ; } String rootCollectionName = rootCollection . getName ( ) ; if ( ! collectionPath . startsWith ( rootCollectionName ) ) { throw new PolicyIndexException ( "Collection path " + collectionPath + " does not start from root collection - " + rootCollectionName ) ; } String pathToCreate = collectionPath . substring ( rootCollectionName . length ( ) ) ; String [ ] collections = pathToCreate . split ( "/" ) ; Collection nextCollection = rootCollection ; for ( String collectionName : collections ) { Collection childCollection = nextCollection . getChildCollection ( collectionName ) ; if ( childCollection != null ) { childCollection = nextCollection . getChildCollection ( collectionName ) ; } else { CollectionManagementService mgtService = ( CollectionManagementService ) nextCollection . getService ( "CollectionManagementService" , "1.0" ) ; childCollection = mgtService . createCollection ( collectionName ) ; log . debug ( "Created collection " + collectionName ) ; } if ( nextCollection . isOpen ( ) ) { nextCollection . close ( ) ; } nextCollection = childCollection ; } return nextCollection ; } catch ( XMLDBException e ) { log . error ( "Error creating collections from path " + e . getMessage ( ) , e ) ; throw new PolicyIndexException ( "Error creating collections from path " + e . getMessage ( ) , e ) ; } }
Create a collection given a full path to the collection . The collection path must include the root collection . Intermediate collections in the path are created if they do not already exist .
4,236
protected void deleteCollection ( ) throws PolicyIndexException { Collection rootCol ; try { rootCol = DatabaseManager . getCollection ( m_databaseURI + ROOT_COLLECTION_PATH , m_user , m_password ) ; CollectionManagementService mgtService = ( CollectionManagementService ) rootCol . getService ( "CollectionManagementService" , "1.0" ) ; mgtService . removeCollection ( m_collectionName ) ; log . debug ( "Policy collection deleted" ) ; } catch ( XMLDBException e ) { throw new PolicyIndexException ( "Error deleting collection " + e . getMessage ( ) , e ) ; } }
delete the policy collection from the database
4,237
protected static Document createDocument ( String document ) throws PolicyIndexException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; DocumentBuilder builder ; try { builder = factory . newDocumentBuilder ( ) ; Document doc = builder . parse ( new InputSource ( new StringReader ( document ) ) ) ; return doc ; } catch ( ParserConfigurationException e ) { throw new PolicyIndexException ( e ) ; } catch ( SAXException e ) { throw new PolicyIndexException ( e ) ; } catch ( IOException e ) { throw new PolicyIndexException ( e ) ; } }
create an XML Document from the policy document
4,238
private XMLEventWriter createXmlEventWriter ( StringWriter stringWriter ) throws FactoryConfigurationError , XMLStreamException { return new IndentingXMLEventWriter ( XMLOutputFactory . newInstance ( ) . createXMLEventWriter ( stringWriter ) ) ; }
Wrap an XMLEventWriter around that StringWriter .
4,239
public static File copyToTempFile ( InputStream serialization ) throws IOException , FileNotFoundException { File tempFile = createTempFile ( ) ; StreamUtility . pipeStream ( serialization , new FileOutputStream ( tempFile ) , 4096 ) ; return tempFile ; }
Copy an input stream to a temporary file so we can hand an input stream to the delegate and have another input stream for the journal .
4,240
public static String captureStackTrace ( Throwable e ) { StringWriter buffer = new StringWriter ( ) ; e . printStackTrace ( new PrintWriter ( buffer ) ) ; return buffer . toString ( ) ; }
Capture the full stack trace of an Exception and return it in a String .
4,241
public static Object createInstanceAccordingToParameter ( String parameterName , Class < ? > [ ] argClasses , Object [ ] args , Map < String , String > parameters ) throws JournalException { String className = parameters . get ( parameterName ) ; if ( className == null ) { throw new JournalException ( "No parameter '" + parameterName + "'" ) ; } return createInstanceFromClassname ( className , argClasses , args ) ; }
Look in the system parameters and create an instance of the named class .
4,242
public static Object createInstanceFromClassname ( String className , Class < ? > [ ] argClasses , Object [ ] args ) throws JournalException { try { Class < ? > clazz = Class . forName ( className ) ; Constructor < ? > constructor = clazz . getConstructor ( argClasses ) ; return constructor . newInstance ( args ) ; } catch ( Exception e ) { throw new JournalException ( e ) ; } }
Create an instance of the named class .
4,243
public static String formatDate ( Date date ) { SimpleDateFormat formatter = new SimpleDateFormat ( TIMESTAMP_FORMAT ) ; return formatter . format ( date ) ; }
Format a date for the journal or the logger .
4,244
public static Date parseDate ( String date ) throws JournalException { try { SimpleDateFormat parser = new SimpleDateFormat ( TIMESTAMP_FORMAT ) ; return parser . parse ( date ) ; } catch ( ParseException e ) { throw new JournalException ( e ) ; } }
Parse a date from the journal .
4,245
public static String createTimestampedFilename ( String filenamePrefix , Date date ) { SimpleDateFormat formatter = new SimpleDateFormat ( FORMAT_JOURNAL_FILENAME_TIMESTAMP ) ; formatter . setTimeZone ( TimeZone . getTimeZone ( "GMT" ) ) ; return filenamePrefix + formatter . format ( date ) + "Z" ; }
Create the name for a Journal file or a log file based on the prefix and the current date .
4,246
public static void validateURL ( String url , String controlGroup ) throws ValidationException { if ( ! ( controlGroup . equalsIgnoreCase ( "M" ) || controlGroup . equalsIgnoreCase ( "E" ) ) && url . startsWith ( "file:" ) ) { throw new ValidationException ( "Malformed URL (file: not allowed for control group " + controlGroup + ") " + url ) ; } try { new URL ( url ) ; } catch ( MalformedURLException e ) { if ( url . startsWith ( DatastreamManagedContent . UPLOADED_SCHEME ) ) { return ; } throw new ValidationException ( "Malformed URL: " + url , e ) ; } }
Validates the candidate URL . The result of the validation also depends on the control group of the datastream in question . Managed datastreams may be ingested using the file URI scheme other datastreams may not .
4,247
public static void validateReservedDatastreams ( DOReader reader ) throws ValidationException { try { for ( Datastream ds : reader . GetDatastreams ( null , null ) ) { if ( "X" . equals ( ds . DSControlGrp ) || "M" . equals ( ds . DSControlGrp ) ) { validateReservedDatastream ( PID . getInstance ( reader . GetObjectPID ( ) ) , ds . DatastreamID , ds ) ; } } } catch ( ValidationException e ) { throw e ; } catch ( ServerException e ) { throw new FaultException ( e ) ; } }
Validates the latest version of all reserved datastreams in the given object .
4,248
public static void validateReservedDatastream ( PID pid , String dsId , Datastream ds ) throws ValidationException { InputStream content = null ; try { if ( "POLICY" . equals ( dsId ) ) { content = ds . getContentStream ( ) ; validatePOLICY ( content ) ; } else if ( "FESLPOLICY" . equals ( dsId ) ) { content = ds . getContentStream ( ) ; validateFESLPOLICY ( content ) ; } else if ( "RELS-EXT" . equals ( dsId ) || "RELS-INT" . equals ( dsId ) ) { content = ds . getContentStream ( ) ; validateRELS ( pid , dsId , content ) ; } } catch ( StreamIOException e ) { throw new ValidationException ( "Failed to get content stream for " + pid + "/" + dsId + ": " + e . getMessage ( ) , e ) ; } if ( content != null ) { try { content . close ( ) ; } catch ( IOException e ) { throw new ValidationException ( "Error closing content stream for " + pid + "/" + dsId + ": " + e . getMessage ( ) , e ) ; } } }
Validates the given datastream if it s a reserved datastream .
4,249
private static void validateRELS ( PID pid , String dsId , InputStream content ) throws ValidationException { logger . debug ( "Validating " + dsId + " datastream" ) ; new RelsValidator ( ) . validate ( pid , dsId , content ) ; logger . debug ( dsId + " datastream is valid" ) ; }
validate relationships datastream
4,250
protected Source convertString2Source ( String param ) { Source src ; try { src = uriResolver . resolve ( param , null ) ; } catch ( TransformerException e ) { src = null ; } if ( src == null ) { src = new StreamSource ( new File ( param ) ) ; } return src ; }
Converts a String parameter to a JAXP Source object .
4,251
protected void renderFO ( String fo , HttpServletResponse response ) throws FOPException , TransformerException , IOException { Source foSrc = convertString2Source ( fo ) ; Transformer transformer = this . transFactory . newTransformer ( ) ; transformer . setURIResolver ( this . uriResolver ) ; render ( foSrc , transformer , response ) ; }
Renders an XSL - FO file into a PDF file . The PDF is written to a byte array that is returned as the method s result .
4,252
protected void renderXML ( String xml , String xslt , HttpServletResponse response ) throws FOPException , TransformerException , IOException { Source xmlSrc = convertString2Source ( xml ) ; Source xsltSrc = convertString2Source ( xslt ) ; Transformer transformer = this . transFactory . newTransformer ( xsltSrc ) ; transformer . setURIResolver ( this . uriResolver ) ; render ( xmlSrc , transformer , response ) ; }
Renders an XML file into a PDF file by applying a stylesheet that converts the XML to XSL - FO . The PDF is written to a byte array that is returned as the method s result .
4,253
public void setSchemaValidation ( boolean validate ) { this . validateSchema = validate ; log . info ( "Initialising validation " + Boolean . toString ( validate ) ) ; ValidationUtility . setValidateFeslPolicy ( validate ) ; }
schema config properties
4,254
public synchronized void shutdown ( ) { try { if ( open ) { open = false ; FileWriter logWriter = new FileWriter ( logFile ) ; logWriter . write ( buffer . toString ( ) ) ; logWriter . close ( ) ; } } catch ( IOException e ) { logger . error ( "Error shutting down" , e ) ; } }
On the first call to this method write the buffer to the log file . Set the flag so no more logging calls will be accepted .
4,255
public static List < TableSpec > getTableSpecs ( InputStream in ) throws InconsistentTableSpecException , IOException { try { TableSpecDeserializer tsd = new TableSpecDeserializer ( ) ; XmlTransformUtility . parseWithoutValidating ( in , tsd ) ; tsd . assertTableSpecsConsistent ( ) ; return tsd . getTableSpecs ( ) ; } catch ( InconsistentTableSpecException itse ) { throw itse ; } catch ( Exception e ) { throw new IOException ( "Error parsing XML: " + e . getMessage ( ) ) ; } }
Gets a TableSpec for each table element in the stream where the stream contains a valid XML document containing one or more table elements wrapped in the root element .
4,256
public synchronized void shutdown ( ) { try { if ( open ) { open = false ; writer . close ( ) ; } } catch ( IOException e ) { logger . error ( "Error shutting down journal log" , e ) ; } }
On the first call to this method close the log file . Set the flag so no more logging calls will be accepted .
4,257
public Boolean getEffectiveInternalSSL ( ) { if ( m_internalSSL != null ) { return m_internalSSL ; } else if ( m_defaultConfig != null ) { return m_defaultConfig . getEffectiveCallSSL ( ) ; } else { return Boolean . FALSE ; } }
Get whether SSL is effectively used for Fedora - to - self calls . This will be the internalSSL value if set or the inherited call value from the default role if set or Boolean . FALSE .
4,258
public Boolean getEffectiveInternalBasicAuth ( ) { if ( m_internalBasicAuth != null ) { return m_internalBasicAuth ; } else if ( m_defaultConfig != null ) { return m_defaultConfig . getEffectiveCallBasicAuth ( ) ; } else { return Boolean . FALSE ; } }
Get whether basic auth is effectively used for Fedora - to - self calls . This will be the internalBasicAuth value if set or the inherited call value from the default role if set or Boolean . FALSE .
4,259
public String getEffectiveInternalUsername ( ) { if ( m_internalUsername != null ) { return m_internalUsername ; } else if ( m_defaultConfig != null ) { return m_defaultConfig . getEffectiveCallUsername ( ) ; } else { return null ; } }
Get the effective internal username for basic auth Fedora - to - self calls . This will be the internal username if set or the inherited call value from the default role if set or null .
4,260
public String getEffectiveInternalPassword ( ) { if ( m_internalPassword != null ) { return m_internalPassword ; } else if ( m_defaultConfig != null ) { return m_defaultConfig . getEffectiveCallPassword ( ) ; } else { return null ; } }
Get the effective internal password for basic auth Fedora - to - self calls . This will be the internal password if set or the inherited call value from the default role if set or null .
4,261
public String [ ] getEffectiveInternalIPList ( ) { if ( m_internalIPList != null ) { return m_internalIPList ; } else if ( m_defaultConfig != null ) { return m_defaultConfig . getEffectiveIPList ( ) ; } else { return null ; } }
Get the effective list of internal IP addresses . This will be the internalIPList value if set or the inherited value from the default role if set or null .
4,262
public void addEmptyConfigs ( Map < String , List < String > > pidToMethodList ) { Iterator < String > pIter = pidToMethodList . keySet ( ) . iterator ( ) ; while ( pIter . hasNext ( ) ) { String sDepPID = pIter . next ( ) ; ServiceDeploymentRoleConfig sDepRoleConfig = m_sDepConfigs . get ( sDepPID ) ; if ( sDepRoleConfig == null ) { sDepRoleConfig = new ServiceDeploymentRoleConfig ( m_defaultConfig , sDepPID ) ; m_sDepConfigs . put ( sDepPID , sDepRoleConfig ) ; } Iterator < String > mIter = pidToMethodList . get ( sDepPID ) . iterator ( ) ; while ( mIter . hasNext ( ) ) { String methodName = ( String ) mIter . next ( ) ; MethodRoleConfig methodRoleConfig = sDepRoleConfig . getMethodConfigs ( ) . get ( methodName ) ; if ( methodRoleConfig == null ) { methodRoleConfig = new MethodRoleConfig ( sDepRoleConfig , methodName ) ; sDepRoleConfig . getMethodConfigs ( ) . put ( methodName , methodRoleConfig ) ; } } } }
Add empty sDep and method configurations given by the map if they are not already already defined .
4,263
public void toStream ( boolean skipNonOverrides , OutputStream out ) throws Exception { PrintWriter writer = null ; try { writer = new PrintWriter ( new OutputStreamWriter ( out , "UTF-8" ) ) ; write ( skipNonOverrides , true , writer ) ; } finally { try { writer . close ( ) ; } catch ( Throwable th ) { } try { out . close ( ) ; } catch ( Throwable th ) { } } }
Serialize to the given stream closing it when finished . If skipNonOverrides is true any configuration whose values are all null will not be written .
4,264
public void write ( boolean skipNonOverrides , boolean withXMLDeclaration , PrintWriter writer ) { final String indent = " " ; if ( withXMLDeclaration ) { writer . println ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ) ; } writer . println ( "<" + _CONFIG + " xmlns=\"" + BE_SECURITY . uri + "\"" ) ; writer . println ( indent + " xmlns:xsi=\"" + XSI . uri + "\"" ) ; writer . println ( indent + " xsi:schemaLocation=\"" + BE_SECURITY . uri + " " + BE_SECURITY1_0 . xsdLocation + "\"" ) ; writer . print ( indent ) ; write ( m_defaultConfig , false , skipNonOverrides , writer ) ; writer . println ( ">" ) ; writeInternalConfig ( 1 , m_internalSSL , m_internalBasicAuth , m_internalUsername , m_internalPassword , m_internalIPList , writer ) ; writeInternalConfig ( 2 , Boolean . FALSE , Boolean . FALSE , null , null , m_internalIPList , writer ) ; Iterator < String > bIter = m_sDepConfigs . keySet ( ) . iterator ( ) ; while ( bIter . hasNext ( ) ) { String role = bIter . next ( ) ; ServiceDeploymentRoleConfig bConfig = m_sDepConfigs . get ( role ) ; write ( bConfig , true , skipNonOverrides , writer ) ; Iterator < String > mIter = bConfig . getMethodConfigs ( ) . keySet ( ) . iterator ( ) ; while ( mIter . hasNext ( ) ) { String methodName = mIter . next ( ) ; MethodRoleConfig mConfig = bConfig . getMethodConfigs ( ) . get ( methodName ) ; write ( mConfig , true , skipNonOverrides , writer ) ; } } writer . println ( "</" + _CONFIG + ">" ) ; }
Serialize to the given writer keeping it open when finished . If skipNonOverrides is true any configuration whose values are all null will not be written .
4,265
private OperationHandler getHandler ( String serviceName , String operationName ) { if ( serviceName == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Service Name was null!" ) ; } return null ; } if ( operationName == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Operation Name was null!" ) ; } return null ; } Map < String , OperationHandler > handlers = m_serviceHandlers . get ( serviceName ) ; if ( handlers == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "No Service Handlers found for: " + serviceName ) ; } return null ; } OperationHandler handler = handlers . get ( operationName ) ; if ( handler == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Handler not found for: " + serviceName + "/" + operationName ) ; } } return handler ; }
Function to try and obtain a handler using the name of the current SOAP service and operation .
4,266
private void enforce ( ResponseCtx res ) { @ SuppressWarnings ( "unchecked" ) Set < Result > results = res . getResults ( ) ; for ( Result r : results ) { if ( r . getDecision ( ) != Result . DECISION_PERMIT ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Denying access: " + r . getDecision ( ) ) ; } switch ( r . getDecision ( ) ) { case Result . DECISION_DENY : throw CXFUtility . getFault ( new AuthzDeniedException ( "Deny" ) ) ; case Result . DECISION_INDETERMINATE : throw CXFUtility . getFault ( new AuthzDeniedException ( "Indeterminate" ) ) ; case Result . DECISION_NOT_APPLICABLE : throw CXFUtility . getFault ( new AuthzDeniedException ( "NotApplicable" ) ) ; default : } } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Permitting access!" ) ; } }
Method to check a response and enforce any denial . This is achieved by throwing an SoapFault .
4,267
public List < Attribute > setupResources ( Map < URI , AttributeValue > res , RelationshipResolver relationshipResolver ) throws MelcoeXacmlException { if ( res == null || res . size ( ) == 0 ) { return new ArrayList < Attribute > ( ) ; } List < Attribute > attributes = new ArrayList < Attribute > ( res . size ( ) ) ; try { String pid = null ; AttributeValue pidAttr = res . get ( Constants . XACML1_RESOURCE . ID . attributeId ) ; if ( pidAttr != null ) { pid = pidAttr . encode ( ) ; pid = relationshipResolver . buildRESTParentHierarchy ( pid ) ; String dsid = null ; AttributeValue dsidAttr = res . get ( Constants . DATASTREAM . ID . attributeId ) ; if ( dsidAttr != null ) { dsid = dsidAttr . encode ( ) ; if ( ! dsid . isEmpty ( ) ) { pid += "/" + dsid ; } } res . put ( Constants . XACML1_RESOURCE . ID . attributeId , new AnyURIAttribute ( new URI ( pid ) ) ) ; } } catch ( Exception e ) { logger . error ( "Error finding parents." , e ) ; throw new MelcoeXacmlException ( "Error finding parents." , e ) ; } for ( URI uri : res . keySet ( ) ) { attributes . add ( new SingletonAttribute ( uri , null , null , res . get ( uri ) ) ) ; } return attributes ; }
Creates a Resource specifying the resource - id a required attribute .
4,268
public List < Attribute > setupAction ( Map < URI , AttributeValue > a ) { if ( a == null || a . size ( ) == 0 ) { return Collections . emptyList ( ) ; } List < Attribute > actions = new ArrayList < Attribute > ( a . size ( ) ) ; Map < URI , AttributeValue > newActions = new HashMap < URI , AttributeValue > ( ) ; for ( URI uri : a . keySet ( ) ) { URI newUri = null ; AttributeValue newValue = null ; if ( actionMap != null && actionMap . size ( ) > 0 ) { newUri = actionMap . get ( uri ) ; } if ( actionValueMap != null && actionValueMap . size ( ) > 0 ) { String tmpValue = actionValueMap . get ( a . get ( uri ) . encode ( ) ) ; if ( tmpValue != null ) { newValue = new StringAttribute ( tmpValue ) ; } } newUri = newUri == null ? uri : newUri ; newValue = newValue == null ? a . get ( uri ) : newValue ; newActions . put ( newUri , newValue ) ; } for ( URI uri : newActions . keySet ( ) ) { actions . add ( new SingletonAttribute ( uri , null , null , newActions . get ( uri ) ) ) ; } return actions ; }
Creates an Action specifying the action - id an optional attribute .
4,269
public List < Attribute > setupEnvironment ( Map < URI , AttributeValue > e ) { if ( e == null || e . size ( ) == 0 ) { return Collections . emptyList ( ) ; } List < Attribute > environment = new ArrayList < Attribute > ( e . size ( ) ) ; for ( URI uri : e . keySet ( ) ) { environment . add ( new SingletonAttribute ( uri , null , null , e . get ( uri ) ) ) ; } return environment ; }
Creates the Environment attributes .
4,270
public RequestCtx buildRequest ( List < Map < URI , List < AttributeValue > > > subjects , Map < URI , AttributeValue > actions , Map < URI , AttributeValue > resources , Map < URI , AttributeValue > environment , RelationshipResolver relationshipResolver ) throws MelcoeXacmlException { logger . debug ( "Building request!" ) ; RequestCtx request = null ; try { request = new BasicRequestCtx ( setupSubjects ( subjects ) , setupResources ( resources , relationshipResolver ) , setupAction ( actions ) , setupEnvironment ( environment ) ) ; } catch ( Exception e ) { logger . error ( "Error creating request." , e ) ; throw new MelcoeXacmlException ( "Error creating request" , e ) ; } return request ; }
Constructs a RequestCtx object .
4,271
public ResponseCtx makeResponseCtx ( String response ) throws MelcoeXacmlException { ResponseCtx resCtx = null ; try { ByteArrayInputStream is = new ByteArrayInputStream ( response . getBytes ( ) ) ; resCtx = ResponseCtx . getInstance ( is ) ; } catch ( ParsingException pe ) { throw new MelcoeXacmlException ( "Error parsing response." , pe ) ; } return resCtx ; }
Converts a string based response to a ResponseCtx obejct .
4,272
public RequestCtx makeRequestCtx ( String request ) throws MelcoeXacmlException { RequestCtx reqCtx = null ; try { ByteArrayInputStream is = new ByteArrayInputStream ( request . getBytes ( ) ) ; reqCtx = BasicRequestCtx . getInstance ( is ) ; } catch ( ParsingException pe ) { throw new MelcoeXacmlException ( "Error parsing response." , pe ) ; } return reqCtx ; }
Converts a string based request to a RequestCtx obejct .
4,273
public String makeRequestCtx ( RequestCtx reqCtx ) { ByteArrayOutputStream request = new ByteArrayOutputStream ( ) ; reqCtx . encode ( request , new Indenter ( ) ) ; return new String ( request . toByteArray ( ) ) ; }
Converts a RequestCtx object to its string representation .
4,274
public String makeResponseCtx ( ResponseCtx resCtx ) { ByteArrayOutputStream response = new ByteArrayOutputStream ( ) ; resCtx . encode ( response , new Indenter ( ) ) ; return new String ( response . toByteArray ( ) ) ; }
Converst a ResponseCtx object to its string representation .
4,275
public Map < String , Result > makeResultMap ( ResponseCtx resCtx ) { @ SuppressWarnings ( "unchecked" ) Iterator < Result > i = resCtx . getResults ( ) . iterator ( ) ; Map < String , Result > resultMap = new HashMap < String , Result > ( ) ; while ( i . hasNext ( ) ) { Result r = i . next ( ) ; resultMap . put ( r . getResource ( ) , r ) ; } return resultMap ; }
Returns a map of resource - id result based on an XACML response .
4,276
private void inputOption ( String optionId ) throws InstallationCancelledException { OptionDefinition opt = OptionDefinition . get ( optionId , this ) ; if ( opt . getLabel ( ) == null || opt . getLabel ( ) . length ( ) == 0 ) { throw new InstallationCancelledException ( optionId + " is missing label (check OptionDefinition.properties?)" ) ; } System . out . println ( opt . getLabel ( ) ) ; System . out . println ( dashes ( opt . getLabel ( ) . length ( ) ) ) ; System . out . println ( opt . getDescription ( ) ) ; System . out . println ( ) ; String [ ] valids = opt . getValidValues ( ) ; if ( valids != null ) { System . out . print ( "Options : " ) ; for ( int i = 0 ; i < valids . length ; i ++ ) { if ( i > 0 ) { System . out . print ( ", " ) ; } System . out . print ( valids [ i ] ) ; } System . out . println ( ) ; } String defaultVal = opt . getDefaultValue ( ) ; if ( valids != null || defaultVal != null ) { System . out . println ( ) ; } boolean gotValidValue = false ; while ( ! gotValidValue ) { System . out . print ( "Enter a value " ) ; if ( defaultVal != null ) { System . out . print ( "[default is " + defaultVal + "] " ) ; } System . out . print ( "==> " ) ; String value = readLine ( ) . trim ( ) ; if ( value . length ( ) == 0 && defaultVal != null ) { value = defaultVal ; } System . out . println ( ) ; if ( value . equalsIgnoreCase ( "cancel" ) ) { throw new InstallationCancelledException ( "Cancelled by user." ) ; } try { opt . validateValue ( value ) ; gotValidValue = true ; _map . put ( optionId , value ) ; System . out . println ( ) ; } catch ( OptionValidationException e ) { System . out . println ( "Error: " + e . getMessage ( ) ) ; } } }
Get the indicated option from the console . Continue prompting until the value is valid or the user has indicated they want to cancel the installation .
4,277
public int getIntValue ( String name , int defaultValue ) throws NumberFormatException { String value = getValue ( name ) ; if ( value == null ) { return defaultValue ; } else { return Integer . parseInt ( value ) ; } }
Get the value of the given option as an integer or the given default value if unspecified .
4,278
private void applyDefaults ( ) { for ( String name : getOptionNames ( ) ) { String val = _map . get ( name ) ; if ( val == null || val . length ( ) == 0 ) { OptionDefinition opt = OptionDefinition . get ( name , this ) ; _map . put ( name , opt . getDefaultValue ( ) ) ; } } }
Apply defaults to the options where possible .
4,279
private void validateAll ( ) throws OptionValidationException { boolean unattended = getBooleanValue ( UNATTENDED , false ) ; for ( String optionId : getOptionNames ( ) ) { OptionDefinition opt = OptionDefinition . get ( optionId , this ) ; if ( opt == null ) { throw new OptionValidationException ( "Option is not defined" , optionId ) ; } opt . validateValue ( getValue ( optionId ) , unattended ) ; } }
Validate the options assuming defaults have already been applied . Validation for a given option might entail more than a syntax check . It might check whether a given directory exists for example .
4,280
private List < String > getFedoraTables ( ) { try { InputStream in = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( DBSPEC_LOCATION ) ; List < TableSpec > specs = TableSpec . getTableSpecs ( in ) ; ArrayList < String > names = new ArrayList < String > ( ) ; for ( TableSpec spec : specs ) { names . add ( spec . getName ( ) . toUpperCase ( ) ) ; } return names ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new RuntimeException ( "Unexpected error reading dbspec file" , e ) ; } }
Get the names of all Fedora tables listed in the server s dbSpec file . Names will be returned in ALL CAPS so that case - insensitive comparisons can be done .
4,281
private void registerObject ( DigitalObject obj ) throws StorageDeviceException { String pid = obj . getPid ( ) ; String userId = "the userID field is no longer used" ; String label = "the label field is no longer used" ; Connection conn = null ; PreparedStatement s1 = null ; try { String query = "INSERT INTO doRegistry (doPID, ownerId, label) VALUES (?, ?, ?)" ; conn = m_connectionPool . getReadWriteConnection ( ) ; s1 = conn . prepareStatement ( query ) ; s1 . setString ( 1 , pid ) ; s1 . setString ( 2 , userId ) ; s1 . setString ( 3 , label ) ; s1 . executeUpdate ( ) ; if ( obj . hasContentModel ( Models . SERVICE_DEPLOYMENT_3_0 ) ) { updateDeploymentMap ( obj , conn ) ; } } catch ( SQLException sqle ) { throw new StorageDeviceException ( "Unexpected error from SQL database while registering object: " + sqle . getMessage ( ) , sqle ) ; } finally { try { if ( s1 != null ) { s1 . close ( ) ; } } catch ( Exception sqle ) { throw new StorageDeviceException ( "Unexpected error from SQL database while registering object: " + sqle . getMessage ( ) , sqle ) ; } finally { s1 = null ; } } PreparedStatement s2 = null ; ResultSet results = null ; try { logger . debug ( "COMMIT: Updating registry..." ) ; String query = "SELECT systemVersion FROM doRegistry WHERE doPID=?" ; s2 = conn . prepareStatement ( query ) ; s2 . setString ( 1 , pid ) ; results = s2 . executeQuery ( ) ; if ( ! results . next ( ) ) { throw new ObjectNotFoundException ( "Error creating replication job: The requested object doesn't exist in the registry." ) ; } int systemVersion = results . getInt ( "systemVersion" ) ; systemVersion ++ ; query = "UPDATE doRegistry SET systemVersion=? WHERE doPID=?" ; s2 . close ( ) ; s2 = conn . prepareStatement ( query ) ; s2 . setInt ( 1 , systemVersion ) ; s2 . setString ( 2 , pid ) ; s2 . executeUpdate ( ) ; } catch ( SQLException sqle ) { throw new StorageDeviceException ( "Error creating replication job: " + sqle . getMessage ( ) ) ; } catch ( ObjectNotFoundException e ) { e . printStackTrace ( ) ; } finally { try { if ( results != null ) { results . close ( ) ; } if ( s2 != null ) { s2 . close ( ) ; } if ( conn != null ) { m_connectionPool . free ( conn ) ; } } catch ( SQLException sqle ) { throw new StorageDeviceException ( "Unexpected error from SQL database: " + sqle . getMessage ( ) ) ; } finally { results = null ; s2 = null ; } } }
Adds a new object .
4,282
private void checkForPotentialFilenameConflict ( ) throws JournalException { File [ ] journalFiles = MultiFileJournalHelper . getSortedArrayOfJournalFiles ( journalDirectory , filenamePrefix ) ; if ( journalFiles . length == 0 ) { return ; } String newestFilename = journalFiles [ journalFiles . length - 1 ] . getName ( ) ; String potentialFilename = JournalHelper . createTimestampedFilename ( filenamePrefix , new Date ( ) ) ; if ( newestFilename . compareTo ( potentialFilename ) > 0 ) { throw new JournalException ( "The name of one or more existing files in the journal " + "directory (e.g. '" + newestFilename + "') may conflict with new Journal " + "files. Has the system clock changed?" ) ; } }
Look at the list of files in the current directory and make sure that any new files we create won t conflict with them .
4,283
public void writeJournalEntry ( CreatorJournalEntry journalEntry ) throws JournalException { if ( open ) { try { synchronized ( JournalWriter . SYNCHRONIZER ) { XMLEventWriter xmlWriter = currentJournal . getXmlWriter ( ) ; super . writeJournalEntry ( journalEntry , xmlWriter ) ; xmlWriter . flush ( ) ; currentJournal . closeIfAppropriate ( ) ; } } catch ( XMLStreamException e ) { throw new JournalException ( e ) ; } } }
We ve prepared for the entry so just write it but remember to synchronize on the file so we don t get an asynchronous close while we re writing . After writing the entry flush the file .
4,284
protected Object getSOAPRequestObjects ( SOAPMessageContext context ) { SOAPElement requestNode = getSOAPRequestNode ( context ) ; return unmarshall ( requestNode ) ; }
Extracts the request as object from the context .
4,285
protected void setSOAPRequestObjects ( SOAPMessageContext context , List < SOAPElement > params ) { SOAPMessage message = context . getMessage ( ) ; SOAPBody body ; try { body = message . getSOAPBody ( ) ; } catch ( SOAPException e ) { throw CXFUtility . getFault ( e ) ; } try { body . removeContents ( ) ; for ( SOAPElement p : params ) { body . addChildElement ( p ) ; } } catch ( Exception e ) { logger . error ( "Problem changing SOAP message contents" , e ) ; throw CXFUtility . getFault ( e ) ; } }
Sets the request parameters for a request .
4,286
protected void setSOAPResponseObject ( SOAPMessageContext context , Object newResponse ) { if ( newResponse == null ) { return ; } SOAPMessage message = context . getMessage ( ) ; SOAPElement body ; try { body = message . getSOAPBody ( ) ; SOAPElement response = getSOAPResponseNode ( context ) ; body . removeChild ( response ) ; marshall ( newResponse , body ) ; } catch ( SOAPException e ) { logger . error ( "Problem changing SOAP message contents" , e ) ; throw CXFUtility . getFault ( e ) ; } }
Sets the return object for a response as the param .
4,287
protected List < Map < URI , List < AttributeValue > > > getSubjects ( SOAPMessageContext context ) { List < Map < URI , List < AttributeValue > > > subjects = new ArrayList < Map < URI , List < AttributeValue > > > ( ) ; if ( getUser ( context ) == null || getUser ( context ) . trim ( ) . isEmpty ( ) ) { return subjects ; } String [ ] fedoraRole = getUserRoles ( context ) ; Map < URI , List < AttributeValue > > subAttr = null ; List < AttributeValue > attrList = null ; subAttr = new HashMap < URI , List < AttributeValue > > ( ) ; attrList = new ArrayList < AttributeValue > ( ) ; attrList . add ( new StringAttribute ( getUser ( context ) ) ) ; subAttr . put ( Constants . SUBJECT . LOGIN_ID . getURI ( ) , attrList ) ; if ( fedoraRole != null && fedoraRole . length > 0 ) { attrList = new ArrayList < AttributeValue > ( ) ; for ( String r : fedoraRole ) { attrList . add ( new StringAttribute ( r ) ) ; } subAttr . put ( Constants . SUBJECT . ROLE . getURI ( ) , attrList ) ; } subjects . add ( subAttr ) ; subAttr = new HashMap < URI , List < AttributeValue > > ( ) ; attrList = new ArrayList < AttributeValue > ( ) ; attrList . add ( new StringAttribute ( getUser ( context ) ) ) ; subAttr . put ( Constants . SUBJECT . USER_REPRESENTED . getURI ( ) , attrList ) ; if ( fedoraRole != null && fedoraRole . length > 0 ) { attrList = new ArrayList < AttributeValue > ( ) ; for ( String r : fedoraRole ) { attrList . add ( new StringAttribute ( r ) ) ; } subAttr . put ( Constants . SUBJECT . ROLE . getURI ( ) , attrList ) ; } subjects . add ( subAttr ) ; subAttr = new HashMap < URI , List < AttributeValue > > ( ) ; attrList = new ArrayList < AttributeValue > ( ) ; attrList . add ( new StringAttribute ( getUser ( context ) ) ) ; subAttr . put ( Constants . XACML1_SUBJECT . ID . getURI ( ) , attrList ) ; if ( fedoraRole != null && fedoraRole . length > 0 ) { attrList = new ArrayList < AttributeValue > ( ) ; for ( String r : fedoraRole ) { attrList . add ( new StringAttribute ( r ) ) ; } subAttr . put ( Constants . SUBJECT . ROLE . getURI ( ) , attrList ) ; } subjects . add ( subAttr ) ; return subjects ; }
Extracts the list of Subjects from the given context .
4,288
protected Map < URI , AttributeValue > getResources ( SOAPMessageContext context ) throws OperationHandlerException , URISyntaxException { Object oMap = null ; String pid = null ; try { oMap = getSOAPRequestObjects ( context ) ; logger . debug ( "Retrieved SOAP Request Objects" ) ; } catch ( SoapFault af ) { logger . error ( "Error obtaining SOAP Request Objects" , af ) ; throw new OperationHandlerException ( "Error obtaining SOAP Request Objects" , af ) ; } try { pid = ( String ) callGetter ( "getPid" , oMap ) ; } catch ( Exception e ) { logger . error ( "Error obtaining parameters" , e ) ; throw new OperationHandlerException ( "Error obtaining parameters." , e ) ; } Map < URI , AttributeValue > resAttr = ResourceAttributes . getResources ( pid ) ; logger . debug ( "Extracted SOAP Request Objects" ) ; return resAttr ; }
Obtains a map of resource Attributes .
4,289
@ SuppressWarnings ( "unchecked" ) protected String [ ] getUserRoles ( SOAPMessageContext context ) { HttpServletRequest request = ( HttpServletRequest ) context . get ( SOAPMessageContext . SERVLET_REQUEST ) ; Map < String , Set < String > > reqAttr = null ; reqAttr = ( Map < String , Set < String > > ) request . getAttribute ( "FEDORA_AUX_SUBJECT_ATTRIBUTES" ) ; if ( reqAttr == null ) { return null ; } Set < String > fedoraRoles = reqAttr . get ( "fedoraRole" ) ; if ( fedoraRoles == null || fedoraRoles . size ( ) == 0 ) { return null ; } String [ ] fedoraRole = fedoraRoles . toArray ( new String [ fedoraRoles . size ( ) ] ) ; return fedoraRole ; }
Returns the roles that the user has .
4,290
private ExternalContentManager getExternalContentManager ( ) throws Exception { if ( s_ecm == null ) { Server server ; try { server = Server . getInstance ( new File ( Constants . FEDORA_HOME ) , false ) ; s_ecm = ( ExternalContentManager ) server . getModule ( "org.fcrepo.server.storage.ExternalContentManager" ) ; } catch ( InitializationException e ) { throw new Exception ( "Unable to get ExternalContentManager Module: " + e . getMessage ( ) , e ) ; } } return s_ecm ; }
Gets the external content manager which is used for the retrieval of content .
4,291
public InputStream getContentStream ( Context context ) throws StreamIOException { try { ContentManagerParams params = new ContentManagerParams ( DSLocation ) ; if ( context != null ) { params . setContext ( context ) ; } MIMETypedStream stream = getExternalContentManager ( ) . getExternalContent ( params ) ; DSSize = getContentLength ( stream ) ; return stream . getStream ( ) ; } catch ( Exception ex ) { throw new StreamIOException ( "Error getting content stream" , ex ) ; } }
Gets an InputStream to the content of this externally - referenced datastream .
4,292
public long getContentLength ( MIMETypedStream stream ) { long length = 0 ; if ( stream . header != null ) { for ( int i = 0 ; i < stream . header . length ; i ++ ) { if ( stream . header [ i ] . name != null && ! stream . header [ i ] . name . equalsIgnoreCase ( "" ) && stream . header [ i ] . name . equalsIgnoreCase ( "content-length" ) ) { length = Long . parseLong ( stream . header [ i ] . value ) ; break ; } } } return length ; }
Returns the length of the content of this stream .
4,293
public void contextDestroyed ( ServletContextEvent event ) { try { for ( Enumeration < Driver > e = DriverManager . getDrivers ( ) ; e . hasMoreElements ( ) ; ) { Driver driver = e . nextElement ( ) ; if ( driver . getClass ( ) . getClassLoader ( ) == getClass ( ) . getClassLoader ( ) ) { DriverManager . deregisterDriver ( driver ) ; } } } catch ( Throwable e ) { } }
Clean up resources used by the application when stopped
4,294
private void checkForUnsupportedPattern ( String namespaceURI , String localName , String qName , Attributes attrs ) throws SAXException { if ( namespaceURI . equalsIgnoreCase ( XML_XSD . uri ) && localName . equalsIgnoreCase ( "complexType" ) ) { throw new SAXException ( "WSDLParser: Detected a WSDL pattern that Fedora does not yet support: " + qName ) ; } else if ( namespaceURI . equalsIgnoreCase ( XML_XSD . uri ) && localName . equalsIgnoreCase ( "element" ) ) { throw new SAXException ( "WSDLParser: Detected a WSDL pattern that Fedora does not yet support: " + qName ) ; } else if ( namespaceURI . equalsIgnoreCase ( XML_XSD . uri ) && localName . equalsIgnoreCase ( "list" ) ) { throw new SAXException ( "WSDLParser: Detected a WSDL pattern that Fedora does not yet support: " + qName ) ; } else if ( namespaceURI . equalsIgnoreCase ( XML_XSD . uri ) && localName . equalsIgnoreCase ( "union" ) ) { throw new SAXException ( "WSDLParser: Detected a WSDL pattern that Fedora does not yet support: " + qName ) ; } else if ( namespaceURI . equalsIgnoreCase ( WSDL . uri ) && localName . equalsIgnoreCase ( "import" ) ) { throw new SAXException ( "WSDLParser: Detected a WSDL pattern that Fedora does not yet support: " + qName ) ; } else if ( namespaceURI . equalsIgnoreCase ( WSDL . uri ) && localName . equalsIgnoreCase ( "fault" ) ) { throw new SAXException ( "WSDLParser: Detected a WSDL pattern that Fedora does not yet support: " + qName ) ; } else if ( namespaceURI . equalsIgnoreCase ( WSDL . uri ) && localName . equalsIgnoreCase ( "part" ) && attrs . getValue ( "element" ) != null ) { throw new SAXException ( "WSDLParser: Detected a WSDL pattern that Fedora does not yet support: " + qName + " element attr" ) ; } else if ( namespaceURI . equalsIgnoreCase ( SOAP . uri ) && localName . equalsIgnoreCase ( "binding" ) ) { throw new SAXException ( "WSDLParser: Detected a WSDL pattern that Fedora does not yet support: " + qName ) ; } else if ( namespaceURI . equalsIgnoreCase ( WSDL_MIME . uri ) && localName . equalsIgnoreCase ( "multipartRelated" ) ) { throw new SAXException ( "WSDLParser: Detected a WSDL pattern that Fedora does not yet support: " + qName ) ; } else if ( namespaceURI . equalsIgnoreCase ( WSDL_HTTP . uri ) && localName . equalsIgnoreCase ( "urlEncoded" ) ) { throw new SAXException ( "WSDLParser: Detected a WSDL pattern that Fedora does not yet support: " + qName ) ; } }
we might encounter!
4,295
private ImageProcessor resize ( ImageProcessor ip , String newWidth ) { if ( newWidth != null ) { try { int width = Integer . parseInt ( newWidth ) ; if ( width < 0 ) { return ip ; } int imgWidth = ip . getWidth ( ) ; int imgHeight = ip . getHeight ( ) ; ip = ip . resize ( width , width * imgHeight / imgWidth ) ; } catch ( NumberFormatException e ) { } } return ip ; }
Resizes an image to the supplied new width in pixels . The height is reduced proportionally to the new width .
4,296
private ImageProcessor zoom ( ImageProcessor ip , String zoomAmt ) { if ( zoomAmt != null ) { try { float zoom = Float . parseFloat ( zoomAmt ) ; if ( zoom < 0 ) { return ip ; } ip . scale ( zoom , zoom ) ; if ( zoom < 1 ) { int imgWidth = ip . getWidth ( ) ; int imgHeight = ip . getHeight ( ) ; ip . setRoi ( Math . round ( imgWidth / 2 - imgWidth * zoom / 2 ) , Math . round ( imgHeight / 2 - imgHeight * zoom / 2 ) , Math . round ( imgWidth * zoom ) , Math . round ( imgHeight * zoom ) ) ; ip = ip . crop ( ) ; } } catch ( NumberFormatException e ) { } } return ip ; }
Zooms either in or out of an image by a supplied amount . The zooming occurs from the center of the image .
4,297
private ImageProcessor brightness ( ImageProcessor ip , String brightAmt ) { if ( brightAmt != null ) { try { float bright = Float . parseFloat ( brightAmt ) ; if ( bright < 0 ) { return ip ; } ip . multiply ( bright ) ; } catch ( NumberFormatException e ) { } } return ip ; }
Adjusts the brightness of an image by a supplied amount .
4,298
public ImageProcessor crop ( ImageProcessor ip , String cropX , String cropY , String cropWidth , String cropHeight ) { if ( cropX != null && cropY != null ) { try { int x = Integer . parseInt ( cropX ) ; int y = Integer . parseInt ( cropY ) ; int width ; int height ; if ( cropWidth != null ) { width = Integer . parseInt ( cropWidth ) ; } else { width = ip . getWidth ( ) ; } if ( cropHeight != null ) { height = Integer . parseInt ( cropHeight ) ; } else { height = ip . getHeight ( ) ; } if ( x < 0 || y < 0 || width < 0 || height < 0 ) { return ip ; } ip . setRoi ( x , y , width , height ) ; ip = ip . crop ( ) ; } catch ( NumberFormatException e ) { } } return ip ; }
Crops an image with supplied starting point and ending point .
4,299
public void start ( boolean wait ) throws MessagingException { Thread connector = new JMSBrokerConnector ( ) ; connector . start ( ) ; if ( wait ) { int maxWait = RETRY_INTERVAL * MAX_RETRIES ; int waitTime = 0 ; while ( ! isConnected ( ) ) { if ( waitTime < maxWait ) { try { Thread . sleep ( 100 ) ; waitTime += 100 ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; } } else { throw new MessagingException ( "Timeout reached waiting " + "for messaging client to start." ) ; } } } }
Starts the MessagingClient . This method must be called in order to receive messages .