auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void readAndValidateClasspathConfigs(String filePath) throws ProcessingException, IOException { this.setConfigDir(DynamicConfigHelpers.formatFilePath(formatClassPath(filePath))); ClassLoader classLoader = DynamicConfigValidator.class.getClassLoader(); URL url = classLoader.getResource(this.configDir); if (url == null) { throw new IllegalStateException("Model Configs Directory doesn't exists"); } URL jar = DynamicConfigValidator.class.getProtectionDomain().getCodeSource().getLocation(); Path jarFile = Paths.get(jar.toString().substring("file:".length())); FileSystem fs = FileSystems.newFileSystem(jarFile, null); this.readVariableConfig(fs); this.readSecurityConfig(fs); this.readTableConfig(fs); }

Target:
public void readAndValidateClasspathConfigs(String filePath) throws IOException { this.setConfigDir(DynamicConfigHelpers.formatFilePath(formatClassPath(filePath))); ClassLoader classLoader = DynamicConfigValidator.class.getClassLoader(); URL url = classLoader.getResource(this.configDir); if (url == null) { throw new IllegalStateException("Model Configs Directory doesn't exists"); } FileSystem fs = null; try { URL jar = DynamicConfigValidator.class.getProtectionDomain().getCodeSource().getLocation(); Path jarFile = Paths.get(jar.toString().substring(FILE_PREFIX_LENGTH)); fs = FileSystems.newFileSystem(jarFile, null); this.readVariableConfig(fs); this.readSecurityConfig(fs); this.readTableConfig(fs); } finally { fs.close(); } }
Source:
public boolean deregisterOutgoingRelationships(Long src, String relationshipType, Class endNodeType) { Iterator<Mappable> iterator = registeredRelationships.iterator(); List<Mappable> candidatesForDeletion = new ArrayList<>(); while (iterator.hasNext()) { Mappable mappedRelationship = iterator.next(); if (mappedRelationship.getStartNodeId() == src && mappedRelationship.getRelationshipType().equals(relationshipType) && endNodeType.equals(mappedRelationship.getEndNodeType())) { candidatesForDeletion.add(mappedRelationship); iterator.remove(); } } boolean notInGraphAtAll = candidatesForDeletion.size() == 0; return notInGraphAtAll || handleDeletionCandidates(candidatesForDeletion); }

Target:
public boolean deregisterOutgoingRelationships(Long src, String relationshipType, Class endNodeType) { return deregisterRelationshipsImpl(src, relationshipType, endNodeType, Mappable::getStartNodeId, Mappable::getEndNodeType); }
Source:
public void testEditShouldCallUpdateOnProject() throws ProjectNotFoundException { ProjectForm form = mock(ProjectForm.class); BindingResult binding = mock(BindingResult.class); String view = projectController.edit(PROJECT_NAME, form, binding); assertEquals("redirect:/projects", view); verify(projectService).update(PROJECT_NAME, form); ; }

Target:
public void testEditShouldCallUpdateOnProject() throws ProjectNotFoundException { ProjectForm form = mock(ProjectForm.class); BindingResult binding = mock(BindingResult.class); String view = projectController.edit(PROJECT_NAME, form, binding); assertEquals("redirect:/projects", view); verify(projectService).update(PROJECT_NAME, form); }
Source:
public void activityCompilesWithRegularDrawable() { addManifestProcessorParameter(ContextCompatDrawableTest.class, "AndroidManifestForDrawable.xml"); CompileResult result = compileFiles(ActivityWithDrawable.class); File generatedFile = toGeneratedFile(ActivityWithDrawable.class); assertCompilationSuccessful(result); assertGeneratedClassMatches(generatedFile, DRAWABLE_SIGNATURE); }

Target:
public void activityCompilesWithRegularDrawable() { CompileResult result = compileFiles(ActivityWithDrawable.class); File generatedFile = toGeneratedFile(ActivityWithDrawable.class); assertCompilationSuccessful(result); assertGeneratedClassMatches(generatedFile, DRAWABLE_SIGNATURE); }
Source:
private void logContext(RelationshipOp operation, Environment environment) { List<?> children = (environment.field.getSelectionSet() != null) ? (List) environment.field.getSelectionSet().getChildren() : new ArrayList<>(); List<String> fieldName = new ArrayList<String>(); if (children.size() > 0) { children.stream().forEach(i -> { if (i.getClass().equals(Field.class)) { fieldName.add(((Field) i).getName()); } else { fieldName.add(((FragmentSpread) i).getName()); } }); } String requestedFields = environment.field.getName() + fieldName.toString(); GraphQLType parent = environment.parentType; if (log.isDebugEnabled()) { log.debug("{} fields with parent {}<{}>", operation, requestedFields, EntityDictionary.getSimpleName(parent.getClass()), parent.getName()); } }

Target:
private void logContext(RelationshipOp operation, Environment environment) { List<?> children = (environment.field.getSelectionSet() != null) ? (List) environment.field.getSelectionSet().getChildren() : new ArrayList<>(); List<String> fieldName = new ArrayList<String>(); if (children.size() > 0) { children.stream().forEach(i -> { if (i.getClass().equals(Field.class)) { fieldName.add(((Field) i).getName()); } else if (i.getClass().equals(FragmentSpread.class)) { fieldName.add(((FragmentSpread) i).getName()); } else { log.debug("A new type of Selection, other than Field and FragmentSpread was encountered, {}", i.getClass()); } }); } String requestedFields = environment.field.getName() + fieldName.toString(); GraphQLType parent = environment.parentType; if (log.isDebugEnabled()) { log.debug("{} fields with parent {}<{}>", operation, requestedFields, EntityDictionary.getSimpleName(parent.getClass()), parent.getName()); } }
Source:
private void handleRotatedLogs(@Nonnull final String gcLogFileLocation, Container result) { File gcLogFile = new File(gcLogFileLocation); String regex = gcLogFile.getName().replaceAll("%[pt]", ".*") + ".*"; final Pattern gcLogFilesPattern = Pattern.compile(regex); File parentDirectory = gcLogFile.getParentFile(); if (parentDirectory == null || !parentDirectory.exists()) { LOGGER.warning("[Support Bundle] " + parentDirectory + " does not exist, cannot collect gc logging files."); return; } File[] gcLogs = parentDirectory.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return gcLogFilesPattern.matcher(name).matches(); } }); if (gcLogs == null || gcLogs.length == 0) { LOGGER.warning("No GC logging files found, although the VM argument was found. This is probably a bug."); return; } LOGGER.finest("Found " + gcLogs.length + " matching files in " + parentDirectory.getAbsolutePath()); for (File gcLog : gcLogs) { if (GCLOGS_RETENTION_DAYS <= 0 || (gcLog.lastModified() > (System.currentTimeMillis() - TimeUnit.DAYS.toMillis(GCLOGS_RETENTION_DAYS)))) { LOGGER.finest("Adding '" + gcLog.getName() + "' file"); result.add(new UnfilteredFileContent(GCLOGS_BUNDLE_ROOT + "{0}", new String[]{gcLog.getName()}, gcLog)); } } }

