idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
21,000
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 .
54
16
21,001
protected boolean isSpace ( String bucketName ) { boolean isSpace = false ; // According to AWS docs, the access key (used in DuraCloud as a // prefix for uniqueness) is a 20 character alphanumeric sequence. if ( bucketName . matches ( "[\\w]{20}[.].*" ) ) { isSpace = true ; } return isSpace ; }
Determines if an S3 bucket is a DuraCloud space
80
14
21,002
@ Override 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 .
82
10
21,003
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 .
204
18
21,004
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 ( ) ) ; } // Replace backslash (\) with forward slash (/) for all content IDs 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 .
225
29
21,005
@ GET 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
64
10
21,006
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 ) ; } // This rule is required to conform with the spec for a URI host name, // see RFC 2396. 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
501
14
21,007
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
260
14
21,008
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
101
10
21,009
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 .
207
37
21,010
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
92
9
21,011
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 .
82
8
21,012
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 .
83
11
21,013
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 .
60
34
21,014
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 .
95
8
21,015
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 .
81
25
21,016
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 .
88
10
21,017
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 .
110
13
21,018
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 user IP limits are set, check request IP if ( null != userIpLimits && ! userIpLimits . equals ( "" ) ) { String requestIp = httpRequest . getRemoteAddr ( ) ; String [ ] ipLimits = userIpLimits . split ( ";" ) ; for ( String ipLimit : ipLimits ) { if ( ipInRange ( requestIp , ipLimit ) ) { // User's IP is within this range, grant access log . debug ( debugText ( label , auth , config , resource , ACCESS_GRANTED ) ) ; return ACCESS_GRANTED ; } } // There are IP limits, and none of them match the user's IP, deny log . debug ( debugText ( label , auth , config , resource , ACCESS_DENIED ) ) ; return ACCESS_DENIED ; } else { // No user IP limits, abstain 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 .
394
28
21,019
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
73
11
21,020
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 .
45
15
21,021
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
87
19
21,022
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
75
17
21,023
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 ) ; // Will throw if bucket does not exist String bucketName = unwrappedS3Provider . getBucketName ( spaceId ) ; GetSignedUrlTaskResult taskResult = new GetSignedUrlTaskResult ( ) ; // Ensure that streaming service is on checkThatStreamingServiceIsEnabled ( spaceId , TASK_NAME ) ; // Retrieve the existing distribution for the given space 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 ( ) ; // Verify that this is a secure distribution 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." ) ; } // Make sure resourcePrefix is a valid string if ( null == resourcePrefix ) { resourcePrefix = "" ; } // Define expiration date/time 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
769
3
21,024
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
93
9
21,025
@ Override 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 ( ) + "" ) ; // must set unique ID for each msg in the batch request msgEntries . add ( msgEntry ) ; // Can only send batch of max 10 messages in a SQS queue request if ( msgEntries . size ( ) == 10 ) { this . sendBatchMessages ( msgEntries ) ; msgEntries . clear ( ) ; // clear the already sent messages } } // After for loop check to see if there are msgs in msgEntries that // haven't been sent yet because the size never reached 10. 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 .
243
41
21,026
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
102
40
21,027
public static String createNewBucketName ( String accessKeyId , String spaceId ) { String bucketName = accessKeyId + "." + spaceId ; bucketName = bucketName . toLowerCase ( ) ; bucketName = bucketName . replaceAll ( "[^a-z0-9-.]" , "-" ) ; // Remove duplicate separators (. and -) 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 .
270
16
21,028
@ Override 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 .
67
14
21,029
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 ( ) ; } } // Make sure a primary provider is set if ( primaryStorageProviderId == null ) { primaryStorageProviderId = accts . get ( 0 ) . getId ( ) ; } }
Initializes the account manager based on provided accounts
124
9
21,030
@ RequestMapping ( value = "/spaces/snapshots/{storeId}/{snapshotId}/restore-space-id" , method = RequestMethod . GET ) @ ResponseBody 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
178
14
21,031
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 .
41
17
21,032
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 .
42
13
21,033
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 .
218
53
21,034
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
145
13
21,035
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
105
8
21,036
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 .
65
23
21,037
@ 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 .
95
22
21,038
@ 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 .
86
25
21,039
@ 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 .
86
25
21,040
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 .
125
24
21,041
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 .
45
22
21,042
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 ( ' ' ) ; } hexString . append ( hex ) ; } return hexString . toString ( ) ; }
Converts a message digest byte array into a String based on the hex values appearing in the array .
105
20
21,043
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 .
92
17
21,044
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 .
88
16
21,045
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 , // Ensures that length is based on UTF-8 encoded bytes serializedProps . getBytes ( StandardCharsets . UTF_8 ) . length , propsChecksum , propsStream ) ; }
Stores a set of snapshot properties in the given space as a properties file .
213
16
21,046
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
160
10
21,047
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 .
59
12
21,048
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 .
61
19
21,049
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 ) ; } } // Make sure that there is at least one storage account 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 .
292
18
21,050
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 .
112
40
21,051
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 .
93
31
21,052
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 .
118
9
21,053
protected boolean restartPossible ( ) { boolean restart = false ; if ( ! syncConfig . isCleanStart ( ) ) { // Determines if the configuration has been changed since the // previous run. If it has, a restart cannot occur. 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 .
118
15
21,054
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 .
320
44
21,055
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
115
34
21,056
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
103
14
21,057
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 ( ) ) { // finished iterating mapChunks . add ( currentChunk ) ; } } return mapChunks ; }
Splits rawMap s entries into a number of chunk maps of max chunkSize elements
278
17
21,058
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 .
73
13
21,059
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
114
28
21,060
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
34
16
21,061
public void setFieldValue ( Object fieldValue ) { ReflectionUtils . callSetter ( parentWrapper . getItem ( ) , field . getName ( ) , fieldValue ) ; }
Sets value via setter
41
6
21,062
@ Override 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 .
68
17
21,063
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 .
66
10
21,064
public void write ( ) { logger . info ( "writing " + users . size ( ) + " users in " + userfilename ) ; try { Backup . backup ( userfilename ) ; } catch ( IOException e ) { logger . error ( "Problem backing up old copy of user file" , e ) ; } try ( FileOutputStream fstream = new FileOutputStream ( userfilename ) ; BufferedOutputStream bstream = new BufferedOutputStream ( fstream ) ) { writeTheLines ( bstream ) ; } catch ( IOException e ) { logger . error ( "Problem writing user file" , e ) ; } }
Write the users file .
134
5
21,065
private void appendUserInfoFields ( final StringBuilder builder , final User user ) { append ( builder , user . getUsername ( ) , "," ) ; append ( builder , user . getFirstname ( ) , "," ) ; append ( builder , user . getLastname ( ) , "," ) ; append ( builder , user . getEmail ( ) , "," ) ; append ( builder , user . getPassword ( ) , "" ) ; }
Append the core fields of the user to the string .
96
12
21,066
private void append ( final StringBuilder builder , final String string , final String separator ) { if ( string != null ) { builder . append ( string ) ; } builder . append ( separator ) ; }
Append a token and separator to the builder .
43
11
21,067
private void appendRoles ( final StringBuilder builder , final User user ) { for ( final UserRoleName role : user . getRoles ( ) ) { append ( builder , "," , role . name ( ) ) ; } }
Append roles to the builder .
49
7
21,068
private RootDocument save ( final Root root ) { final RootDocumentMongo rootdoc = ( RootDocumentMongo ) toDocConverter . createGedDocument ( root ) ; try { repositoryManager . getRootDocumentRepository ( ) . save ( rootdoc ) ; } catch ( DataAccessException e ) { logger . error ( "Could not save root: " + root . getDbName ( ) , e ) ; return null ; } return rootdoc ; }
Save the root to the database .
98
7
21,069
public final void reloadAll ( ) { final List < String > list = new ArrayList <> ( ) ; for ( final RootDocument mongo : repositoryManager . getRootDocumentRepository ( ) . findAll ( ) ) { list . add ( mongo . getDbName ( ) ) ; } reset ( ) ; for ( final String dbname : list ) { loadDocument ( dbname ) ; } }
Reload all of the data sets .
86
8
21,070
public static Feature createBounds ( final String id ) { final Feature feature = new Feature ( ) ; feature . setId ( id ) ; feature . setGeometry ( new Polygon ( ) ) ; return feature ; }
Build a bounding box feature . In this case it has a name but is empty .
46
18
21,071
public static Feature createBounds ( final String id , final LngLatAlt southwest , final LngLatAlt northeast ) { final Feature feature = new Feature ( ) ; feature . setId ( id ) ; if ( northeast == null || southwest == null ) { throw new IllegalArgumentException ( "Must have a proper bounding box" ) ; } final double [ ] bbox = { southwest . getLongitude ( ) , southwest . getLatitude ( ) , northeast . getLongitude ( ) , northeast . getLatitude ( ) } ; final Polygon polygon = new Polygon ( ) ; feature . setGeometry ( polygon ) ; polygon . setBbox ( bbox ) ; final List < LngLatAlt > elements = new ArrayList <> ( 5 ) ; elements . add ( new LngLatAlt ( bbox [ SW_LNG ] , bbox [ SW_LAT ] ) ) ; elements . add ( new LngLatAlt ( bbox [ NE_LNG ] , bbox [ SW_LAT ] ) ) ; elements . add ( new LngLatAlt ( bbox [ NE_LNG ] , bbox [ NE_LAT ] ) ) ; elements . add ( new LngLatAlt ( bbox [ SW_LNG ] , bbox [ NE_LAT ] ) ) ; elements . add ( new LngLatAlt ( bbox [ SW_LNG ] , bbox [ SW_LAT ] ) ) ; polygon . add ( elements ) ; feature . setBbox ( bbox ) ; return feature ; }
Build a bounding box feature .
338
7
21,072
@ SuppressWarnings ( "unchecked" ) public final FindableDocument < ? extends GedObject , ? extends GedDocument < ? > > get ( final Class < ? extends GedObject > clazz ) { return ( FindableDocument < ? extends GedObject , ? extends GedDocument < ? > > ) classToRepoMap . get ( clazz ) ; }
Get a repository based on the class of ged object we are working with .
83
16
21,073
@ Override public void visit ( final Person person ) { visitedNameable = person ; for ( final GedObject gob : person . getAttributes ( ) ) { gob . accept ( this ) ; } }
Visit a Person . This is could be primary focus of the visitation . From here interesting information is gathered from the attributes .
43
24
21,074
@ Override public void visit ( final Submitter submitter ) { visitedNameable = submitter ; for ( final GedObject gob : submitter . getAttributes ( ) ) { gob . accept ( this ) ; } }
Visit a Submitter . This is could be primary focus of the visitation . From here interesting information is gathered from the attributes .
47
25
21,075
private Collection < PersonDocument > copy ( final Collection < PersonDocumentMongo > in ) { final List < PersonDocument > out = new ArrayList <> ( in ) ; Collections . sort ( out , new PersonDocumentComparator ( ) ) ; return out ; }
Correct the type of the collection .
55
7
21,076
public Person getChild ( ) { final Person toPerson = ( Person ) find ( getToString ( ) ) ; if ( toPerson == null ) { return new Person ( ) ; } return toPerson ; }
Get the person that this object points to . If not found return an unset Person object .
44
19
21,077
public static final String escapeString ( final String delimiter , final String input ) { final String escaped = escapeString ( input ) ; if ( escaped . isEmpty ( ) ) { return escaped ; } return delimiter + escaped ; }
Convert the string for use in HTML or URLs .
48
11
21,078
private String findCharsetInHeader ( final GedObject gob ) { for ( final GedObject hgob : gob . getAttributes ( ) ) { if ( "Character Set" . equals ( hgob . getString ( ) ) ) { return ( ( Attribute ) hgob ) . getTail ( ) ; } } return "UTF-8" ; }
Find the GEDCOM charset in the attributes of the header .
78
14
21,079
private static Family findFamily ( final Child child ) { if ( ! child . isSet ( ) ) { return new Family ( ) ; } final Family foundFamily = ( Family ) child . find ( child . getFromString ( ) ) ; if ( foundFamily == null ) { return new Family ( ) ; } return foundFamily ; }
Get the family for this child to build the navigator with .
70
13
21,080
private static Family findFamily ( final FamC famc ) { if ( ! famc . isSet ( ) ) { return new Family ( ) ; } final Family foundFamily = ( Family ) famc . find ( famc . getToString ( ) ) ; if ( foundFamily == null ) { return new Family ( ) ; } return foundFamily ; }
Get the family for this famc to build the navigator with .
75
14
21,081
private static Family findFamily ( final FamS fams ) { if ( ! fams . isSet ( ) ) { return new Family ( ) ; } final Family foundFamily = ( Family ) fams . find ( fams . getToString ( ) ) ; if ( foundFamily == null ) { return new Family ( ) ; } return foundFamily ; }
Get the family for this fams to build the navigator with .
75
14
21,082
public Person getSpouse ( final GedObject person ) { final List < Person > spouses = visitor . getSpouses ( ) ; if ( person != null && ! spouses . contains ( person ) ) { return new Person ( ) ; } for ( final Person spouse : spouses ) { if ( ! spouse . equals ( person ) ) { return spouse ; } } return new Person ( ) ; }
Get the person in this family who is the spouse of the person passed in .
82
16
21,083
protected final LocalDate createLocalDate ( final Attribute attribute ) { final GetDateVisitor visitor = new GetDateVisitor ( ) ; attribute . accept ( visitor ) ; return createLocalDate ( visitor . getDate ( ) ) ; }
Create a local date from the attribute s date .
50
10
21,084
public static LocalDate minDate ( final LocalDate date0 , final LocalDate date1 ) { if ( date1 == null ) { return date0 ; } if ( date0 == null ) { return date1 ; } if ( date1 . isBefore ( date0 ) ) { return date1 ; } else { return date0 ; } }
Return the earlier of the 2 dates . If either is null return the other .
72
16
21,085
private void initLevel0FactoryTokens ( ) { put ( "ROOT" , "Root" , AbstractGedObjectFactory . ROOT_FACTORY ) ; put ( "HEAD" , "Header" , AbstractGedObjectFactory . HEAD_FACTORY ) ; put ( "FAM" , "Family" , AbstractGedObjectFactory . FAMILY_FACTORY ) ; put ( "INDI" , "Person" , AbstractGedObjectFactory . PERSON_FACTORY ) ; put ( "NOTE" , "Note" , AbstractGedObjectFactory . NOTE_FACTORY ) ; put ( "OBJE" , "Multimedia" , AbstractGedObjectFactory . MULTIMEDIA_FACTORY ) ; put ( "SOUR" , "Source" , AbstractGedObjectFactory . SOURCE_FACTORY ) ; put ( "SUBM" , "Submitter" , AbstractGedObjectFactory . SUBMITTER_FACTORY ) ; put ( "SUBN" , "Submission" , AbstractGedObjectFactory . SUBMISSION_FACTORY ) ; put ( "TRLR" , "Trailer" , AbstractGedObjectFactory . TRAILER_FACTORY ) ; }
Method to initialize the tokens for top level items .
269
10
21,086
private void initSpecialFactoryTokens ( ) { put ( "CHIL" , "Child" , AbstractGedObjectFactory . CHILD_FACTORY ) ; put ( "CONC" , "Concatenate" , AbstractGedObjectFactory . CONCAT_FACTORY ) ; put ( "CONT" , "Continuation" , AbstractGedObjectFactory . CONTIN_FACTORY ) ; put ( "DATE" , "Date" , AbstractGedObjectFactory . DATE_FACTORY ) ; put ( "FAMC" , "Child of Family" , AbstractGedObjectFactory . FAMC_FACTORY ) ; put ( "FAMS" , "Spouse of Family" , AbstractGedObjectFactory . FAMS_FACTORY ) ; put ( "HUSB" , "Husband" , AbstractGedObjectFactory . HUSBAND_FACTORY ) ; put ( "LINK" , "Link" , AbstractGedObjectFactory . LINK_FACTORY ) ; put ( "NAME" , "Name" , AbstractGedObjectFactory . NAME_FACTORY ) ; put ( "PLAC" , "Place" , AbstractGedObjectFactory . PLACE_FACTORY ) ; put ( "PLACE" , "Place" , AbstractGedObjectFactory . PLACE_FACTORY ) ; put ( "WIFE" , "Wife" , AbstractGedObjectFactory . WIFE_FACTORY ) ; }
Method to initialize the tokens that use something other than the attribute factory .
319
14
21,087
private void analyzeFamily ( final Family family ) { Person prevChild = null ; final FamilyNavigator navigator = new FamilyNavigator ( family ) ; for ( final Person child : navigator . getChildren ( ) ) { prevChild = analyzeChild ( child , prevChild ) ; } }
Analyze the order of children in one family .
60
10
21,088
private Person analyzeChild ( final Person child , final Person prevChild ) { Person retChild = prevChild ; if ( retChild == null ) { return child ; } final LocalDate birthDate = getNearBirthEventDate ( child ) ; if ( birthDate == null ) { return retChild ; } final LocalDate prevDate = getNearBirthEventDate ( prevChild ) ; if ( prevDate == null ) { return child ; } if ( birthDate . isBefore ( prevDate ) ) { final String message = String . format ( CHILD_ORDER_FORMAT , child . getName ( ) . getString ( ) , birthDate , prevChild . getName ( ) . getString ( ) , prevDate ) ; getResult ( ) . addMismatch ( message ) ; } retChild = child ; return retChild ; }
Check the order of one child against the previous dated child .
176
12
21,089
private String getNameHtml ( final Submitter submitter ) { final GedRenderer < ? extends GedObject > renderer = new SimpleNameRenderer ( submitter . getName ( ) , submitterRenderer . getRendererFactory ( ) , submitterRenderer . getRenderingContext ( ) ) ; return renderer . getNameHtml ( ) ; }
Handle the messy getting of the name ready for HTML formatting .
86
12
21,090
@ Override public void visit ( final Attribute attribute ) { if ( "Title" . equals ( attribute . getString ( ) ) ) { titleString = attribute . getTail ( ) ; } }
Visit an Attribute . Specific Attributes provide interesting data for the Source that is the primary focus .
43
19
21,091
@ Override public void visit ( final Source source ) { titleString = source . getString ( ) ; for ( final GedObject gob : source . getAttributes ( ) ) { gob . accept ( this ) ; } }
Visit a Source . This is the primary focus of the visitation . From here interesting information is gathered .
47
20
21,092
@ Transient private Feature getLocation ( ) { if ( geometry == null ) { return null ; } final List < Feature > features = geometry . getFeatures ( ) ; if ( features == null || features . isEmpty ( ) ) { return null ; } return features . get ( 0 ) ; }
Return the location . It is in the form of a GeoJSON feature . Much of the descriptive data from Google is in the properties of that feature .
62
30
21,093
public static void backup ( final String filename ) throws IOException { final File dest = createFile ( filename ) ; if ( dest . exists ( ) ) { final File backupFile = generateBackupFilename ( filename ) ; LOGGER . debug ( "backing up file from " + filename + " to " + backupFile . getName ( ) ) ; if ( ! dest . renameTo ( backupFile ) ) { throw new IOException ( "Could not rename file from " + dest . getName ( ) + " to " + backupFile . getName ( ) ) ; } } }
Save the existing version of the file by renaming it to something ending with . &lt ; number&gt ; .
122
24
21,094
private LocalDate parentDateIncrement ( final LocalDate date ) { final int years = typicals . ageAtMarriage ( ) + typicals . gapBetweenChildren ( ) ; return plusYearsAdjustToBegin ( date , years ) ; }
Adjust the given date by age of parent at first child .
50
12
21,095
public void write ( ) { root . accept ( visitor ) ; try { Backup . backup ( root . getFilename ( ) ) ; } catch ( IOException e ) { logger . error ( "Problem backing up old copy of GEDCOM file" , e ) ; } final String filename = root . getFilename ( ) ; final String charset = new CharsetScanner ( ) . charset ( root ) ; try ( FileOutputStream fstream = new FileOutputStream ( filename ) ; BufferedOutputStream bstream = new BufferedOutputStream ( fstream ) ) { writeTheLines ( bstream , charset ) ; } catch ( IOException e ) { logger . error ( "Problem writing GEDCOM file" , e ) ; } }
Write the file as directed .
159
6
21,096
public static AbstractGedLine createGedLine ( final AbstractGedLine parent , final String inLine ) { GedLineSource sour ; if ( parent == null ) { sour = new NullSource ( ) ; } else { sour = parent . source ; } return sour . createGedLine ( parent , inLine ) ; }
Create a GedLine from the provided string .
70
10
21,097
public final AbstractGedLine readToNext ( ) throws IOException { AbstractGedLine gedLine = source . createGedLine ( this ) ; while ( true ) { if ( gedLine == null || gedLine . getLevel ( ) == - 1 ) { break ; } if ( gedLine . getLevel ( ) <= this . getLevel ( ) ) { return gedLine ; } children . add ( gedLine ) ; gedLine = gedLine . readToNext ( ) ; } return null ; }
Read the source data until the a line is encountered at the same level as this one . That allows the reading of children .
115
25
21,098
public Family createFamily ( final String idString ) { if ( idString == null ) { return new Family ( ) ; } final Family family = new Family ( getRoot ( ) , new ObjectId ( idString ) ) ; getRoot ( ) . insert ( family ) ; return family ; }
Encapsulate creating family with the given ID .
61
10
21,099
public Attribute createFamilyEvent ( final Family family , final String type , final String dateString ) { if ( family == null || type == null || dateString == null ) { return gedObjectBuilder . createAttribute ( ) ; } final Attribute event = gedObjectBuilder . createAttribute ( family , type ) ; event . insert ( new Date ( event , dateString ) ) ; return event ; }
Create a dated event .
85
5