idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
21,000
public synchronized boolean handleChangedFile ( ChangedFile changedFile ) { File watchDir = getWatchDir ( changedFile . getFile ( ) ) ; SyncWorker worker = new SyncWorker ( changedFile , watchDir , endpoint ) ; try { addToWorkerList ( worker ) ; workerPool . execute ( worker ) ; return true ; } catch ( RejectedExecutionException e ) { workerList . remove ( worker ) ; return false ; } }
Notifies the SyncManager that a file has changed
21,001
protected int calculateBufferSize ( long maxChunkSize ) { final int KB = 1000 ; if ( maxChunkSize % KB != 0 ) { String m = "MaxChunkSize must be multiple of " + KB + ": " + maxChunkSize ; log . error ( m ) ; throw new DuraCloudRuntimeException ( m ) ; } long size = maxChunkSize ; for ( int i = 1 ; i <= maxChunkSize ; i ++ ) { if ( ( maxChunkSize % i == 0 ) && ( ( maxChunkSize / i ) <= ( 8 * KB ) ) ) { size = maxChunkSize / i ; break ; } } log . debug ( "Buf size: " + size + " for maxChunkSize: " + maxChunkSize ) ; return ( int ) size ; }
This method finds the maximum 1 - KB divisor of arg maxChunkSize that is less than 8 - KB . It also ensures that arg maxChunkSize is a multiple of 1 - KB otherwise the stream buffering would lose bytes if the maxChunkSize was not divisible by the buffer size . Additionally by making the buffer multiples of 1 - KB ensures efficient block - writing .
21,002
protected DistributionSummary getExistingDistribution ( String bucketName ) { List < DistributionSummary > dists = getAllExistingWebDistributions ( bucketName ) ; if ( dists . isEmpty ( ) ) { return null ; } else { return dists . get ( 0 ) ; } }
Returns the first streaming web distribution associated with a given bucket
21,003
protected List < DistributionSummary > getAllExistingWebDistributions ( String bucketName ) { List < DistributionSummary > distListForBucket = new ArrayList < > ( ) ; DistributionList distList = cfClient . listDistributions ( new ListDistributionsRequest ( ) ) . getDistributionList ( ) ; List < DistributionSummary > webDistList = distList . getItems ( ) ; while ( distList . isTruncated ( ) ) { distList = cfClient . listDistributions ( new ListDistributionsRequest ( ) . withMarker ( distList . getNextMarker ( ) ) ) . getDistributionList ( ) ; webDistList . addAll ( distList . getItems ( ) ) ; } for ( DistributionSummary distSummary : webDistList ) { if ( isDistFromBucket ( bucketName , distSummary ) ) { distListForBucket . add ( distSummary ) ; } } return distListForBucket ; }
Determines if a streaming distribution already exists for a given bucket
21,004
protected void checkThatStreamingServiceIsEnabled ( String spaceId , String taskName ) { Map < String , String > spaceProperties = s3Provider . getSpaceProperties ( spaceId ) ; if ( ! spaceProperties . containsKey ( HLS_STREAMING_HOST_PROP ) ) { throw new UnsupportedTaskException ( taskName , "The " + taskName + " task can only be used after a space " + "has been configured to enable HLS streaming. Use " + StorageTaskConstants . ENABLE_HLS_TASK_NAME + " to enable HLS streaming on this space." ) ; } }
Determines if a streaming distribution exists for a given space
21,005
public Iterator < String > getSpaces ( ) { ConnectOperation co = new ConnectOperation ( host , port , username , password , zone ) ; log . trace ( "Listing spaces" ) ; try { return listDirectories ( baseDirectory , co . getConnection ( ) ) ; } catch ( IOException e ) { log . error ( "Could not connect to iRODS" , e ) ; throw new StorageException ( e ) ; } }
Return a list of irods spaces . IRODS spaces are directories under the baseDirectory of this provider .
21,006
public void createSpace ( String spaceId ) { ConnectOperation co = new ConnectOperation ( host , port , username , password , zone ) ; try { IrodsOperations io = new IrodsOperations ( co ) ; io . mkdir ( baseDirectory + "/" + spaceId ) ; log . trace ( "Created space/directory: " + baseDirectory + "/" + spaceId ) ; } catch ( IOException e ) { log . error ( "Could not connect to iRODS" , e ) ; throw new StorageException ( e ) ; } }
Create a new directory under the baseDirectory
21,007
public static ChunksManifest createManifestFrom ( ChunksManifestDocument doc ) { ChunksManifestType manifestType = doc . getChunksManifest ( ) ; HeaderType headerType = manifestType . getHeader ( ) ; ChunksManifest . ManifestHeader header = createHeaderFromElement ( headerType ) ; ChunksType chunksType = manifestType . getChunks ( ) ; List < ChunksManifestBean . ManifestEntry > entries = createEntriesFromElement ( chunksType ) ; ChunksManifestBean manifestBean = new ChunksManifestBean ( ) ; manifestBean . setHeader ( header ) ; manifestBean . setEntries ( entries ) ; return new ChunksManifest ( manifestBean ) ; }
This method binds a ChunksManifest xml document to a ChunksManifest object
21,008
public long loadBackup ( ) { long backupTime = - 1 ; File [ ] backupDirFiles = getSortedBackupDirFiles ( ) ; if ( backupDirFiles . length > 0 ) { File latestBackup = backupDirFiles [ 0 ] ; try { backupTime = Long . parseLong ( latestBackup . getName ( ) ) ; changedList . restore ( latestBackup , this . contentDirs ) ; } catch ( NumberFormatException e ) { logger . error ( "Unable to load changed list backup. File in " + "changed list backup dir has invalid name: " + latestBackup . getName ( ) ) ; backupTime = - 1 ; } } return backupTime ; }
Attempts to reload the changed list from a backup file . If there are no backup files or the backup file cannot be read returns - 1 otherwise the backup file is loaded and the time the backup file was written is returned .
21,009
public void run ( ) { while ( continueBackup ) { if ( changedListVersion < changedList . getVersion ( ) ) { cleanupBackupDir ( SAVED_BACKUPS ) ; String filename = String . valueOf ( System . currentTimeMillis ( ) ) ; File persistFile = new File ( backupDir , filename ) ; backingUp = true ; changedListVersion = changedList . persist ( persistFile ) ; backingUp = false ; } sleepAndCheck ( backupFrequency ) ; } }
Runs the backup manager . Writes out files which are a backups of the changed list based on the set backup frequency . Retains SAVED_BACKUPS number of backup files removes the rest .
21,010
public synchronized ChangedFile reserve ( ) { if ( fileList . isEmpty ( ) || shutdown ) { return null ; } String key = fileList . keySet ( ) . iterator ( ) . next ( ) ; ChangedFile changedFile = fileList . remove ( key ) ; reservedFiles . put ( key , changedFile ) ; incrementVersion ( ) ; fireChangedEventAsync ( ) ; return changedFile ; }
Retrieves a changed file for processing and removes it from the list of unreserved files . Returns null if there are no changed files in the list .
21,011
public long persist ( File persistFile ) { try { FileOutputStream fileStream = new FileOutputStream ( persistFile ) ; ObjectOutputStream oStream = new ObjectOutputStream ( ( fileStream ) ) ; long persistVersion ; Map < String , ChangedFile > fileListCopy ; synchronized ( this ) { fileListCopy = ( Map < String , ChangedFile > ) fileList . clone ( ) ; fileListCopy . putAll ( reservedFiles ) ; persistVersion = listVersion ; } oStream . writeObject ( fileListCopy ) ; oStream . close ( ) ; return persistVersion ; } catch ( IOException e ) { throw new RuntimeException ( "Unable to persist File Changed List:" + e . getMessage ( ) , e ) ; } }
Writes out the current state of the ChangeList to the given file .
21,012
public synchronized void restore ( File persistFile , List < File > contentDirs ) { try { FileInputStream fileStream = new FileInputStream ( persistFile ) ; ObjectInputStream oStream = new ObjectInputStream ( fileStream ) ; log . info ( "Restoring changed list from backup: {}" , persistFile . getAbsolutePath ( ) ) ; synchronized ( this ) { LinkedHashMap < String , ChangedFile > fileListFromDisk = ( LinkedHashMap < String , ChangedFile > ) oStream . readObject ( ) ; if ( contentDirs != null && ! contentDirs . isEmpty ( ) ) { Iterator < Entry < String , ChangedFile > > entries = fileListFromDisk . entrySet ( ) . iterator ( ) ; while ( entries . hasNext ( ) ) { Entry < String , ChangedFile > entry = entries . next ( ) ; ChangedFile file = entry . getValue ( ) ; boolean watched = false ; for ( File contentDir : contentDirs ) { if ( file . getFile ( ) . getAbsolutePath ( ) . startsWith ( contentDir . getAbsolutePath ( ) ) && ! this . fileExclusionManager . isExcluded ( file . getFile ( ) ) ) { watched = true ; break ; } } if ( ! watched ) { entries . remove ( ) ; } } } this . fileList = fileListFromDisk ; } oStream . close ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "Unable to restore File Changed List:" + e . getMessage ( ) , e ) ; } }
Restores the state of the ChangedList using the given backup file
21,013
private Response addSpacePropertiesToResponse ( ResponseBuilder response , String spaceID , String storeID ) throws ResourceException { Map < String , String > properties = spaceResource . getSpaceProperties ( spaceID , storeID ) ; return addPropertiesToResponse ( response , properties ) ; }
Adds the properties of a space as header values to the response
21,014
private Response addSpaceACLsToResponse ( ResponseBuilder response , String spaceID , String storeID ) throws ResourceException { Map < String , String > aclProps = new HashMap < String , String > ( ) ; Map < String , AclType > acls = spaceResource . getSpaceACLs ( spaceID , storeID ) ; for ( String key : acls . keySet ( ) ) { aclProps . put ( key , acls . get ( key ) . name ( ) ) ; } return addPropertiesToResponse ( response , aclProps ) ; }
Adds the ACLs of a space as header values to the response .
21,015
@ Path ( "/acl/{spaceID}" ) public Response updateSpaceACLs ( @ PathParam ( "spaceID" ) String spaceID , @ QueryParam ( "storeID" ) String storeID ) { String msg = "update space ACLs(" + spaceID + ", " + storeID + ")" ; try { log . debug ( msg ) ; return doUpdateSpaceACLs ( spaceID , storeID ) ; } catch ( ResourceNotFoundException e ) { return responseNotFound ( msg , e , NOT_FOUND ) ; } catch ( ResourceException e ) { return responseBad ( msg , e , INTERNAL_SERVER_ERROR ) ; } catch ( Exception e ) { return responseBad ( msg , e , INTERNAL_SERVER_ERROR ) ; } }
This method sets the ACLs associated with a space . Only values included in the ACLs headers will be updated others will be removed .
21,016
public ChunksManifest write ( String spaceId , ChunkableContent chunkable , Map < String , String > contentProperties ) throws NotFoundException { return write ( spaceId , chunkable , contentProperties , true ) ; }
This method implements the ContentWriter interface for writing content to a DataStore . In this case the DataStore is durastore .
21,017
public String writeSingle ( String spaceId , String chunkChecksum , ChunkInputStream chunk , Map < String , String > properties ) throws NotFoundException { log . debug ( "writeSingle: " + spaceId + ", " + chunk . getChunkId ( ) ) ; createSpaceIfNotExist ( spaceId ) ; addChunk ( spaceId , chunkChecksum , chunk , properties , true ) ; log . debug ( "written: " + spaceId + ", " + chunk . getChunkId ( ) ) ; return chunk . getMD5 ( ) ; }
This method writes a single chunk to the DataStore .
21,018
public String getSpaces ( String storeID ) throws ResourceException { Element spacesElem = new Element ( "spaces" ) ; try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; Iterator < String > spaces = storage . getSpaces ( ) ; while ( spaces . hasNext ( ) ) { String spaceID = spaces . next ( ) ; Element spaceElem = new Element ( "space" ) ; spaceElem . setAttribute ( "id" , spaceID ) ; spacesElem . addContent ( spaceElem ) ; } } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "Error attempting to build spaces XML" , e ) ; } Document doc = new Document ( spacesElem ) ; XMLOutputter xmlConverter = new XMLOutputter ( ) ; return xmlConverter . outputString ( doc ) ; }
Provides a listing of all spaces for a customer . Open spaces are always included in the list closed spaces are included based on user authorization .
21,019
public String getSpaceContents ( String spaceID , String storeID , String prefix , long maxResults , String marker ) throws ResourceException { Element spaceElem = new Element ( "space" ) ; spaceElem . setAttribute ( "id" , spaceID ) ; try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; List < String > contents = storage . getSpaceContentsChunked ( spaceID , prefix , maxResults , marker ) ; if ( contents != null ) { for ( String contentItem : contents ) { Element contentElem = new Element ( "item" ) ; contentElem . setText ( contentItem ) ; spaceElem . addContent ( contentElem ) ; } } } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "build space XML for" , spaceID , e ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "build space XML for" , spaceID , e ) ; } Document doc = new Document ( spaceElem ) ; XMLOutputter xmlConverter = new XMLOutputter ( ) ; return xmlConverter . outputString ( doc ) ; }
Gets a listing of the contents of a space .
21,020
public void addSpace ( String spaceID , Map < String , AclType > userACLs , String storeID ) throws ResourceException , InvalidIdException { IdUtil . validateSpaceId ( spaceID ) ; try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; storage . createSpace ( spaceID ) ; waitForSpaceCreation ( storage , spaceID ) ; updateSpaceACLs ( spaceID , userACLs , storeID ) ; } catch ( NotFoundException e ) { throw new InvalidIdException ( e . getMessage ( ) ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "add space" , spaceID , e ) ; } }
Adds a space .
21,021
public void updateSpaceACLs ( String spaceID , Map < String , AclType > spaceACLs , String storeID ) throws ResourceException { try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; if ( null != spaceACLs ) { storage . setSpaceACLs ( spaceID , spaceACLs ) ; } } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "update space ACLs for" , spaceID , e ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "update space ACLs for" , spaceID , e ) ; } }
Updates the ACLs of a space .
21,022
public void deleteSpace ( String spaceID , String storeID ) throws ResourceException { try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; storage . deleteSpace ( spaceID ) ; } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "delete space" , spaceID , e ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "delete space" , spaceID , e ) ; } }
Deletes a space removing all included content .
21,023
public UserDetails loadUserByUsername ( String username ) throws UsernameNotFoundException { UserDetails userDetails = usersTable . get ( username ) ; if ( null == userDetails ) { throw new UsernameNotFoundException ( username ) ; } return userDetails ; }
This method retrieves UserDetails for all users from a flat file in DuraCloud .
21,024
public List < SecurityUserBean > getUsers ( ) { List < SecurityUserBean > users = new ArrayList < SecurityUserBean > ( ) ; for ( DuracloudUserDetails user : this . usersTable . values ( ) ) { SecurityUserBean bean = createUserBean ( user ) ; users . add ( bean ) ; } return users ; }
This method returns all of the non - system - defined users .
21,025
public static ByteArrayInputStream storeProperties ( Map < String , String > propertiesMap ) throws StorageException { propertiesMap . remove ( StorageProvider . PROPERTIES_SPACE_COUNT ) ; byte [ ] properties = null ; try { String serializedProperties = serializeMap ( propertiesMap ) ; properties = serializedProperties . getBytes ( "UTF-8" ) ; } catch ( Exception e ) { String err = "Could not store properties" + " due to error: " + e . getMessage ( ) ; throw new StorageException ( err ) ; } ByteArrayInputStream is = new ByteArrayInputStream ( properties ) ; return is ; }
Converts properties stored in a Map into a stream for storage purposes .
21,026
public static String compareChecksum ( StorageProvider provider , String spaceId , String contentId , String checksum ) throws StorageException { String providerChecksum = provider . getContentProperties ( spaceId , contentId ) . get ( StorageProvider . PROPERTIES_CONTENT_CHECKSUM ) ; return compareChecksum ( providerChecksum , spaceId , contentId , checksum ) ; }
Determines if the checksum for a particular piece of content stored in a StorageProvider matches the expected checksum value .
21,027
public static String compareChecksum ( String providerChecksum , String spaceId , String contentId , String checksum ) throws ChecksumMismatchException { if ( ! providerChecksum . equals ( checksum ) ) { String err = "Content " + contentId + " was added to space " + spaceId + " but the checksum, either provided or computed " + "enroute, (" + checksum + ") does not match the checksum " + "computed by the storage provider (" + providerChecksum + "). This content should be retransmitted." ; log . warn ( err ) ; throw new ChecksumMismatchException ( err , NO_RETRY ) ; } return providerChecksum ; }
Determines if two checksum values are equal
21,028
public static boolean contains ( Iterator < String > iterator , String value ) { if ( iterator == null || value == null ) { return false ; } while ( iterator . hasNext ( ) ) { if ( value . equals ( iterator . next ( ) ) ) { return true ; } } return false ; }
Determines if a String value is included in a Iterated list . The iteration is only run as far as necessary to determine if the value is included in the underlying list .
21,029
public static long count ( Iterator < String > iterator ) { if ( iterator == null ) { return 0 ; } long count = 0 ; while ( iterator . hasNext ( ) ) { ++ count ; iterator . next ( ) ; } return count ; }
Determines the number of elements in an iteration .
21,030
public static List < String > getList ( Iterator < String > iterator ) { List < String > contents = new ArrayList < String > ( ) ; while ( iterator . hasNext ( ) ) { contents . add ( iterator . next ( ) ) ; } return contents ; }
Creates a list of all of the items in an iteration . Be wary of using this for Iterations of very long lists .
21,031
public static Map < String , String > createContentProperties ( String absolutePath , String creator ) { Map < String , String > props = new HashMap < String , String > ( ) ; if ( creator != null && creator . trim ( ) . length ( ) > 0 ) { props . put ( StorageProvider . PROPERTIES_CONTENT_CREATOR , creator ) ; } props . put ( StorageProvider . PROPERTIES_CONTENT_FILE_PATH , absolutePath ) ; try { Path path = FileSystems . getDefault ( ) . getPath ( absolutePath ) ; BasicFileAttributes bfa = Files . readAttributes ( path , BasicFileAttributes . class ) ; String creationDate = DateUtil . convertToStringLong ( bfa . creationTime ( ) . toMillis ( ) ) ; props . put ( StorageProvider . PROPERTIES_CONTENT_FILE_CREATED , creationDate ) ; String lastAccessed = DateUtil . convertToStringLong ( bfa . lastAccessTime ( ) . toMillis ( ) ) ; props . put ( StorageProvider . PROPERTIES_CONTENT_FILE_LAST_ACCESSED , lastAccessed ) ; String modified = DateUtil . convertToStringLong ( bfa . lastModifiedTime ( ) . toMillis ( ) ) ; props . put ( StorageProvider . PROPERTIES_CONTENT_FILE_MODIFIED , modified ) ; } catch ( IOException ex ) { log . error ( "Failed to read basic file attributes from " + absolutePath + ": " + ex . getMessage ( ) , ex ) ; } return props ; }
Generates a map of all client - side default content properties to be added with new content .
21,032
public static Map < String , String > removeCalculatedProperties ( Map < String , String > contentProperties ) { if ( contentProperties != null ) { contentProperties = new HashMap < > ( contentProperties ) ; contentProperties . remove ( StorageProvider . PROPERTIES_CONTENT_MD5 ) ; contentProperties . remove ( StorageProvider . PROPERTIES_CONTENT_CHECKSUM ) ; contentProperties . remove ( StorageProvider . PROPERTIES_CONTENT_MODIFIED ) ; contentProperties . remove ( StorageProvider . PROPERTIES_CONTENT_SIZE ) ; } return contentProperties ; }
Returns a new map with the calculated properties removed . If null null is returned .
21,033
public void setSpaceLifecycle ( String bucketName , BucketLifecycleConfiguration config ) { boolean success = false ; int maxLoops = 6 ; for ( int loops = 0 ; ! success && loops < maxLoops ; loops ++ ) { try { s3Client . deleteBucketLifecycleConfiguration ( bucketName ) ; s3Client . setBucketLifecycleConfiguration ( bucketName , config ) ; success = true ; } catch ( NotFoundException e ) { success = false ; wait ( loops ) ; } } if ( ! success ) { throw new StorageException ( "Lifecycle policy for bucket " + bucketName + " could not be applied. The space cannot be found." ) ; } }
Sets a lifecycle policy on an S3 bucket based on the given configuration
21,034
public String addHiddenContent ( String spaceId , String contentId , String contentMimeType , InputStream content ) { log . debug ( "addHiddenContent(" + spaceId + ", " + contentId + ", " + contentMimeType + ")" ) ; String bucketName = getBucketName ( spaceId ) ; if ( contentMimeType == null || contentMimeType . equals ( "" ) ) { contentMimeType = DEFAULT_MIMETYPE ; } ObjectMetadata objMetadata = new ObjectMetadata ( ) ; objMetadata . setContentType ( contentMimeType ) ; PutObjectRequest putRequest = new PutObjectRequest ( bucketName , contentId , content , objMetadata ) ; putRequest . setStorageClass ( DEFAULT_STORAGE_CLASS ) ; putRequest . setCannedAcl ( CannedAccessControlList . Private ) ; try { PutObjectResult putResult = s3Client . putObject ( putRequest ) ; return putResult . getETag ( ) ; } catch ( AmazonClientException e ) { String err = "Could not add content " + contentId + " with type " + contentMimeType + " to S3 bucket " + bucketName + " due to error: " + e . getMessage ( ) ; throw new StorageException ( err , e , NO_RETRY ) ; } }
Adds content to a hidden space .
21,035
public String getBucketName ( String spaceId ) { List < Bucket > buckets = listAllBuckets ( ) ; for ( Bucket bucket : buckets ) { String bucketName = bucket . getName ( ) ; spaceId = spaceId . replace ( "." , "[.]" ) ; if ( bucketName . matches ( "(" + HIDDEN_SPACE_PREFIX + ")?[\\w]{20}[.]" + spaceId ) ) { return bucketName ; } } throw new NotFoundException ( "No S3 bucket found matching spaceID: " + spaceId ) ; }
Gets the name of an existing bucket based on a space ID . If no bucket with this spaceId exists throws a NotFoundException
21,036
protected String getSpaceId ( String bucketName ) { String spaceId = bucketName ; if ( isSpace ( bucketName ) ) { spaceId = spaceId . substring ( accessKeyId . length ( ) + 1 ) ; } return spaceId ; }
Converts a bucket name into what could be passed in as a space ID .
21,037
protected boolean isSpace ( String bucketName ) { boolean isSpace = false ; if ( bucketName . matches ( "[\\w]{20}[.].*" ) ) { isSpace = true ; } return isSpace ; }
Determines if an S3 bucket is a DuraCloud space
21,038
public void flush ( ) throws IOException { checkWriter ( ) ; writer . flush ( ) ; try { contentStoreUtil . storeContentStream ( tempFile , spaceId , contentId , mimetype ) ; } catch ( DuraCloudRuntimeException ex ) { throw new IOException ( "flush failed: " + ex . getMessage ( ) , ex ) ; } }
Writes the tempfile to durastore .
21,039
protected void addContentFrom ( File baseDir , String destSpaceId ) { Collection < File > files = listFiles ( baseDir , options . getFileFilter ( ) , options . getDirFilter ( ) ) ; for ( File file : files ) { try { doAddContent ( baseDir , destSpaceId , file ) ; } catch ( Exception e ) { StringBuilder sb = new StringBuilder ( "Error: " ) ; sb . append ( "Unable to addContentFrom [" ) ; sb . append ( baseDir ) ; sb . append ( ", " ) ; sb . append ( destSpaceId ) ; sb . append ( "] : " ) ; sb . append ( e . getMessage ( ) ) ; sb . append ( "\n" ) ; sb . append ( ExceptionUtil . getStackTraceAsString ( e ) ) ; log . error ( sb . toString ( ) ) ; } } }
This method loops the arg baseDir and pushes the found content to the arg destSpace .
21,040
private String getContentId ( File baseDir , File file ) { String filePath = file . getPath ( ) ; String basePath = baseDir . getPath ( ) ; int index = filePath . indexOf ( basePath ) ; if ( index == - 1 ) { StringBuilder sb = new StringBuilder ( "Invalid basePath for file: " ) ; sb . append ( "b: '" + basePath + "', " ) ; sb . append ( "f: '" + filePath + "'" ) ; throw new DuraCloudRuntimeException ( sb . toString ( ) ) ; } String contentId = filePath . substring ( index + basePath . length ( ) ) ; if ( contentId . startsWith ( File . separator ) ) { contentId = contentId . substring ( 1 , contentId . length ( ) ) ; } contentId = contentId . replaceAll ( "\\\\" , "/" ) ; return contentId ; }
This method defines the returned contentId as the path of the arg file minus the path of the arg baseDir in which the file was found .
21,041
public Response getStores ( ) { String msg = "getting stores." ; try { return doGetStores ( msg ) ; } catch ( StorageException se ) { return responseBad ( msg , se ) ; } catch ( Exception e ) { return responseBad ( msg , e ) ; } }
Provides a listing of all available storage provider accounts
21,042
public static void validateSpaceId ( String spaceID ) throws InvalidIdException { if ( spaceID == null || spaceID . trim ( ) . length ( ) < 3 || spaceID . trim ( ) . length ( ) > 42 ) { String err = "Space ID must be between 3 and 42 characters long" ; throw new InvalidIdException ( err ) ; } if ( ! spaceID . matches ( "[a-z0-9.-]*" ) ) { String err = "Only lowercase letters, numbers, periods, " + "and dashes may be used in a Space ID" ; throw new InvalidIdException ( err ) ; } if ( spaceID . startsWith ( "." ) || spaceID . startsWith ( "-" ) ) { String err = "A Space ID must begin with a lowercase letter." ; throw new InvalidIdException ( err ) ; } if ( spaceID . matches ( "[0-9]+[a-z0-9.-]*" ) ) { String err = "A Space ID must begin with a lowercase letter." ; throw new InvalidIdException ( err ) ; } if ( spaceID . matches ( "[a-z0-9.-]*[.][0-9]+[a-z0-9-]*" ) ) { String err = "The last period in a Space ID may not be " + "immediately followed by a number." ; throw new InvalidIdException ( err ) ; } if ( spaceID . endsWith ( "-" ) ) { String err = "A Space ID must end with a lowercase letter, " + "number, or period" ; throw new InvalidIdException ( err ) ; } if ( spaceID . contains ( ".." ) || spaceID . contains ( "-." ) || spaceID . contains ( ".-" ) ) { String err = "A Space ID must not contain '..' '-.' or '.-'" ; throw new InvalidIdException ( err ) ; } if ( spaceID . matches ( "[0-9]+.[0-9]+.[0-9]+.[0-9]+" ) ) { String err = "A Space ID must not be formatted as an IP address" ; throw new InvalidIdException ( err ) ; } }
Determines if the ID of the space to be added is valid
21,043
public static void validateContentId ( String contentID ) throws InvalidIdException { if ( contentID == null ) { String err = "Content ID must be at least 1 character long" ; throw new InvalidIdException ( err ) ; } if ( contentID . contains ( "?" ) ) { String err = "Content ID may not include the '?' character" ; throw new InvalidIdException ( err ) ; } if ( contentID . contains ( "\\" ) ) { String err = "Content ID may not include the '\\' character" ; throw new InvalidIdException ( err ) ; } int utfLength ; int urlLength ; try { utfLength = contentID . getBytes ( "UTF-8" ) . length ; String urlEncoded = URLEncoder . encode ( contentID , "UTF-8" ) ; urlLength = urlEncoded . getBytes ( "UTF-8" ) . length ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } if ( utfLength > 1024 || urlLength > 1024 ) { String err = "Content ID must <= 1024 bytes after URL and UTF-8 encoding" ; throw new InvalidIdException ( err ) ; } }
Determines if the ID of the content to be added is valid
21,044
public static CompleteRestoreBridgeResult deserialize ( String json ) { JaxbJsonSerializer < CompleteRestoreBridgeResult > serializer = new JaxbJsonSerializer < > ( CompleteRestoreBridgeResult . class ) ; try { return serializer . deserialize ( json ) ; } catch ( IOException e ) { throw new SnapshotDataException ( "Unable to create result due to: " + e . getMessage ( ) ) ; } }
Creates a deserialized version of bridge parameters
21,045
public static String appendRedirectMessage ( String outcomeUrl , Message message , HttpServletRequest request ) { String key = addMessageToRedirect ( message , request ) ; if ( ! outcomeUrl . contains ( "?" ) ) { outcomeUrl += "?" ; } else { outcomeUrl += "&" ; } int index = outcomeUrl . indexOf ( REDIRECT_KEY ) ; if ( index > 0 ) { int start = index + REDIRECT_KEY . length ( ) + 1 ; int end = outcomeUrl . indexOf ( "=" , start ) ; if ( end < 0 ) { end = outcomeUrl . length ( ) ; } String value = outcomeUrl . substring ( start , end ) ; outcomeUrl = outcomeUrl . replace ( REDIRECT_KEY + "=" + value , REDIRECT_KEY + "=" + key ) ; } else { outcomeUrl += REDIRECT_KEY + "=" + key ; } return outcomeUrl ; }
adds a redirect message and appends the redirect key to the outcomeUrl . If a redirect key already exists it is replaced . replace redirect key if it exists in the outcomeUrl .
21,046
public String serialize ( ) { JaxbJsonSerializer < SetStoragePolicyTaskParameters > serializer = new JaxbJsonSerializer < > ( SetStoragePolicyTaskParameters . class ) ; try { return serializer . serialize ( this ) ; } catch ( IOException e ) { throw new TaskDataException ( "Unable to create task parameters due to: " + e . getMessage ( ) ) ; } }
Creates a serialized version of task parameters
21,047
public void startMonitor ( ) { logger . info ( "Starting Directory Update Monitor" ) ; try { monitor . start ( ) ; } catch ( IllegalStateException e ) { logger . info ( "File alteration monitor is already started: " + e . getMessage ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } }
Starts the monitor watching for updates .
21,048
public void stopMonitor ( ) { logger . info ( "Stopping Directory Update Monitor" ) ; try { monitor . stop ( ) ; } catch ( IllegalStateException e ) { logger . info ( "File alteration monitor is already stopped: " + e . getMessage ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } }
Stops the monitor no further updates will be reported .
21,049
protected Map < String , AclType > getSpaceACLs ( HttpServletRequest request ) { String storeId = getStoreId ( request ) ; String spaceId = getSpaceId ( request ) ; return getSpaceACLs ( storeId , spaceId ) ; }
This method returns the ACLs of the requested space or an empty - map if there is an error or for certain keyword spaces or null if the space does not exist .
21,050
public String encrypt ( String toEncrypt ) throws DuraCloudRuntimeException { try { byte [ ] input = toEncrypt . getBytes ( "UTF-8" ) ; cipher . init ( Cipher . ENCRYPT_MODE , key ) ; byte [ ] cipherText = cipher . doFinal ( input ) ; return encodeBytes ( cipherText ) ; } catch ( Exception e ) { throw new DuraCloudRuntimeException ( e ) ; } }
Provides basic encryption on a String .
21,051
private String encodeBytes ( byte [ ] cipherText ) { StringBuffer cipherStringBuffer = new StringBuffer ( ) ; for ( int i = 0 ; i < cipherText . length ; i ++ ) { byte b = cipherText [ i ] ; cipherStringBuffer . append ( Byte . toString ( b ) + ":" ) ; } return cipherStringBuffer . toString ( ) ; }
Encodes a byte array as a String without using a charset to ensure that the exact bytes can be retrieved on decode .
21,052
private byte [ ] decodeBytes ( String cipherString ) { String [ ] cipherStringBytes = cipherString . split ( ":" ) ; byte [ ] cipherBytes = new byte [ cipherStringBytes . length ] ; for ( int i = 0 ; i < cipherStringBytes . length ; i ++ ) { cipherBytes [ i ] = Byte . parseByte ( cipherStringBytes [ i ] ) ; } return cipherBytes ; }
Decodes a String back into a byte array .
21,053
public static void main ( String [ ] args ) throws Exception { EncryptionUtil util = new EncryptionUtil ( ) ; System . out . println ( "Enter text to encrypt: " ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( System . in ) ) ; String input = reader . readLine ( ) ; if ( null != input && ! "" . equals ( input ) ) { System . out . println ( "'" + util . encrypt ( input ) + "'" ) ; } }
This main prompts the user to input a string to be encrypted .
21,054
public int vote ( Authentication auth , Object resource , Collection config ) { String label = "UserIpLimitsAccessVoter" ; if ( resource != null && ! supports ( resource . getClass ( ) ) ) { log . debug ( debugText ( label , auth , config , resource , ACCESS_ABSTAIN ) ) ; return ACCESS_ABSTAIN ; } FilterInvocation invocation = ( FilterInvocation ) resource ; HttpServletRequest httpRequest = invocation . getHttpRequest ( ) ; if ( null == httpRequest ) { log . debug ( debugText ( label , auth , config , resource , ACCESS_DENIED ) ) ; return ACCESS_DENIED ; } String userIpLimits = getUserIpLimits ( auth ) ; if ( null != userIpLimits && ! userIpLimits . equals ( "" ) ) { String requestIp = httpRequest . getRemoteAddr ( ) ; String [ ] ipLimits = userIpLimits . split ( ";" ) ; for ( String ipLimit : ipLimits ) { if ( ipInRange ( requestIp , ipLimit ) ) { log . debug ( debugText ( label , auth , config , resource , ACCESS_GRANTED ) ) ; return ACCESS_GRANTED ; } } log . debug ( debugText ( label , auth , config , resource , ACCESS_DENIED ) ) ; return ACCESS_DENIED ; } else { log . debug ( debugText ( label , auth , config , resource , ACCESS_ABSTAIN ) ) ; return ACCESS_ABSTAIN ; } }
This method checks the IP limits of the principal and denys access if those limits exist and the request is coming from outside the specified range .
21,055
protected String getUserIpLimits ( Authentication auth ) { Object principal = auth . getPrincipal ( ) ; if ( principal instanceof DuracloudUserDetails ) { DuracloudUserDetails userDetails = ( DuracloudUserDetails ) principal ; return userDetails . getIpLimits ( ) ; } else { return null ; } }
Retrieves the ip limits defined for a given user
21,056
protected boolean ipInRange ( String ipAddress , String range ) { IpAddressMatcher addressMatcher = new IpAddressMatcher ( range ) ; return addressMatcher . matches ( ipAddress ) ; }
Determines if a given IP address is in the given IP range .
21,057
public void readTask ( Task task ) { Map < String , String > props = task . getProperties ( ) ; setAccount ( props . get ( ACCOUNT_PROP ) ) ; setStoreId ( props . get ( STORE_ID_PROP ) ) ; setSpaceId ( props . get ( SPACE_ID_PROP ) ) ; this . attempts = task . getAttempts ( ) ; }
Reads the information stored in a Task and sets data in the SpaceCentricTypedTask
21,058
public Task writeTask ( ) { Task task = new Task ( ) ; addProperty ( task , ACCOUNT_PROP , getAccount ( ) ) ; addProperty ( task , STORE_ID_PROP , getStoreId ( ) ) ; addProperty ( task , SPACE_ID_PROP , getSpaceId ( ) ) ; return task ; }
Writes all of the information in the SpaceCentricTypedTask into a Task
21,059
public String performTask ( String taskParameters ) { GetSignedUrlTaskParameters taskParams = GetSignedUrlTaskParameters . deserialize ( taskParameters ) ; String spaceId = taskParams . getSpaceId ( ) ; String contentId = taskParams . getContentId ( ) ; String resourcePrefix = taskParams . getResourcePrefix ( ) ; String ipAddress = taskParams . getIpAddress ( ) ; int minutesToExpire = taskParams . getMinutesToExpire ( ) ; if ( minutesToExpire <= 0 ) { minutesToExpire = DEFAULT_MINUTES_TO_EXPIRE ; } log . info ( "Performing " + TASK_NAME + " task with parameters: spaceId=" + spaceId + ", contentId=" + contentId + ", resourcePrefix=" + resourcePrefix + ", minutesToExpire=" + minutesToExpire + ", ipAddress=" + ipAddress ) ; String bucketName = unwrappedS3Provider . getBucketName ( spaceId ) ; GetSignedUrlTaskResult taskResult = new GetSignedUrlTaskResult ( ) ; checkThatStreamingServiceIsEnabled ( spaceId , TASK_NAME ) ; StreamingDistributionSummary existingDist = getExistingDistribution ( bucketName ) ; if ( null == existingDist ) { throw new UnsupportedTaskException ( TASK_NAME , "The " + TASK_NAME + " task can only be used after a space " + "has been configured to enable secure streaming. Use " + StorageTaskConstants . ENABLE_STREAMING_TASK_NAME + " to enable secure streaming on this space." ) ; } String domainName = existingDist . getDomainName ( ) ; if ( existingDist . getTrustedSigners ( ) . getItems ( ) . isEmpty ( ) ) { throw new UnsupportedTaskException ( TASK_NAME , "The " + TASK_NAME + " task cannot be used to request a " + "stream from an open distribution. Use " + StorageTaskConstants . GET_URL_TASK_NAME + " instead." ) ; } if ( null == resourcePrefix ) { resourcePrefix = "" ; } Calendar expireCalendar = Calendar . getInstance ( ) ; expireCalendar . add ( Calendar . MINUTE , minutesToExpire ) ; try { File cfKeyPathFile = getCfKeyPathFile ( this . cfKeyPath ) ; String signedUrl = CloudFrontUrlSigner . getSignedURLWithCustomPolicy ( SignerUtils . Protocol . rtmp , domainName , cfKeyPathFile , contentId , cfKeyId , expireCalendar . getTime ( ) , null , ipAddress ) ; taskResult . setSignedUrl ( "rtmp://" + domainName + "/cfx/st/" + resourcePrefix + signedUrl ) ; } catch ( InvalidKeySpecException | IOException e ) { throw new RuntimeException ( "Error encountered attempting to sign URL for" + " task " + TASK_NAME + ": " + e . getMessage ( ) , e ) ; } String toReturn = taskResult . serialize ( ) ; log . info ( "Result of " + TASK_NAME + " task: " + toReturn ) ; return toReturn ; }
Build secure URL
21,060
public String serialize ( ) { JaxbJsonSerializer < CreateSnapshotBridgeParameters > serializer = new JaxbJsonSerializer < > ( CreateSnapshotBridgeParameters . class ) ; try { return serializer . serialize ( this ) ; } catch ( IOException e ) { throw new SnapshotDataException ( "Unable to create task result due to: " + e . getMessage ( ) ) ; } }
Creates a serialized version of bridge parameters
21,061
public void put ( Set < Task > tasks ) { String msgBody = null ; SendMessageBatchRequestEntry msgEntry = null ; Set < SendMessageBatchRequestEntry > msgEntries = new HashSet < > ( ) ; for ( Task task : tasks ) { msgBody = unmarshallTask ( task ) ; msgEntry = new SendMessageBatchRequestEntry ( ) . withMessageBody ( msgBody ) . withId ( msgEntries . size ( ) + "" ) ; msgEntries . add ( msgEntry ) ; if ( msgEntries . size ( ) == 10 ) { this . sendBatchMessages ( msgEntries ) ; msgEntries . clear ( ) ; } } if ( ! msgEntries . isEmpty ( ) ) { this . sendBatchMessages ( msgEntries ) ; } }
Puts multiple tasks on the queue using batch puts . The tasks argument can contain more than 10 Tasks in that case there will be multiple SQS batch send requests made each containing up to 10 messages .
21,062
public SyncToolConfig retrievePrevConfig ( File backupDir ) { File prevConfigBackupFile = new File ( backupDir , PREV_BACKUP_FILE_NAME ) ; if ( prevConfigBackupFile . exists ( ) ) { String [ ] prevConfigArgs = retrieveConfig ( prevConfigBackupFile ) ; try { return processStandardOptions ( prevConfigArgs , false ) ; } catch ( ParseException e ) { return null ; } } else { return null ; } }
Retrieves the configuration of the previous run of the Sync Tool . If there was no previous run the backup file cannot be found or the backup file cannot be read returns null otherwise returns the parsed configuration
21,063
public static String createNewBucketName ( String accessKeyId , String spaceId ) { String bucketName = accessKeyId + "." + spaceId ; bucketName = bucketName . toLowerCase ( ) ; bucketName = bucketName . replaceAll ( "[^a-z0-9-.]" , "-" ) ; while ( bucketName . contains ( "--" ) || bucketName . contains ( ".." ) || bucketName . contains ( "-." ) || bucketName . contains ( ".-" ) ) { bucketName = bucketName . replaceAll ( "[-]+" , "-" ) ; bucketName = bucketName . replaceAll ( "[.]+" , "." ) ; bucketName = bucketName . replaceAll ( "-[.]" , "-" ) ; bucketName = bucketName . replaceAll ( "[.]-" , "." ) ; } if ( bucketName . length ( ) > 63 ) { bucketName = bucketName . substring ( 0 , 63 ) ; } while ( bucketName . endsWith ( "-" ) || bucketName . endsWith ( "." ) ) { bucketName = bucketName . substring ( 0 , bucketName . length ( ) - 1 ) ; } return bucketName ; }
Converts a provided space ID into a valid and unique S3 bucket name .
21,064
public int vote ( Authentication authentication , Object resource , Collection < ConfigAttribute > config ) { int decision = super . vote ( authentication , resource , config ) ; log . debug ( VoterUtil . debugText ( "RoleVoterImpl" , authentication , config , resource , decision ) ) ; return decision ; }
This method is a pass - through for Spring - RoleVoter .
21,065
public void initialize ( List < StorageAccount > accts ) throws StorageException { storageAccounts = new HashMap < > ( ) ; for ( StorageAccount acct : accts ) { storageAccounts . put ( acct . getId ( ) , acct ) ; if ( acct . isPrimary ( ) ) { primaryStorageProviderId = acct . getId ( ) ; } } if ( primaryStorageProviderId == null ) { primaryStorageProviderId = accts . get ( 0 ) . getId ( ) ; } }
Initializes the account manager based on provided accounts
21,066
@ RequestMapping ( value = "/spaces/snapshots/{storeId}/{snapshotId}/restore-space-id" , method = RequestMethod . GET ) public String restoreSpaceId ( HttpServletRequest request , @ PathVariable ( "storeId" ) String storeId , @ PathVariable ( "snapshotId" ) String snapshotId ) throws Exception { ContentStore contentStore = getContentStore ( storeId ) ; String spaceId = SnapshotIdentifier . parseSnapshotId ( snapshotId ) . getRestoreSpaceId ( ) ; if ( contentStore . spaceExists ( spaceId ) ) { return "{ \"spaceId\": \"" + spaceId + "\"," + "\"storeId\": \"" + storeId + "\"}" ; } else { return "{}" ; } }
Returns the name of the restore space if it exists associated with a snapshot
21,067
protected < T > T getValueFromJson ( String json , String propName ) throws IOException { return ( T ) jsonStringToMap ( json ) . get ( propName ) ; }
A helper method that takes a json string and extracts the value of the specified property .
21,068
protected Map jsonStringToMap ( String json ) throws IOException { return new JaxbJsonSerializer < HashMap > ( HashMap . class ) . deserialize ( json ) ; }
A helper method that converts a json string into a map object .
21,069
public int getOptimalThreads ( SyncOptimizeConfig syncOptConfig ) throws IOException { File tempDir = FileUtils . getTempDirectory ( ) ; this . dataDir = new File ( tempDir , DATA_DIR_NAME ) ; this . workDir = new File ( tempDir , WORK_DIR_NAME ) ; String prefix = "sync-optimize/" + InetAddress . getLocalHost ( ) . getHostName ( ) + "/" ; TestDataHandler dataHandler = new TestDataHandler ( ) ; dataHandler . createDirectories ( dataDir , workDir ) ; dataHandler . createTestData ( dataDir , syncOptConfig . getNumFiles ( ) , syncOptConfig . getSizeFiles ( ) ) ; SyncTestManager testManager = new SyncTestManager ( syncOptConfig , dataDir , workDir , syncTestStatus , prefix ) ; int optimalThreads = testManager . runTest ( ) ; dataHandler . removeDirectories ( dataDir , workDir ) ; return optimalThreads ; }
Determines the optimal SyncTool thread count value . This value is discovered by running a series of timed tests and returning the fastest performer . The results of these tests depend highly on the machine they are run on and the capacity of the network available to that machine .
21,070
public static void main ( String [ ] args ) throws Exception { SyncOptimizeDriver syncOptDriver = new SyncOptimizeDriver ( true ) ; SyncOptimizeConfig syncOptConfig = syncOptDriver . processCommandLineArgs ( args ) ; System . out . println ( "### Running Sync Thread Optimizer with configuration: " + syncOptConfig . getPrintableConfig ( ) ) ; int optimalThreads = syncOptDriver . getOptimalThreads ( syncOptConfig ) ; System . out . println ( "### Sync Thread Optimizer complete. Optimal thread " + "count for running the DuraCloud SyncTool on " + "this machine is: " + optimalThreads ) ; }
Picks up the command line parameters and kicks off the optimization tests
21,071
public static CancelSnapshotBridgeResult deserialize ( String bridgeResult ) { JaxbJsonSerializer < CancelSnapshotBridgeResult > serializer = new JaxbJsonSerializer < > ( CancelSnapshotBridgeResult . class ) ; try { return serializer . deserialize ( bridgeResult ) ; } catch ( IOException e ) { throw new SnapshotDataException ( "Unable to deserialize result due to: " + e . getMessage ( ) ) ; } }
Parses properties from bridge result string
21,072
public static String serializeMap ( Map < String , String > map ) { if ( map == null ) { map = new HashMap < String , String > ( ) ; } XStream xstream = new XStream ( new DomDriver ( ) ) ; return xstream . toXML ( map ) ; }
Serializes a Map to XML . If the map is either empty or null the XML will indicate an empty map .
21,073
@ SuppressWarnings ( "unchecked" ) public static Map < String , String > deserializeMap ( String map ) { if ( map == null || map . equals ( "" ) ) { return new HashMap < String , String > ( ) ; } else { XStream xstream = new XStream ( new DomDriver ( ) ) ; return ( Map < String , String > ) xstream . fromXML ( map ) ; } }
DeSerializes XML into a Map . If the XML is either empty or null an empty Map is returned .
21,074
@ SuppressWarnings ( "unchecked" ) public static List < String > deserializeList ( String list ) { if ( list == null || list . equals ( "" ) ) { return new ArrayList < String > ( ) ; } XStream xstream = new XStream ( new DomDriver ( ) ) ; return ( List < String > ) xstream . fromXML ( list ) ; }
DeSerializes XML into a List of Strings . If the XML is either empty or null an empty List is returned .
21,075
@ SuppressWarnings ( "unchecked" ) public static Set < String > deserializeSet ( String set ) { if ( set == null || set . equals ( "" ) ) { return new HashSet < String > ( ) ; } XStream xstream = new XStream ( new DomDriver ( ) ) ; return ( Set < String > ) xstream . fromXML ( set ) ; }
DeSerializes XML into a Set of Strings . If the XML is either empty or null an empty List is returned .
21,076
public static DigestInputStream wrapStream ( InputStream inStream , Algorithm algorithm ) { MessageDigest streamDigest = null ; try { streamDigest = MessageDigest . getInstance ( algorithm . toString ( ) ) ; } catch ( NoSuchAlgorithmException e ) { String error = "Could not create a MessageDigest because the " + "required algorithm " + algorithm . toString ( ) + " is not supported." ; throw new RuntimeException ( error ) ; } DigestInputStream wrappedContent = new DigestInputStream ( inStream , streamDigest ) ; return wrappedContent ; }
Wraps an InputStream with a DigestInputStream in order to compute a checksum as the stream is being read .
21,077
public static String getChecksum ( DigestInputStream digestStream ) { MessageDigest digest = digestStream . getMessageDigest ( ) ; return checksumBytesToString ( digest . digest ( ) ) ; }
Determines the checksum value of a DigestInputStream s underlying stream after the stream has been read .
21,078
public static String checksumBytesToString ( byte [ ] digestBytes ) { StringBuffer hexString = new StringBuffer ( ) ; for ( int i = 0 ; i < digestBytes . length ; i ++ ) { String hex = Integer . toHexString ( 0xff & digestBytes [ i ] ) ; if ( hex . length ( ) == 1 ) { hexString . append ( '0' ) ; } hexString . append ( hex ) ; } return hexString . toString ( ) ; }
Converts a message digest byte array into a String based on the hex values appearing in the array .
21,079
public static ChunksManifest createManifestFrom ( InputStream xml ) { try { ChunksManifestDocument doc = ChunksManifestDocument . Factory . parse ( xml ) ; return ManifestElementReader . createManifestFrom ( doc ) ; } catch ( XmlException e ) { throw new DuraCloudRuntimeException ( e ) ; } catch ( IOException e ) { throw new DuraCloudRuntimeException ( e ) ; } }
This method binds a ChunksManifest object to the content of the arg xml .
21,080
public static String createDocumentFrom ( ChunksManifestBean manifest ) { ChunksManifestDocument doc = ChunksManifestDocument . Factory . newInstance ( ) ; if ( null != manifest ) { ChunksManifestType manifestType = ManifestElementWriter . createChunksManifestElementFrom ( manifest ) ; doc . setChunksManifest ( manifestType ) ; } return docToString ( doc ) ; }
This method serializes the arg ChunksManifest object into an xml document .
21,081
protected void storeSnapshotProps ( String spaceId , String serializedProps ) { InputStream propsStream ; try { propsStream = IOUtil . writeStringToStream ( serializedProps ) ; } catch ( IOException e ) { throw new TaskException ( "Unable to build stream from serialized " + "snapshot properties due to: " + e . getMessage ( ) ) ; } ChecksumUtil checksumUtil = new ChecksumUtil ( ChecksumUtil . Algorithm . MD5 ) ; String propsChecksum = checksumUtil . generateChecksum ( serializedProps ) ; snapshotProvider . addContent ( spaceId , Constants . SNAPSHOT_PROPS_FILENAME , "text/x-java-properties" , null , serializedProps . getBytes ( StandardCharsets . UTF_8 ) . length , propsChecksum , propsStream ) ; }
Stores a set of snapshot properties in the given space as a properties file .
21,082
protected String getSnapshotIdFromProperties ( String spaceId ) { Properties props = new Properties ( ) ; try ( InputStream is = this . snapshotProvider . getContent ( spaceId , Constants . SNAPSHOT_PROPS_FILENAME ) . getContentStream ( ) ) { props . load ( is ) ; return props . getProperty ( Constants . SNAPSHOT_ID_PROP ) ; } catch ( NotFoundException ex ) { return null ; } catch ( Exception e ) { throw new TaskException ( MessageFormat . format ( "Call to create snapshot failed, unable to determine existence of " + "snapshot properties file in {0}. Error: {1}" , spaceId , e . getMessage ( ) ) ) ; } }
Returns snapshot from the snapshot properties file if it exists
21,083
protected boolean snapshotPropsPresentInSpace ( String spaceId ) { try { snapshotProvider . getContentProperties ( spaceId , Constants . SNAPSHOT_PROPS_FILENAME ) ; return true ; } catch ( NotFoundException ex ) { return false ; } }
Checks if the snapshot props file is in the space .
21,084
public static ChunksManifestType createChunksManifestElementFrom ( ChunksManifestBean manifest ) { ChunksManifestType manifestType = ChunksManifestType . Factory . newInstance ( ) ; populateElementFromObject ( manifestType , manifest ) ; return manifestType ; }
This method serializes a ChunksManifest object into a ChunksManifest xml element .
21,085
public List < StorageAccount > createStorageAccountsFrom ( Element accounts ) { List < StorageAccount > accts = new ArrayList < StorageAccount > ( ) ; try { Iterator < ? > accountList = accounts . getChildren ( ) . iterator ( ) ; while ( accountList . hasNext ( ) ) { Element accountXml = ( Element ) accountList . next ( ) ; String type = accountXml . getChildText ( "storageProviderType" ) ; StorageProviderType acctType = StorageProviderType . fromString ( type ) ; StorageAccountProviderBinding providerBinding = providerBindings . get ( acctType ) ; if ( null != providerBinding ) { accts . add ( providerBinding . getAccountFromXml ( accountXml ) ) ; } else { log . warn ( "Unexpected account type: " + acctType ) ; } } if ( accts . isEmpty ( ) ) { String error = "No storage accounts could be read" ; throw new StorageException ( error ) ; } } catch ( Exception e ) { String error = "Unable to build storage account information due " + "to error: " + e . getMessage ( ) ; log . error ( error ) ; throw new StorageException ( error , e ) ; } return accts ; }
This method deserializes the provided xml into a durastore acct config object .
21,086
public List < StorageAccount > createStorageAccountsFromXml ( InputStream xml ) { try { SAXBuilder builder = new SAXBuilder ( ) ; Document doc = builder . build ( xml ) ; Element root = doc . getRootElement ( ) ; return createStorageAccountsFrom ( root ) ; } catch ( Exception e ) { String error = "Could not build storage accounts from xml " + "due to: " + e . getMessage ( ) ; throw new DuraCloudRuntimeException ( error , e ) ; } }
Creates storage accounts listing from XML which includes only the storage accounts list ( not the full DuraStore config . This is used to parse the response of the GET stores DuraStore REST call .
21,087
public String createXmlFrom ( Collection < StorageAccount > accts , boolean includeCredentials , boolean includeOptions ) { Element storageProviderAccounts = createDocumentFrom ( accts , includeCredentials , includeOptions ) ; Document document = new Document ( storageProviderAccounts ) ; XMLOutputter outputter = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; return outputter . outputString ( document ) ; }
Converts the provided DuraStore acct configuration into a stand - alone XML document . This is used for the DuraStore GET stores REST call .
21,088
protected void setSyncConfig ( SyncToolConfig syncConfig ) { this . syncConfig = syncConfig ; this . syncConfig . setVersion ( version ) ; File exclusionListFile = this . syncConfig . getExcludeList ( ) ; if ( exclusionListFile != null ) { this . fileExclusionManager = new FileExclusionManager ( exclusionListFile ) ; } else { this . fileExclusionManager = new FileExclusionManager ( ) ; } ChangedList . getInstance ( ) . setFileExclusionManager ( this . fileExclusionManager ) ; }
Sets the configuration of the sync tool .
21,089
protected boolean restartPossible ( ) { boolean restart = false ; if ( ! syncConfig . isCleanStart ( ) ) { SyncToolConfigParser syncConfigParser = new SyncToolConfigParser ( ) ; SyncToolConfig prevConfig = syncConfigParser . retrievePrevConfig ( syncConfig . getWorkDir ( ) ) ; if ( prevConfig != null ) { restart = configEquals ( syncConfig , prevConfig ) ; } } return restart ; }
Determines if this run of the sync tool will perform a restart .
21,090
protected boolean configEquals ( SyncToolConfig currConfig , SyncToolConfig prevConfig ) { boolean sameHost = currConfig . getHost ( ) . equals ( prevConfig . getHost ( ) ) ; boolean sameSpaceId = currConfig . getSpaceId ( ) . equals ( prevConfig . getSpaceId ( ) ) ; boolean sameStoreId = sameConfig ( currConfig . getStoreId ( ) , prevConfig . getStoreId ( ) ) ; boolean sameSyncDeletes = currConfig . syncDeletes ( ) == prevConfig . syncDeletes ( ) ; boolean sameContentDirs = currConfig . getContentDirs ( ) . equals ( prevConfig . getContentDirs ( ) ) ; boolean sameSyncUpdates = currConfig . isSyncUpdates ( ) == prevConfig . isSyncUpdates ( ) ; boolean sameRenameUpdates = currConfig . isRenameUpdates ( ) == prevConfig . isRenameUpdates ( ) ; boolean sameExclude = sameConfig ( currConfig . getExcludeList ( ) , prevConfig . getExcludeList ( ) ) ; boolean samePrefix = sameConfig ( currConfig . getPrefix ( ) , prevConfig . getPrefix ( ) ) ; if ( sameHost && sameSpaceId && sameStoreId && sameSyncDeletes && sameContentDirs && sameSyncUpdates && sameRenameUpdates && sameExclude && samePrefix ) { return true ; } return false ; }
Determines if two sets of configuration are equal enough to indicate that the content to be reviewed for sync operations has not changed on either the local or remote end suggesting that a re - start would be permissable .
21,091
public static < T > boolean hasDeclaredGetterAndSetter ( final Field field , Class < T > entityClazz ) { boolean hasDeclaredAccessorsMutators = true ; Method getter = retrieveGetterFrom ( entityClazz , field . getName ( ) ) ; Method setter = retrieveSetterFrom ( entityClazz , field . getName ( ) ) ; if ( getter == null || setter == null ) { hasDeclaredAccessorsMutators = false ; } return hasDeclaredAccessorsMutators ; }
This method checks if the declared Field is accessible through getters and setters methods Fields which have only setters OR getters and NOT both are discarded from serialization process
21,092
public static List < Field > getFirstLevelOfReferenceAttributes ( Class < ? > clazz ) { List < Field > references = new ArrayList < Field > ( ) ; List < String > referencedFields = ReflectionUtils . getReferencedAttributeNames ( clazz ) ; for ( String eachReference : referencedFields ) { Field referenceField = ReflectionUtils . getField ( clazz , eachReference ) ; references . add ( referenceField ) ; } return references ; }
Get only the first Level of Nested Reference Attributes from a given class
21,093
public static List < Map < String , List < String > > > splitToChunksOfSize ( Map < String , List < String > > rawMap , int chunkSize ) { List < Map < String , List < String > > > mapChunks = new LinkedList < Map < String , List < String > > > ( ) ; Set < Map . Entry < String , List < String > > > rawEntries = rawMap . entrySet ( ) ; Map < String , List < String > > currentChunk = new LinkedHashMap < String , List < String > > ( ) ; int rawEntryIndex = 0 ; for ( Map . Entry < String , List < String > > rawEntry : rawEntries ) { if ( rawEntryIndex % chunkSize == 0 ) { if ( currentChunk . size ( ) > 0 ) { mapChunks . add ( currentChunk ) ; } currentChunk = new LinkedHashMap < String , List < String > > ( ) ; } currentChunk . put ( rawEntry . getKey ( ) , rawEntry . getValue ( ) ) ; rawEntryIndex ++ ; if ( rawEntryIndex == rawMap . size ( ) ) { mapChunks . add ( currentChunk ) ; } } return mapChunks ; }
Splits rawMap s entries into a number of chunk maps of max chunkSize elements
21,094
public static String encodeByteArray ( byte [ ] byteArray ) { try { return new String ( Base64 . encodeBase64 ( byteArray ) , UTF8_ENCODING ) ; } catch ( UnsupportedEncodingException e ) { throw new MappingException ( "Could not encode byteArray to UTF8 encoding" , e ) ; } }
Encodes byteArray value into a base64 - encoded string .
21,095
protected void dropDomain ( final String domainName , final AmazonSimpleDB sdb ) { try { LOGGER . debug ( "Dropping domain: {}" , domainName ) ; DeleteDomainRequest request = new DeleteDomainRequest ( domainName ) ; sdb . deleteDomain ( request ) ; LOGGER . debug ( "Dropped domain: {}" , domainName ) ; } catch ( AmazonClientException amazonException ) { throw SimpleDbExceptionTranslator . getTranslatorInstance ( ) . translateAmazonClientException ( amazonException ) ; } }
Running the delete - domain command over & over again on the same domain or if the domain does NOT exist will NOT result in a Amazon Exception
21,096
public T populateDomainItem ( SimpleDbEntityInformation < T , ? > entityInformation , Item item ) { return buildDomainItem ( entityInformation , item ) ; }
Used during deserialization process each item being populated based on attributes retrieved from DB
21,097
public void setFieldValue ( Object fieldValue ) { ReflectionUtils . callSetter ( parentWrapper . getItem ( ) , field . getName ( ) , fieldValue ) ; }
Sets value via setter
21,098
public void visit ( final Root root ) { final Map < String , GedObject > objectMap = root . getObjects ( ) ; final Collection < GedObject > objects = objectMap . values ( ) ; for ( final GedObject gob : objects ) { gob . accept ( this ) ; } }
Visit the Root . From here we will look through the top level objects for Persons .
21,099
public boolean isType ( final String t ) { final String dt = decode ( t ) ; if ( dt . equals ( getType ( ) ) ) { return true ; } return "attribute" . equals ( getType ( ) ) && dt . equalsIgnoreCase ( getString ( ) ) ; }
Check this object against a sought after type string .