Target:
private void handleRotatedLogs(@Nonnull final String gcLogFileLocation, Container result) { File gcLogFile = new File(gcLogFileLocation); String regex = gcLogFile.getName().replaceAll("%[pt]", ".*") + ".*"; final Pattern gcLogFilesPattern = Pattern.compile(regex); File parentDirectory = gcLogFile.getParentFile(); if (parentDirectory == null || !parentDirectory.exists()) { LOGGER.warning("[Support Bundle] " + parentDirectory + " does not exist, cannot collect gc logging files."); return; } File[] gcLogs = parentDirectory.listFiles((dir, name) -> gcLogFilesPattern.matcher(name).matches()); if (gcLogs == null || gcLogs.length == 0) { LOGGER.warning("No GC logging files found, although the VM argument was found. This is probably a bug."); return; } LOGGER.finest("Found " + gcLogs.length + " matching files in " + parentDirectory.getAbsolutePath()); for (File gcLog : gcLogs) { if (shouldConsiderFile(gcLog)) { LOGGER.finest("Adding '" + gcLog.getName() + "' file"); result.add(new UnfilteredFileContent(GCLOGS_BUNDLE_ROOT + "{0}", new String[]{gcLog.getName()}, gcLog)); } } }
Source:
protected void onResume() { super.onResume(); Log.d(TAG, "onResumed called."); mWebView.onResume(); mWebView.resumeTimers(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); Log.d(TAG,"display_options_units: "+prefs.getString("display_options_units", "0")); int sgv = (Integer) mTextSGV.getTag(R.string.display_sgv); int direction = (Integer) mTextSGV.getTag(R.string.display_trend); if (sgv != -1) { mTextSGV.setText(getSGVStringByUnit(sgv, Constants.TREND_ARROW_VALUES.values()[direction])); } currentUnits = prefs.getString("display_options_units", "0").equals("0") ? 1 : Constants.MG_DL_TO_MMOL_L; boolean isLogritmic = prefs.getString("display_verticle_axis", "0").equals("0") ? true : false; mWebView.loadUrl("javascript:updateUnits(" + Boolean.toString(currentUnits == Constants.MG_DL_TO_MMOL_L) +"," + Boolean.toString(isLogritmic) + ","+ prefs.getString("display_low_range", "80") + "," + prefs.getString("display_high_range", "180") + ")"); mHandler.post(updateTimeAgo); }

Target:
protected void onResume() { super.onResume(); Log.d(TAG, "onResumed called."); mWebView.onResume(); mWebView.resumeTimers(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); Log.d(TAG,"display_options_units: "+prefs.getString("display_options_units", "0")); int sgv = (Integer) mTextSGV.getTag(R.string.display_sgv); int direction = (Integer) mTextSGV.getTag(R.string.display_trend); if (sgv != -1) { mTextSGV.setText(getSGVStringByUnit(sgv, Constants.TREND_ARROW_VALUES.values()[direction])); } currentUnits = prefs.getString("display_options_units", "0").equals("0") ? 1 : Constants.MG_DL_TO_MMOL_L; boolean isLogarithmic = prefs.getString("display_verticle_axis", "0").equals("0") ? true : false; mWebView.loadUrl("javascript:updateUnits(" + Boolean.toString(currentUnits == Constants.MG_DL_TO_MMOL_L) +"," + Boolean.toString(isLogarithmic) + ","+ prefs.getString("display_low_range", "80") + "," + prefs.getString("display_high_range", "180") + ")"); mHandler.post(updateTimeAgo); }
Source:
private SynchronizationTestUpdater(final Clock clock) { this.clock = clock; this.counterMap = new HashMap<>(); }

Target:
private SynchronizationTestUpdater(final Clock clock) { this.clock = clock; this.beforeMsgCounterMap = new HashMap<>(); this.afterMsgCounterMap = new HashMap<>(); }
Source:
public void testCustomPathHandler() throws Throwable { final String contents = "Some content for testing\n"; final String encoding = "utf-8"; WebViewAssetLoader.PathHandler assetsHandler = new WebViewAssetLoader.PathHandler("appassets.androidplatform.net", "/notused/", true) { @Override public InputStream handle(Uri url) { return null; } }; WebViewAssetLoader.PathHandler resourcesHandler = new WebViewAssetLoader.PathHandler("appassets.androidplatform.net", "/test/", true) { @Override public InputStream handle(Uri url) { try { return new ByteArrayInputStream(contents.getBytes(encoding)); } catch (UnsupportedEncodingException e) { Log.e(TAG, "exception when creating response", e); } return null; } }; WebViewAssetLoader assetLoader = (new WebViewAssetLoader.Builder(new MockContext())) .buildForTest(assetsHandler, resourcesHandler); WebResourceResponse response = assetLoader.shouldInterceptRequest("<LINK_1>"); Assert.assertNotNull("didn't match the exact registered URL", response); Assert.assertEquals(contents, readAsString(response.getData(), encoding)); Assert.assertNull("opened \"<LINK_0>\" that isn't registered - should return null", assetLoader.shouldInterceptRequest("<LINK_0>")); }

Target:
public void testCustomPathHandler() throws Throwable { final String contents = "Some content for testing\n"; final String encoding = "utf-8"; WebViewAssetLoader.PathHandler assetsHandler = new WebViewAssetLoader.PathHandler("appassets.androidplatform.net", "/notused/", true) { @Override public InputStream handle(Uri url) { return null; } }; WebViewAssetLoader.PathHandler resourcesHandler = new WebViewAssetLoader.PathHandler("appassets.androidplatform.net", "/test/", true) { @Override public InputStream handle(Uri url) { try { return new ByteArrayInputStream(contents.getBytes(encoding)); } catch (UnsupportedEncodingException e) { Log.e(TAG, "exception when creating response", e); } return null; } }; WebViewAssetLoader assetLoader = (new WebViewAssetLoader.Builder(new MockContext())) .buildForTest(assetsHandler, resourcesHandler); WebResourceResponse response = assetLoader.shouldInterceptRequest("<LINK_1>"); Assert.assertNotNull("didn't match the exact registered URL", response); Assert.assertEquals(contents, readAsString(response.getData(), encoding)); Assert.assertNull("opened a non-registered URL - should return null", assetLoader.shouldInterceptRequest("<LINK_0>")); }
Source:
public List<Object> getSortedObjects() { Set<Object> sorted = newSetFromMap(new LinkedHashMap<>(objectCount)); for (List<Object> bucket : buckets) { if (bucket != null) { sorted.addAll(bucket); } } return new ArrayList<>(sorted); }

