code
stringlengths
73
34.1k
label
stringclasses
1 value
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...
java
protected int calculateBufferSize(long maxChunkSize) { final int KB = 1000; // Ensure maxChunkSize falls on 1-KB boundaries. if (maxChunkSize % KB != 0) { String m = "MaxChunkSize must be multiple of " + KB + ": " + maxChunkSize; log.error(m); throw new DuraC...
java
protected DistributionSummary getExistingDistribution(String bucketName) { List<DistributionSummary> dists = getAllExistingWebDistributions(bucketName); if (dists.isEmpty()) { return null; } else { return dists.get(0); } }
java
protected List<DistributionSummary> getAllExistingWebDistributions(String bucketName) { List<DistributionSummary> distListForBucket = new ArrayList<>(); DistributionList distList = cfClient.listDistributions(new ListDistributionsRequest()) .getDistributionList(); ...
java
protected void checkThatStreamingServiceIsEnabled(String spaceId, String taskName) { // Verify that streaming is enabled Map<String, String> spaceProperties = s3Provider.getSpaceProperties(spaceId); if (!spaceProperties.containsKey(HLS_STREAMING_HOST_PROP)) { throw new UnsupportedTas...
java
@Override 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) { ...
java
@Override 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/...
java
public static ChunksManifest createManifestFrom(ChunksManifestDocument doc) { ChunksManifestType manifestType = doc.getChunksManifest(); HeaderType headerType = manifestType.getHeader(); ChunksManifest.ManifestHeader header = createHeaderFromElement( headerType); ChunksType...
java
public long loadBackup() { long backupTime = -1; File[] backupDirFiles = getSortedBackupDirFiles(); if (backupDirFiles.length > 0) { File latestBackup = backupDirFiles[0]; try { backupTime = Long.parseLong(latestBackup.getName()); changedLi...
java
public void run() { while (continueBackup) { if (changedListVersion < changedList.getVersion()) { cleanupBackupDir(SAVED_BACKUPS); String filename = String.valueOf(System.currentTimeMillis()); File persistFile = new File(backupDir, filename); ...
java
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(); ...
java
public long persist(File persistFile) { try { FileOutputStream fileStream = new FileOutputStream(persistFile); ObjectOutputStream oStream = new ObjectOutputStream((fileStream)); long persistVersion; Map<String, ChangedFile> fileListCopy; synchronized ...
java
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.getA...
java
private Response addSpacePropertiesToResponse(ResponseBuilder response, String spaceID, String storeID) throws ResourceException { Map<String, String> properties = spaceResource.getSpaceProper...
java
private Response addSpaceACLsToResponse(ResponseBuilder response, String spaceID, String storeID) throws ResourceException { Map<String, String> aclProps = new HashMap<String, String>(); Map<String, AclType> ...
java
@Path("/acl/{spaceID}") @POST public Response updateSpaceACLs(@PathParam("spaceID") String spaceID, @QueryParam("storeID") String storeID) { String msg = "update space ACLs(" + spaceID + ", " + storeID + ")"; try { log.debug(msg); retu...
java
@Override public ChunksManifest write(String spaceId, ChunkableContent chunkable, Map<String, String> contentProperties) throws NotFoundException { return write(spaceId, chunkable, contentProperties, true); }
java
@Override public String writeSingle(String spaceId, String chunkChecksum, ChunkInputStream chunk, Map<String, String> properties) throws NotFoundException { log.debug("writeSingle: " + spaceId + ", " + chunk.g...
java
public String getSpaces(String storeID) throws ResourceException { Element spacesElem = new Element("spaces"); try { StorageProvider storage = storageProviderFactory.getStorageProvider(storeID); Iterator<String> spaces = storage.getSpaces(); while (...
java
public String getSpaceContents(String spaceID, String storeID, String prefix, long maxResults, String marker) throws ResourceException { Element spaceElem = new Element("sp...
java
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(spa...
java
public void updateSpaceACLs(String spaceID, Map<String, AclType> spaceACLs, String storeID) throws ResourceException { try { StorageProvider storage = storageProviderFactory.getStorageProvider( storeID); if (...
java
public void deleteSpace(String spaceID, String storeID) throws ResourceException { try { StorageProvider storage = storageProviderFactory.getStorageProvider(storeID); storage.deleteSpace(spaceID); } catch (NotFoundException e) { throw new ResourceNotFoundException("de...
java
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserDetails userDetails = usersTable.get(username); if (null == userDetails) { throw new UsernameNotFoundException(username); } return userDetails; }
java
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; }
java
public static ByteArrayInputStream storeProperties( Map<String, String> propertiesMap) throws StorageException { // Pull out known computed values propertiesMap.remove(StorageProvider.PROPERTIES_SPACE_COUNT); // Serialize Map byte[] properties = null; try { ...
java
public static String compareChecksum(StorageProvider provider, String spaceId, String contentId, String checksum) throws StorageException { String providerChecksum = pro...
java
public static String compareChecksum(String providerChecksum, String spaceId, String contentId, String checksum) throws ChecksumMismatchException { if (!providerChecksum.equals(chec...
java
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; ...
java
public static long count(Iterator<String> iterator) { if (iterator == null) { return 0; } long count = 0; while (iterator.hasNext()) { ++count; iterator.next(); } return count; }
java
public static List<String> getList(Iterator<String> iterator) { List<String> contents = new ArrayList<String>(); while (iterator.hasNext()) { contents.add(iterator.next()); } return contents; }
java
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(StoragePr...
java
public static Map<String, String> removeCalculatedProperties(Map<String, String> contentProperties) { if (contentProperties != null) { contentProperties = new HashMap<>(contentProperties); // Remove calculated properties contentProperties.remove(StorageProvider.PROPERTIES_CON...
java
public void setSpaceLifecycle(String bucketName, BucketLifecycleConfiguration config) { boolean success = false; int maxLoops = 6; for (int loops = 0; !success && loops < maxLoops; loops++) { try { s3Client.deleteBucketLifecycleConfig...
java
public String addHiddenContent(String spaceId, String contentId, String contentMimeType, InputStream content) { log.debug("addHiddenContent(" + spaceId + ", " + contentId + ", " + contentMi...
java
public String getBucketName(String spaceId) { // Determine if there is an existing bucket that matches this space ID. // The bucket name may use any access key ID as the prefix, so there is // no way to know the exact bucket name up front. List<Bucket> buckets = listAllBuckets(); ...
java
protected String getSpaceId(String bucketName) { String spaceId = bucketName; if (isSpace(bucketName)) { spaceId = spaceId.substring(accessKeyId.length() + 1); } return spaceId; }
java
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; } ...
java
@Override public void flush() throws IOException { checkWriter(); writer.flush(); try { contentStoreUtil.storeContentStream(tempFile, spaceId, contentId, ...
java
protected void addContentFrom(File baseDir, String destSpaceId) { Collection<File> files = listFiles(baseDir, options.getFileFilter(), options.getDirFilter()); for (File file : files) { try { ...
java
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...
java
@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); } }
java
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 InvalidIdExcept...
java
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 = "...
java
public static CompleteRestoreBridgeResult deserialize(String json) { JaxbJsonSerializer<CompleteRestoreBridgeResult> serializer = new JaxbJsonSerializer<>(CompleteRestoreBridgeResult.class); try { return serializer.deserialize(json); } catch (IOException e) { ...
java
public static String appendRedirectMessage(String outcomeUrl, Message message, HttpServletRequest request) { String key = addMessageToRedirect(message, request); if (!outcomeUrl.contains("?")) { out...
java
public String serialize() { JaxbJsonSerializer<SetStoragePolicyTaskParameters> serializer = new JaxbJsonSerializer<>(SetStoragePolicyTaskParameters.class); try { return serializer.serialize(this); } catch (IOException e) { throw new TaskDataException( ...
java
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 Ru...
java
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 Runt...
java
protected Map<String, AclType> getSpaceACLs(HttpServletRequest request) { String storeId = getStoreId(request); String spaceId = getSpaceId(request); return getSpaceACLs(storeId, spaceId); }
java
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 (Exceptio...
java
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(); ...
java
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]); } ...
java
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 ...
java
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)); ...
java
protected String getUserIpLimits(Authentication auth) { Object principal = auth.getPrincipal(); if (principal instanceof DuracloudUserDetails) { DuracloudUserDetails userDetails = (DuracloudUserDetails) principal; return userDetails.getIpLimits(); } else { re...
java
protected boolean ipInRange(String ipAddress, String range) { IpAddressMatcher addressMatcher = new IpAddressMatcher(range); return addressMatcher.matches(ipAddress); }
java
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(); }
java
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; }
java
public String performTask(String taskParameters) { GetSignedUrlTaskParameters taskParams = GetSignedUrlTaskParameters.deserialize(taskParameters); String spaceId = taskParams.getSpaceId(); String contentId = taskParams.getContentId(); String resourcePrefix = taskParams.getRe...
java
public String serialize() { JaxbJsonSerializer<CreateSnapshotBridgeParameters> serializer = new JaxbJsonSerializer<>(CreateSnapshotBridgeParameters.class); try { return serializer.serialize(this); } catch (IOException e) { throw new SnapshotDataException( ...
java
@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 SendMessa...
java
public SyncToolConfig retrievePrevConfig(File backupDir) { File prevConfigBackupFile = new File(backupDir, PREV_BACKUP_FILE_NAME); if (prevConfigBackupFile.exists()) { String[] prevConfigArgs = retrieveConfig(prevConfigBackupFile); try { return process...
java
public static String createNewBucketName(String accessKeyId, String spaceId) { String bucketName = accessKeyId + "." + spaceId; bucketName = bucketName.toLowerCase(); bucketName = bucketName.replaceAll("[^a-z0-9-.]", "-"); // Remove duplicate...
java
@Override public int vote(Authentication authentication, Object resource, Collection<ConfigAttribute> config) { int decision = super.vote(authentication, resource, config); log.debug(VoterUtil.debugText("RoleVoterImpl", au...
java
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(); ...
java
@RequestMapping(value = "/spaces/snapshots/{storeId}/{snapshotId}/restore-space-id", method = RequestMethod.GET) @ResponseBody public String restoreSpaceId(HttpServletRequest request, @PathVariable("storeId") String storeId, @PathVariable("snapsh...
java
protected <T> T getValueFromJson(String json, String propName) throws IOException { return (T) jsonStringToMap(json).get(propName); }
java
protected Map jsonStringToMap(String json) throws IOException { return new JaxbJsonSerializer<HashMap>(HashMap.class).deserialize(json); }
java
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/" + ...
java
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: " + ...
java
public static CancelSnapshotBridgeResult deserialize(String bridgeResult) { JaxbJsonSerializer<CancelSnapshotBridgeResult> serializer = new JaxbJsonSerializer<>(CancelSnapshotBridgeResult.class); try { return serializer.deserialize(bridgeResult); } catch (IOException e) {...
java
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); }
java
@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.f...
java
@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); }
java
@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); }
java
public static DigestInputStream wrapStream(InputStream inStream, Algorithm algorithm) { MessageDigest streamDigest = null; try { streamDigest = MessageDigest.getInstance(algorithm.toString()); } catch (NoSuchAlgorithmException e) { ...
java
public static String getChecksum(DigestInputStream digestStream) { MessageDigest digest = digestStream.getMessageDigest(); return checksumBytesToString(digest.digest()); }
java
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'); ...
java
public static ChunksManifest createManifestFrom(InputStream xml) { try { ChunksManifestDocument doc = ChunksManifestDocument.Factory.parse( xml); return ManifestElementReader.createManifestFrom(doc); } catch (XmlException e) { throw new DuraCloudRuntim...
java
public static String createDocumentFrom(ChunksManifestBean manifest) { ChunksManifestDocument doc = ChunksManifestDocument.Factory .newInstance(); if (null != manifest) { ChunksManifestType manifestType = ManifestElementWriter.createChunksManifestElementFrom( mani...
java
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 " + ...
java
protected String getSnapshotIdFromProperties(String spaceId) { Properties props = new Properties(); try (InputStream is = this.snapshotProvider.getContent(spaceId, Constants.SNAPSHOT_PROPS_FILENAME) .getContentStream()) { props.load(is); ...
java
protected boolean snapshotPropsPresentInSpace(String spaceId) { try { snapshotProvider.getContentProperties(spaceId, Constants.SNAPSHOT_PROPS_FILENAME); return true; } catch (NotFoundException ex) { return false; } }
java
public static ChunksManifestType createChunksManifestElementFrom( ChunksManifestBean manifest) { ChunksManifestType manifestType = ChunksManifestType.Factory .newInstance(); populateElementFromObject(manifestType, manifest); return manifestType; }
java
public List<StorageAccount> createStorageAccountsFrom(Element accounts) { List<StorageAccount> accts = new ArrayList<StorageAccount>(); try { Iterator<?> accountList = accounts.getChildren().iterator(); while (accountList.hasNext()) { Element accountXml = (Element...
java
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) {...
java
public String createXmlFrom(Collection<StorageAccount> accts, boolean includeCredentials, boolean includeOptions) { Element storageProviderAccounts = createDocumentFrom(accts, includeCredentials, includeOptions); Document docume...
java
protected void setSyncConfig(SyncToolConfig syncConfig) { this.syncConfig = syncConfig; this.syncConfig.setVersion(version); File exclusionListFile = this.syncConfig.getExcludeList(); if (exclusionListFile != null) { this.fileExclusionManager = new FileExclusionManager(exclus...
java
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 SyncToolConfi...
java
protected boolean configEquals(SyncToolConfig currConfig, SyncToolConfig prevConfig) { boolean sameHost = currConfig.getHost().equals(prevConfig.getHost()); boolean sameSpaceId = currConfig.getSpaceId().equals(prevConfig.getSpaceId()); boolean sameS...
java
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) ...
java
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 = R...
java
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>> currentChun...
java
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); } }
java
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(AmazonClientExceptio...
java
public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); }
java
public void setFieldValue(Object fieldValue) { ReflectionUtils.callSetter(parentWrapper.getItem(), field.getName(), fieldValue); }
java
@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); } }
java
public boolean isType(final String t) { final String dt = decode(t); if (dt.equals(getType())) { return true; } return "attribute".equals(getType()) && dt.equalsIgnoreCase(getString()); }
java