Target:
public List<Object> getSortedObjects() { List<Object> sorted = new ArrayList<>(objectCount); for (List<Object> bucket : buckets) { if (bucket != null) { sorted.addAll(bucket); } } return sorted; }
Source:
private Set<String> validateCreateUserFromInvitationRequest(final CreateUserFromInvitationRequest request) { Set<String> validationErrors = new HashSet<String>(); if (request.getUser().getSubjectName().length() > getMaxLength("subjectName")) { validationErrors.add(errorMessageUtil.getMessage("user.subjectName.maxlength", "subjectName")); } if (request.getUser().getFullName().length() > getMaxLength("fullName")) { validationErrors.add(errorMessageUtil.getMessage("user.fullName.maxlength", "fullName")); } if (request.getUser().getFriendlyName().length() > getMaxLength("friendlyName")) { validationErrors.add(errorMessageUtil.getMessage("user.friendlyName.maxlength", "friendlyName")); } if (request.getUser().getTitle().length() > getMaxLength("title")) { validationErrors.add(errorMessageUtil.getMessage("user.title.maxlength", "title")); } if (request.getUser().getEmail().length() > getMaxLength("email")) { validationErrors.add(errorMessageUtil.getMessage("user.email.maxlength", "email")); } if (request.getUser().getPhoneNumber().length() > getMaxLength("phoneNumber")) { validationErrors.add(errorMessageUtil.getMessage("user.phoneNumber.maxlength", "phoneNumber")); } return validationErrors; }

Target:
private Set<String> validateCreateUserFromInvitationRequest(final CreateUserFromInvitationRequest request) { Set<String> validationErrors = new HashSet<String>(); if (request.getUser().getSubjectName().length() > getMaxLength("subjectName")) { validationErrors.add(errorMessageUtil.getMessage("user.subjectName.maxlength", getMaxLength("subjectName"))); } if (request.getUser().getFullName().length() > getMaxLength("fullName")) { validationErrors.add(errorMessageUtil.getMessage("user.fullName.maxlength", getMaxLength("fullName"))); } if (request.getUser().getFriendlyName().length() > getMaxLength("friendlyName")) { validationErrors.add(errorMessageUtil.getMessage("user.friendlyName.maxlength", getMaxLength("friendlyName"))); } if (request.getUser().getTitle().length() > getMaxLength("title")) { validationErrors.add(errorMessageUtil.getMessage("user.title.maxlength", getMaxLength("title"))); } if (request.getUser().getEmail().length() > getMaxLength("email")) { validationErrors.add(errorMessageUtil.getMessage("user.email.maxlength", getMaxLength("email"))); } if (request.getUser().getPhoneNumber().length() > getMaxLength("phoneNumber")) { validationErrors.add(errorMessageUtil.getMessage("user.phoneNumber.maxlength", getMaxLength("phoneNumber"))); } return validationErrors; }
Source:
public LinkedHashMap<String, Integer> getDimensionOrder() { return dimensionOrder; }

Target:
public List<String> getDimensionOrder() { synchronized (dimensionDescs) { return ImmutableList.copyOf(dimensionDescs.keySet()); } }
Source:
private byte[] encryptBlockCipher(byte[] compressedFragment) throws GeneralSecurityException { if (session == null) { throw new IllegalStateException("DTLS session must be set on record"); } else if (compressedFragment == null) { throw new NullPointerException("Compressed fragment must not be null"); } DTLSConnectionState writeState = session.getWriteState(); DatagramWriter plaintext = new DatagramWriter(); plaintext.writeBytes(compressedFragment); plaintext.writeBytes(getBlockCipherMac(writeState, compressedFragment)); int ciphertextLength = compressedFragment.length + writeState.getMacLength() + 1; int blocksize = writeState.getRecordIvLength(); int smallestMultipleOfBlocksize = blocksize; while ( smallestMultipleOfBlocksize <= ciphertextLength) { smallestMultipleOfBlocksize += blocksize; } int paddingLength = smallestMultipleOfBlocksize - ciphertextLength; byte[] padding = new byte[paddingLength + 1]; Arrays.fill(padding, (byte) paddingLength); plaintext.writeBytes(padding); Cipher blockCipher = writeState.getCipherSuite().getCipher(); blockCipher.init(Cipher.ENCRYPT_MODE, writeState.getEncryptionKey()); DatagramWriter result = new DatagramWriter(); result.writeBytes(blockCipher.getIV()); result.writeBytes(blockCipher.doFinal(plaintext.toByteArray())); return result.toByteArray(); }

Target:
private byte[] encryptBlockCipher(byte[] compressedFragment) throws GeneralSecurityException { if (session == null) { throw new IllegalStateException("DTLS session must be set on record"); } else if (compressedFragment == null) { throw new NullPointerException("Compressed fragment must not be null"); } DTLSConnectionState writeState = session.getWriteState(); DatagramWriter plaintext = new DatagramWriter(); plaintext.writeBytes(compressedFragment); plaintext.writeBytes(getBlockCipherMac(writeState, compressedFragment)); int ciphertextLength = compressedFragment.length + writeState.getMacLength() + 1; int blocksize = writeState.getRecordIvLength(); int paddingLength = ciphertextLength % blocksize; if (0 < paddingLength) { paddingLength = blocksize - paddingLength; } byte[] padding = new byte[paddingLength + 1]; Arrays.fill(padding, (byte) paddingLength); plaintext.writeBytes(padding); Cipher blockCipher = writeState.getCipherSuite().getCipher(); blockCipher.init(Cipher.ENCRYPT_MODE, writeState.getEncryptionKey()); DatagramWriter result = new DatagramWriter(); result.writeBytes(blockCipher.getIV()); result.writeBytes(blockCipher.doFinal(plaintext.toByteArray())); return result.toByteArray(); }
Source:
AzureCheckpointManager(AzureConfig azureConfig) { storageConnectionString = azureConfig.getAzureConnect(); azureClient = new AzureClient(storageConnectionString); }

Target:
AzureCheckpointManager(AzureConfig azureConfig) { storageConnectionString = azureConfig.getAzureConnectionString(); azureClient = new AzureClient(storageConnectionString); }
Source:
private BeanDefinition beanFromRequest(JolokiaListRequest pJmxReq, String providerAndDomain) { List<String> pathParts = pJmxReq.getPathParts(); if(pathParts != null && pathParts.size() == 2 && providerAndDomain.equals( pathParts.get(0))) { final String beanAndName = pathParts.get(1); if(beanAndName.startsWith("name=")) { final String beanName=beanAndName.substring(5); return getAsConfigurableApplicationContext().getBeanFactory().getMergedBeanDefinition(beanName); } } return null; }

Target:
private BeanDefinition beanFromRequest(JolokiaListRequest pJmxReq, String providerAndDomain) { List<String> pathParts = pJmxReq.getPathParts(); if(pathParts != null && pathParts.size() == 2 && providerAndDomain.equals( pathParts.get(0))) { final String beanAndName = pathParts.get(1); if(beanAndName.toLowerCase().startsWith(NAME_PREFIX)) { final String beanName=beanAndName.substring(NAME_PREFIX.length()); return getAsConfigurableApplicationContext().getBeanFactory().getMergedBeanDefinition(beanName); } } return null; }
Source:
synchronized void sendErrorToListeners(String error) { try { for (LIRCEventListener listener : listeners) { listener.errorOccured(error); } } catch (Exception e) { logger.error("Error invoking event listener", e); } }

Target:
public synchronized void sendErrorToListeners(String error) { try { for (LIRCEventListener listener : listeners) { listener.errorOccured(error); } } catch (Exception e) { logger.error("Error invoking event listener", e); } }
Source:
private void waitOrThrow(Throwable t, int nTry) throws IOException { final boolean isConnectionReset = isConnectionReset(t); if (isConnectionReset || retryCondition.apply(t)) { if (isConnectionReset) { try { startOffset += delegate.getCount(); delegate.close(); } catch (IOException e) { } } try { RetryUtils.awaitNextRetry(t, null, nTry + 1, maxRetry, false); if (isConnectionReset) { log.info("retrying from offset[%d]", startOffset); delegate = new CountingInputStream(objectOpenFunction.open(object, startOffset)); } } catch (InterruptedException | IOException e) { t.addSuppressed(e); throwAsIOException(t); } } else { throwAsIOException(t); } }

Target:
private void waitOrThrow(Throwable t, int nTry) throws IOException { final boolean isConnectionReset = isConnectionReset(t); if (isConnectionReset || retryCondition.apply(t)) { if (isConnectionReset) { startOffset += delegate.getCount(); try { delegate.close(); } catch (IOException e) { log.warn(e, "Error while closing the delegate input stream"); } } try { RetryUtils.awaitNextRetry(t, null, nTry + 1, maxRetry, false); if (isConnectionReset) { log.info("retrying from offset[%d]", startOffset); delegate = new CountingInputStream(objectOpenFunction.open(object, startOffset)); } } catch (InterruptedException | IOException e) { t.addSuppressed(e); throwAsIOException(t); } } else { throwAsIOException(t); } }
Source:
public ISchedulingRule getSchedulingRule() { return RuleUtil.getRuleForContainers(Collections.<IPath> emptySet()); }

Target:
public ISchedulingRule getSchedulingRule() { return null; }
Source:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } user.setDisplayNick(); final String message = _("helpOp", user.getDisplayName(), Util.stripFormat(getFinalArg(args, 0))); logger.log(Level.INFO, message); for (Player onlinePlayer : server.getOnlinePlayers()) { final User player = ess.getUser(onlinePlayer); if (!player.isAuthorized("essentials.helpop.receive")) { continue; } if (player.isBusy() && !user.isAuthorized("essentals.busy.bypass")) { continue; } player.sendMessage(message); } }

Target:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } user.setDisplayNick(); final String message = _("helpOp", user.getDisplayName(), Util.stripFormat(getFinalArg(args, 0))); logger.log(Level.INFO, message); for (Player onlinePlayer : server.getOnlinePlayers()) { final User player = ess.getUser(onlinePlayer); if (!player.isAuthorized("essentials.helpop.receive")) { continue; } if (player.isBusy() && !user.isAuthorized("essentials.busy.bypass")) { continue; } player.sendMessage(message); } }
Source:
public static Collection<VdsNetworkInterface> findAllInterfaceBondNameIsEmpty(List<VdsNetworkInterface> items) { return where(items, new IPredicate<VdsNetworkInterface>() { @Override public boolean match(VdsNetworkInterface i) { return !StringHelper.isNullOrEmpty(i.getBondName()); } }); }

Target:
public static Collection<VdsNetworkInterface> findAllInterfaceBondNameIsEmpty(List<VdsNetworkInterface> items) { return where(items, new IPredicate<VdsNetworkInterface>() { @Override public boolean match(VdsNetworkInterface i) { return StringHelper.isNullOrEmpty(i.getBondName()); } }); }
Source:
public CopyRatioData(final SegmentedGenome segmentedGenome) { if (segmentedGenome.getGenome().getTargets().targetCount() == 0) { throw new IllegalArgumentException("Cannot construct CopyRatioData with no target-coverage data."); } final TargetCollection<ReadCountRecord.SingleSampleRecord> targetCoverages = segmentedGenome.getGenome().getTargets(); final List<Double> coverages = segmentedGenome.getSegments().stream() .flatMap(s -> targetCoverages.targets(s).stream()) .map(ReadCountRecord.SingleSampleRecord::getCount) .collect(Collectors.toList()); numTargetsPerSegment = segmentedGenome.getSegments().stream() .map(s -> targetCoverages.targets(s).size()) .collect(Collectors.toList()); numSegments = numTargetsPerSegment.size(); numTargets = coverages.size(); coverageMin = Collections.min(coverages); coverageMax = Collections.max(coverages); coverageRange = coverageMax - coverageMin; int startTarget = 0; for (int segment = 0; segment < numSegments; segment++) { startTargetsPerSegment.add(startTarget); final int numTargetsInSegment = numTargetsPerSegment.get(segment); coveragesPerSegment.add(coverages.subList(startTarget, startTarget + numTargetsInSegment)); startTarget += numTargetsInSegment; } }

Target:
public CopyRatioData(final SegmentedGenome segmentedGenome) { final TargetCollection<ReadCountRecord.SingleSampleRecord> targetCoverages = segmentedGenome.getGenome().getTargets(); Utils.validateArg(targetCoverages.targetCount() > 0, "Cannot construct CopyRatioData with no target-coverage data."); final List<SimpleInterval> segments = segmentedGenome.getSegments(); numSegments = segments.size(); final List<Double> coverages = segments.stream() .flatMap(s -> targetCoverages.targets(s).stream()) .map(ReadCountRecord.SingleSampleRecord::getCount) .collect(Collectors.toList()); numTargets = coverages.size(); coverageMin = Collections.min(coverages); coverageMax = Collections.max(coverages); int targetIndex = 0; for (final SimpleInterval segment : segments) { final List<ReadCountRecord.SingleSampleRecord> targetCoveragesInSegment = targetCoverages.targets(segment); final List<IndexedCoverage> indexedCoveragesInSegment = new ArrayList<>(); for (final ReadCountRecord.SingleSampleRecord targetCoverage : targetCoveragesInSegment) { final double coverage = targetCoverage.getCount(); indexedCoveragesInSegment.add(new IndexedCoverage(coverage, targetIndex++)); } indexedCoveragesPerSegment.add(indexedCoveragesInSegment); } }
Source:
private Map<String, Integer> collateAnswerFrequency(List<FeedbackResponseAttributes> responses) { Map<String, Integer> answerFrequency = new LinkedHashMap<>(); for (String option : mcqChoices) { answerFrequency.put(option, 0); } if (otherEnabled) { answerFrequency.put("Other", 0); } for (FeedbackResponseAttributes response : responses) { String answerString = response.getResponseDetails().getAnswerString(); boolean isOtherOptionAnswer = ((FeedbackMcqResponseDetails) response.getResponseDetails()).isOtherOptionAnswer(); String key = isOtherOptionAnswer ? "Other" : answerString; answerFrequency.put(key, answerFrequency.getOrDefault(key, 0) + 1); } return answerFrequency; }

Target:
private Map<String, Integer> collateAnswerFrequency(List<FeedbackResponseAttributes> responses) { Map<String, Integer> answerFrequency = new LinkedHashMap<>(); for (String option : mcqChoices) { answerFrequency.put(option, 0); } if (otherEnabled) { answerFrequency.put("Other", 0); } for (FeedbackResponseAttributes response : responses) { FeedbackResponseDetails responseDetails = response.getResponseDetails(); boolean isOtherOptionAnswer = ((FeedbackMcqResponseDetails) responseDetails).isOtherOptionAnswer(); String key = isOtherOptionAnswer ? "Other" : responseDetails.getAnswerString(); answerFrequency.put(key, answerFrequency.getOrDefault(key, 0) + 1); } return answerFrequency; }
Source:
public void doCreateAccount() { new AMCreateAccountInfoTask() { @Override public void onCatch(Throwable caught) { L.e("AMCreateAccountInfoTask failed: " + caught.getMessage()); } @Override public void onFinish(AMCreateAccountInfoResult result) { if (result.getEnabled()) { L.i("Creating account with AuthManager"); captchaHandler.handleCaptcha(new CaptchaResult(result.getCaptchaId()), true); } else { L.i("Creating account with legacy API"); doLegacyCreateAccount(); } } }.execute(); }

Target:
public void doCreateAccount() { new AMCreateAccountInfoTask() { @Override public void onCatch(Throwable caught) { L.e(caught); } @Override public void onFinish(AMCreateAccountInfoResult result) { if (result.getEnabled()) { L.i("Creating account with AuthManager"); captchaHandler.handleCaptcha(new CaptchaResult(result.getCaptchaId()), true); } else { L.i("Creating account with legacy API"); doLegacyCreateAccount(); } } }.execute(); }
Source:
public void initialize() throws InternalErrorException, PrivilegeException { this.extSourcesManagerBl.initialize(this.getPerunSession()); }

Target:
public void initialize() throws InternalErrorException { this.extSourcesManagerBl.initialize(this.getPerunSession()); this.auditer.initialize(); }
Source:
public CompletableFuture<Void> visitGetKeysInGroupCommand(InvocationContext ctx, GetKeysInGroupCommand command) throws Throwable { final String groupName = command.getGroupName(); final boolean isOwner = groupManager.isOwner(groupName); updateTopologyId(command); final int commandTopologyId = command.getTopologyId(); if (ctx.isOriginLocal()) { return ctx.forkInvocation(command, (ctx1, command1, rv, throwable) -> { boolean shouldRetry; if (throwable != null) { Throwable ce = throwable; while (ce instanceof RemoteException) { ce = ce.getCause(); } shouldRetry = ce instanceof OutdatedTopologyException || ce instanceof SuspectException; } else { shouldRetry = isOwner && currentTopologyId() != commandTopologyId; } if (shouldRetry) { return retryVisitGetKeysInGroupCommand(ctx, command, commandTopologyId); } if (throwable != null) { throw throwable; } else { return ctx.shortCircuit(rv); } }); } else { ctx.onReturn((ctx1, command1, rv, throwable) -> { if (isOwner && currentTopologyId() != commandTopologyId) { throw new OutdatedTopologyException( "Cache topology changed while the command was executing: expected " + commandTopologyId + ", got " + currentTopologyId()); } return null; }); return ctx.continueInvocation(); } }

Target:
public CompletableFuture<Void> visitGetKeysInGroupCommand(InvocationContext ctx, GetKeysInGroupCommand command) throws Throwable { final String groupName = command.getGroupName(); final boolean isOwner = groupManager.isOwner(groupName); updateTopologyId(command); final int commandTopologyId = command.getTopologyId(); if (ctx.isOriginLocal()) { return ctx.forkInvocation(command, (rCtx, rCommand, rv, throwable) -> { boolean shouldRetry; if (throwable != null) { Throwable ce = throwable; while (ce instanceof RemoteException) { ce = ce.getCause(); } shouldRetry = ce instanceof OutdatedTopologyException || ce instanceof SuspectException; } else { shouldRetry = isOwner && currentTopologyId() != commandTopologyId; } if (shouldRetry) { return retryVisitGetKeysInGroupCommand(ctx, command, commandTopologyId); } if (throwable != null) { throw throwable; } else { return ctx.shortCircuit(rv); } }); } else { return ctx.onReturn((rCtx, rCommand, rv, throwable) -> { if (isOwner && currentTopologyId() != commandTopologyId) { throw new OutdatedTopologyException( "Cache topology changed while the command was executing: expected " + commandTopologyId + ", got " + currentTopologyId()); } return null; }); } }
Source:
public LoginPage() { setStatelessHint(true); setVersioned(false); add(form = new LoginForm("loginForm")); signInBtn = new Button("signInBtn", new ResourceModel("signIn")); tooManyUsersLabel = new MultiLineLabel("usersLabel", new ResourceModel("tooManyUsers")); tooManyUsersLabel.setVisible(false); form.add(signInBtn); form.add(tooManyUsersLabel); checkUsersLimit(); redirectIfAlreadyLoggedIn(); if (userRepository.list().isEmpty()) { User admin = new User(); admin.setUsername(ADMIN_DEFAULT_USERNAME); admin.setPassword(ADMIN_DEFAULT_PASSWORD); admin.setEnabled(true); admin.setRoles(EnumSet.of(Role.ROLE_ADMIN, Role.ROLE_USER)); userRepository.create(admin); String msg = "No user accounts have been found. An admin account has been created: " + ADMIN_DEFAULT_USERNAME + "/" + ADMIN_DEFAULT_PASSWORD; warn(msg); } }

Target:
public LoginPage() { setStatelessHint(true); setVersioned(false); add(form = new LoginForm("loginForm")); signInBtn = new Button("signInBtn"); signInBtn.add(LambdaBehavior.enabledWhen(() -> !isTooManyUsers())); tooManyUsersLabel = new WebMarkupContainer("usersLabel"); tooManyUsersLabel.add(LambdaBehavior.visibleWhen(this::isTooManyUsers)); form.add(signInBtn); form.add(tooManyUsersLabel); form.add(LambdaBehavior.enabledWhen(() -> !isTooManyUsers())); redirectIfAlreadyLoggedIn(); if (userRepository.list().isEmpty()) { User admin = new User(); admin.setUsername(ADMIN_DEFAULT_USERNAME); admin.setPassword(ADMIN_DEFAULT_PASSWORD); admin.setEnabled(true); admin.setRoles(EnumSet.of(Role.ROLE_ADMIN, Role.ROLE_USER)); userRepository.create(admin); String msg = "No user accounts have been found. An admin account has been created: " + ADMIN_DEFAULT_USERNAME + "/" + ADMIN_DEFAULT_PASSWORD; warn(msg); } }
Source:
@Test public void testRelShuttleForLogicalTableModify() { String sql = "insert into emp select * from emp"; LogicalTableModify rel = (LogicalTableModify) tester.convertSqlToRel(sql).rel; List<RelNode> rels = new ArrayList<>(); final RelShuttleImpl visitor = new RelShuttleImpl() { @Override public RelNode visit(LogicalTableModify modify) { rels.add(modify); return super.visit(modify); } }; visitor.visit(rel); assertThat(rels.size(), is(1)); assertThat(rels.get(0), isA(LogicalTableModify.class)); }

Target:
@Test public void testRelShuttleForLogicalTableModify() { final String sql = "insert into emp select * from emp"; final LogicalTableModify rel = (LogicalTableModify) tester.convertSqlToRel(sql).rel; final List<RelNode> rels = new ArrayList<>(); final RelShuttleImpl visitor = new RelShuttleImpl() { @Override public RelNode visit(LogicalTableModify modify) { RelNode visitedRel = super.visit(modify); rels.add(visitedRel); return visitedRel; } }; visitor.visit(rel); assertThat(rels.size(), is(1)); assertThat(rels.get(0), isA(LogicalTableModify.class)); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("RassXmlAwardEntry: [proposalNumber: ").append(proposalNumber); sb.append(", status:").append(status); sb.append(", projectTitle:").append(projectTitle); sb.append(", startDate:").append(startDate); sb.append(", stopDate:").append(stopDate); sb.append(", directCostAmount:").append(directCostAmount); sb.append(", indirectCostAMount:").append(indirectCostAMount); sb.append(", totalAMount:").append(totalAMount); sb.append(", grantNumber:").append(grantNumber); sb.append(", grantDescription:").append(grantDescription); sb.append(", federalPassThrough:").append(federalPassThrough); sb.append(", federalPassThroughAgencyNumber:").append(federalPassThroughAgencyNumber); sb.append(", cfdaNumber:").append(cfdaNumber); sb.append(", organizationCode:").append(organizationCode); sb.append(", costShareRequiredString:").append(costShareRequiredString); sb.append(", finalReportDueDate:").append(finalReportDueDate); if (CollectionUtils.isNotEmpty(principalAndCoPrincipalInvestigators)) { for (RassXMLAwardPiCoPiEntry pi : principalAndCoPrincipalInvestigators) { sb.append(KFSConstants.SQUARE_BRACKET_LEFT).append(pi.toString()).append(KFSConstants.SQUARE_BRACKET_RIGHT); } } else { sb.append(KFSConstants.SQUARE_BRACKET_LEFT).append("NO INVESTIGATIORS").append(KFSConstants.SQUARE_BRACKET_RIGHT); } sb.append(KFSConstants.SQUARE_BRACKET_RIGHT); return sb.toString(); }

Target:
public String toString() { return ToStringBuilder.reflectionToString(this); }
Source:
public static ItemStack insertItem(IItemHandler dest, ItemStack stack, boolean simulate) { if (dest == null || stack == null) return stack; for (int i = 0; i < dest.getSlots() && stack != null; i++) { stack = dest.insertItem(i, stack, simulate); } return stack; }

Target:
public static ItemStack insertItem(IItemHandler dest, ItemStack stack, boolean simulate) { if (dest == null || stack == null) return stack; for (int i = 0; i < dest.getSlots(); i++) { stack = dest.insertItem(i, stack, simulate); if (stack == null || stack.stackSize <= 0) { return null; } } return stack; }
Source:
public String toString() { return "Processor" + getCurrentJobCoordinator().getProcessorId(); }

Target:
public String toString() { return "Processor:" + processorId; }
Source:
public IConditionValueAutoCompleter getFieldValueAutoCompleter(String fieldName) { IConditionValueAutoCompleter retval = null; if (StringHelper.EqOp(fieldName, "TYPE")) { retval = new EnumValueAutoCompleter(VmPoolType.class); } else { } return retval; }

Target:
public IConditionValueAutoCompleter getFieldValueAutoCompleter(String fieldName) { IConditionValueAutoCompleter retval = null; if ("TYPE".equals(fieldName)) { retval = new EnumValueAutoCompleter(VmPoolType.class); } return retval; }
Source:
public boolean passesOcspCheck(X509Certificate[] certs) { if (!ocspEnabled) { LOGGER.debug("OCSP check is not enabled. Skipping."); return true; } for (X509Certificate cert : certs) { try { Certificate certificate = convertToBouncyCastleCert(cert); OCSPReq ocspRequest = generateOcspRequest(certificate); List<OCSPResp> ocspResponses = sendOcspRequests(cert, ocspRequest); if (anyOcspResponseStatusIsRevoked(ocspResponses)) { SecurityLogger.audit( "Certificate has been revoked by the OCSP server {}.", cert, ocspServerUrls); LOGGER.debug("Certificate has been revoked by the OCSP server."); return false; } } catch (OcspCheckerException ignore) { } } return true; }

Target:
public boolean passesOcspCheck(X509Certificate[] certs) { if (!ocspEnabled) { LOGGER.debug("OCSP check is not enabled. Skipping."); return true; } for (X509Certificate cert : certs) { try { Certificate certificate = convertToBouncyCastleCert(cert); OCSPReq ocspRequest = generateOcspRequest(certificate); Map<String, CertificateStatus> ocspStatuses = sendOcspRequests(cert, ocspRequest); String revokedStatusUrl = getFirstRevokedStatusUrl(ocspStatuses); if (revokedStatusUrl != null) { SecurityLogger.audit( "Certificate has been revoked by the OCSP server at URL {}.", cert, revokedStatusUrl); LOGGER.warn( "Certificate has been revoked by the OCSP server at URL {}.", cert, revokedStatusUrl); return false; } } catch (OcspCheckerException e) { postErrorEvent(e.getMessage()); } } return true; }
Source:
public List<Sample> listBySearchOffsetAndNumResults(int offset, int resultsPerPage, String querystr, String sortCol, String sortDir) throws IOException { if (offset < 0 || resultsPerPage < 0) throw new IOException("Limit and Offset must not be less than zero"); if ("lastModified".equals(sortCol)) sortCol = "derivedInfo.lastModified"; Criteria criteria = currentSession().createCriteria(SampleImpl.class); criteria.add(searchRestrictions(querystr)); criteria.createAlias("derivedInfo", "derivedInfo"); criteria.setFirstResult(offset); criteria.setMaxResults(resultsPerPage); criteria.addOrder("asc".equalsIgnoreCase(sortDir) ? Order.asc(sortCol) : Order.desc(sortCol)); criteria.setProjection(Projections.property("id")); @SuppressWarnings("unchecked") List<Long> ids = criteria.list(); if (ids.isEmpty()) { return Collections.emptyList(); } Criteria query = currentSession().createCriteria(SampleImpl.class); query.add(Restrictions.in("id", ids)); query.addOrder("asc".equalsIgnoreCase(sortDir) ? Order.asc(sortCol) : Order.desc(sortCol)); query.createAlias("derivedInfo", "derivedInfo"); @SuppressWarnings("unchecked") List<Sample> requestedPage = query.list(); return requestedPage; }

Target:
public List<Sample> listBySearchOffsetAndNumResults(int offset, int resultsPerPage, String querystr, String sortCol, String sortDir) throws IOException { if (offset < 0 || resultsPerPage < 0) throw new IOException("Limit and Offset must not be less than zero"); if ("lastModified".equals(sortCol)) sortCol = "derivedInfo.lastModified"; Criteria criteria = currentSession().createCriteria(SampleImpl.class); criteria.add(searchRestrictions(querystr)); criteria.createAlias("derivedInfo", "derivedInfo"); criteria.setFirstResult(offset); criteria.setMaxResults(resultsPerPage); criteria.addOrder("asc".equalsIgnoreCase(sortDir) ? Order.asc(sortCol) : Order.desc(sortCol)); criteria.setProjection(Projections.property("id")); @SuppressWarnings("unchecked") List<Long> ids = criteria.list(); if (ids.isEmpty()) { return Collections.emptyList(); } Criteria sampleCriteria = currentSession().createCriteria(SampleImpl.class); sampleCriteria.add(Restrictions.in("id", ids)); sampleCriteria.addOrder("asc".equalsIgnoreCase(sortDir) ? Order.asc(sortCol) : Order.desc(sortCol)); sampleCriteria.createAlias("derivedInfo", "derivedInfo"); @SuppressWarnings("unchecked") List<Sample> requestedPage = sampleCriteria.list(); return requestedPage; }
Source:
public void updateFromTileSourceTemplate(TileSourceTemplate r) { db = ctx.getSQLiteAPI().getOrCreateDatabase( ctx.getAppPath(TILES_INDEX_DIR).getAbsolutePath() + "/" + name + SQLITE_EXT, false); if (!onlyReadonlyAvailable) { int maxZoom = r.getMaximumZoomSupported(); int minZoom = r.getMinimumZoomSupported(); if (inversiveZoom) { int mnz = minZoom; minZoom = 17 - maxZoom; maxZoom = 17 - mnz; } if (getUrlTemplate() != null && !getUrlTemplate().equals(r.getUrlTemplate())) { db.execSQL("update info set " + URL + " = '" + r.getUrlTemplate() + "'"); } if (minZoom != this.minZoom) { db.execSQL("update info set " + MIN_ZOOM + " = '" + minZoom + "'"); } if (maxZoom != this.maxZoom) { db.execSQL("update info set " + MAX_ZOOM + " = '" + maxZoom + "'"); } if (r.isEllipticYTile() != isEllipticYTile()) { db.execSQL("update info set " + ELLIPSOID + " = '" + (r.isEllipticYTile() ? 1 : 0) + "'"); } if (r.getExpirationTimeMinutes() != getExpirationTimeMinutes()) { db.execSQL("update info set " + EXPIRE_MINUTES + " = '" + r.getExpirationTimeMinutes() + "'"); } } }

Target:
public void updateFromTileSourceTemplate(TileSourceTemplate r) { boolean openedBefore = isDbOpened(); SQLiteConnection db = getDatabase(); if (!onlyReadonlyAvailable && db != null) { int maxZoom = r.getMaximumZoomSupported(); int minZoom = r.getMinimumZoomSupported(); if (inversiveZoom) { int mnz = minZoom; minZoom = 17 - maxZoom; maxZoom = 17 - mnz; } if (getUrlTemplate() != null && !getUrlTemplate().equals(r.getUrlTemplate())) { db.execSQL("update info set " + URL + " = '" + r.getUrlTemplate() + "'"); } if (minZoom != this.minZoom) { db.execSQL("update info set " + MIN_ZOOM + " = '" + minZoom + "'"); } if (maxZoom != this.maxZoom) { db.execSQL("update info set " + MAX_ZOOM + " = '" + maxZoom + "'"); } if (r.isEllipticYTile() != isEllipticYTile()) { db.execSQL("update info set " + ELLIPSOID + " = '" + (r.isEllipticYTile() ? 1 : 0) + "'"); } if (r.getExpirationTimeMinutes() != getExpirationTimeMinutes()) { db.execSQL("update info set " + EXPIRE_MINUTES + " = '" + r.getExpirationTimeMinutes() + "'"); } } if (db != null && !openedBefore) { db.close(); } }
Source:
private EventSeverity parseMinSeverity(String input) { EventSeverity sev = EventSeverity.SEVERITY_CLEAR; if (ZingUtils.isNullOrEmpty(input)) { return sev; } switch (input.toUpperCase()) { case "CLEAR": sev = EventSeverity.SEVERITY_CLEAR; break; case "DEBUG": sev = EventSeverity.SEVERITY_DEBUG; break; case "INFO": sev = EventSeverity.SEVERITY_INFO; break; case "WARNING": sev = EventSeverity.SEVERITY_WARNING; break; case "ERROR": sev = EventSeverity.SEVERITY_ERROR; break; case "CRITICAL": sev = EventSeverity.SEVERITY_CRITICAL; break; default: logger.warn("Could not parse minimum severity. All events will be forwarded."); } return sev; }

Target:
private EventSeverity parseMinSeverity(String input) { EventSeverity sev = EventSeverity.SEVERITY_CLEAR; if (ZingUtils.isNullOrEmpty(input)) { return sev; } switch (ZingUtils.sanitizeToken(input)) { case "CLEAR": sev = EventSeverity.SEVERITY_CLEAR; break; case "DEBUG": sev = EventSeverity.SEVERITY_DEBUG; break; case "INFO": sev = EventSeverity.SEVERITY_INFO; break; case "WARNING": sev = EventSeverity.SEVERITY_WARNING; break; case "ERROR": sev = EventSeverity.SEVERITY_ERROR; break; case "CRITICAL": sev = EventSeverity.SEVERITY_CRITICAL; break; default: logger.warn("Could not parse minimum severity. All events will be forwarded."); } return sev; }
Source:
public Object getImage(Object object) { Match match = (Match)object; Object ret = null; try { ret = itemDelegator.getImage(match.getLeft()); if (ret == null) { ret = itemDelegator.getImage(match.getOrigin()); } if (ret == null) { ret = itemDelegator.getImage(match.getRight()); } if (ret == null && match instanceof NotLoadedFragmentMatch) { ret = itemDelegator.getImage(((NotLoadedFragmentMatch)match).getResource()); } } catch (MissingResourceException ex) { EMFCompareEditPlugin.getPlugin().log(ex); } if (ret == null) { ret = super.getImage(object); } Object matchImage = overlayProvider.getComposedImage(match, ret); ret = overlayImage(object, matchImage); return ret; }

Target:
public Object getImage(Object object) { Match match = (Match)object; Object ret = itemDelegator.getImage(match.getLeft()); if (ret == null) { ret = itemDelegator.getImage(match.getOrigin()); } if (ret == null) { ret = itemDelegator.getImage(match.getRight()); } if (ret == null && match instanceof NotLoadedFragmentMatch) { ret = itemDelegator.getImage(((NotLoadedFragmentMatch)match).getResource()); } if (ret == null) { Adapter adapter = EcoreUtil.getAdapter(match.eAdapters(), MatchOfContainmentReferenceChangeAdapter.class); if (adapter instanceof MatchOfContainmentReferenceChangeAdapter) { ReferenceChange referenceChange = ((MatchOfContainmentReferenceChangeAdapter)adapter) .getReferenceChange(); if (referenceChange != null) { ret = itemDelegator.getImage(referenceChange.getValue()); } } } if (ret == null) { ret = super.getImage(object); } Object matchImage = overlayProvider.getComposedImage(match, ret); ret = overlayImage(object, matchImage); return ret; }
Source:
public String getExtensionResource(final String resourcePath) throws FalconException { if (StringUtils.isBlank(resourcePath)) { throw new StoreAccessException(new Exception("Resource path cannot be null or empty")); } try { Path resourceFile = new Path(resourcePath); InputStream data; ByteArrayOutputStream writer = new ByteArrayOutputStream(); if (resourcePath.startsWith("hdfs")){ FileSystem fileSystem = getHdfsFileSystem(resourcePath); data = fileSystem.open(resourceFile); IOUtils.copyBytes(data, writer, fileSystem.getConf(), true); }else{ data = fs.open(resourceFile); IOUtils.copyBytes(data, writer, fs.getConf(), true); } return writer.toString(); } catch (IOException e) { throw new StoreAccessException(e); } }

Target:
public String getExtensionResource(final String resourcePath) throws FalconException { if (StringUtils.isBlank(resourcePath)) { throw new StoreAccessException("Resource path cannot be null or empty"); } try { Path resourceFile = new Path(resourcePath); InputStream data; ByteArrayOutputStream writer = new ByteArrayOutputStream(); if (resourcePath.startsWith("file")){ data = fs.open(resourceFile); IOUtils.copyBytes(data, writer, fs.getConf(), true); }else{ FileSystem fileSystem = getHdfsFileSystem(resourcePath); data = fileSystem.open(resourceFile); IOUtils.copyBytes(data, writer, fileSystem.getConf(), true); } return writer.toString(); } catch (IOException e) { throw new StoreAccessException(e); } }
Source:
public void deleteRecord(DataIdentifier identifier) throws DataStoreException { }

Target:
public void deleteRecord(DataIdentifier identifier) throws DataStoreException { Iterator<DataStore> iter = delegateHandler.getWritableDelegatesIterator(identifier); if (! iter.hasNext()) { iter = delegateHandler.getWritableDelegatesIterator(); } boolean deleted = false; while (iter.hasNext()) { DataStore ds = iter.next(); if (null != ds.getRecordIfStored(identifier)) { if (ds instanceof MultiDataStoreAware) { ((MultiDataStoreAware) ds).deleteRecord(identifier); deleted = true; } else if (ds instanceof DataStoreBlobStore) { try { ((DataStoreBlobStore) ds).deleteChunks(Lists.newArrayList(identifier.toString()), 0L); deleted = true; } catch (Exception e) { throw new DataStoreException(e); } } } if (deleted) { unmapIdFromDelegate(identifier); } } if (! deleted) { iter = delegateHandler.getAllDelegatesIterator(identifier); if (! iter.hasNext()) { iter = delegateHandler.getAllDelegatesIterator(); } if (! iter.hasNext()) { throw new DataStoreException(String.format("No such record for identifier %s", identifier.toString())); } else { while (iter.hasNext()) { if (null != iter.next().getRecordIfStored(identifier)) { return; } } } throw new DataStoreException(String.format("No such record for identifier %s", identifier.toString())); } }