auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public synchronized boolean delete(String filename) { if (filename.equals(MEMORY_BUFFER_NAME)) { mCurrentReportsSendBuffer = null; return true; } final File file = new File(mReportsDir, filename); boolean ok = true; if (Prefs.getInstance().isSaveStumbleLogs()) { File newFile = new File(sdcard_archive_path() + File.separator + filename); ok = copyAndDelete(file, newFile); if (!ok) { ok = file.delete(); } } else { ok = file.delete(); } mFileList.update(mReportsDir); return ok; }

Target:
public synchronized boolean delete(String filename) { if (filename.equals(MEMORY_BUFFER_NAME)) { mCurrentReportsSendBuffer = null; return true; } final File file = new File(mReportsDir, filename); boolean ok = file.delete(); mFileList.update(mReportsDir); return ok; }
Source:
private IObservableValue<E> getDetailObservableValue(M masterKey) { IObservableValue<E> detailValue = detailObservableValueMap .get(masterKey); if (detailValue == null) { ObservableTracker.setIgnore(true); try { detailValue = observableValueFactory .createObservable(masterKey); detailObservableValueMap.put(masterKey, detailValue); if (detailValue.isStale()) { addStaleDetailObservable(detailValue); } } finally { ObservableTracker.setIgnore(false); } } return detailValue; }

Target:
private IObservableValue<E> getDetailObservableValue(M masterKey) { IObservableValue<E> detailValue = detailObservableValueMap.get(masterKey); if (detailValue == null) { ObservableTracker.setIgnore(true); try { detailValue = observableValueFactory.createObservable(masterKey); } finally { ObservableTracker.setIgnore(false); } detailObservableValueMap.put(masterKey, detailValue); if (detailValue.isStale()) { addStaleDetailObservable(detailValue); } } return detailValue; }
Source:
public static CosmosAsyncClient getCosmosClient() { return new CosmosClientBuilder() .endpoint(SampleConfigurations.HOST) .key(SampleConfigurations.MASTER_KEY) .connectionPolicy(ConnectionPolicy.getDefaultPolicy()) .consistencyLevel(ConsistencyLevel.EVENTUAL) .returnMinimalResponse(false) .buildAsyncClient(); }

Target:
public static CosmosAsyncClient getCosmosClient() { return new CosmosClientBuilder() .endpoint(SampleConfigurations.HOST) .key(SampleConfigurations.MASTER_KEY) .connectionPolicy(ConnectionPolicy.getDefaultPolicy()) .consistencyLevel(ConsistencyLevel.EVENTUAL) .contentResponseOnWriteEnabled(true) .buildAsyncClient(); }
Source:
public static boolean didPressNextKey(int actionId, KeyEvent event) { return actionId == EditorInfo.IME_ACTION_NEXT || event != null && (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_NAVIGATE_NEXT); }

Target:
protected boolean didPressNextKey(int actionId, KeyEvent event) { return actionId == EditorInfo.IME_ACTION_NEXT || event != null && (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_NAVIGATE_NEXT); }
Source:
public <T extends RealType<T>> IterableInterval<T> equation( final IterableInterval<T> out, final UnaryFunctionOp<long[], Double> in) { @SuppressWarnings("unchecked") final IterableInterval<T> result = (IterableInterval<T>) ops().run( net.imagej.ops.image.equation.DefaultCoordinatesEquation.class, out, in); return result; }

Target:
public <T extends RealType<T>> IterableInterval<T> equation( final IterableInterval<T> out, final UnaryFunctionOp<long[], Double> in) { @SuppressWarnings("unchecked") final IterableInterval<T> result = (IterableInterval<T>) ops().run( net.imagej.ops.Ops.Image.Equation.class, out, in); return result; }
Source:
public void updateDecoration(IStatus status) { String statusMessage = ""; if (status.isOK()) { PlanStatuses planStatuses = getPlanStatuses(); if (planStatuses.isSuccess()) { setTitleImage(CommonImages.getImageWithOverlay(BuildImages.VIEW_BUILDS, CommonImages.OVERLAY_SUCCESS, false, false)); } else if (planStatuses.isUnstable()) { setTitleImage(CommonImages.getImageWithOverlay(BuildImages.VIEW_BUILDS, CommonImages.OVERLAY_FAILED, false, false)); } else if (planStatuses.isFailed()) { setTitleImage(CommonImages.getImageWithOverlay(BuildImages.VIEW_BUILDS, CommonImages.OVERLAY_ERROR, false, false)); } else { setTitleImage(CommonImages.getImage(BuildImages.VIEW_BUILDS)); } String message = NLS.bind("{0} Succeeded, {1} Unstable, {2} Failed", new Object[] { planStatuses.numSuccess, planStatuses.numUnstable, planStatuses.numFailed }); setContentDescription(message); if (lastRefresh != null) { statusMessage = NLS.bind("Last update: {0}", DateFormat.getDateTimeInstance().format(lastRefresh)); } } else { setTitleImage(CommonImages.getImageWithOverlay(BuildImages.VIEW_BUILDS, CommonImages.OVERLAY_WARNING, false, false)); statusMessage = "Last update failed"; } if (statusMessage != null) { final IViewSite viewSite = getViewSite(); if (viewSite != null) { final IStatusLineManager statusLine = viewSite.getActionBars().getStatusLineManager(); if (statusLine != null) { statusLine.setMessage(statusMessage); } } } }

Target:
public void updateDecoration(IStatus status) { String statusMessage = ""; if (status.isOK()) { BuildsSummary buildsSummary = getBuildsSummary(); if (buildsSummary.isSuccess()) { setTitleImage(CommonImages.getImageWithOverlay(BuildImages.VIEW_BUILDS, CommonImages.OVERLAY_SUCCESS, false, false)); } else if (buildsSummary.isUnstable()) { setTitleImage(CommonImages.getImageWithOverlay(BuildImages.VIEW_BUILDS, CommonImages.OVERLAY_FAILED, false, false)); } else if (buildsSummary.isFailed()) { setTitleImage(CommonImages.getImageWithOverlay(BuildImages.VIEW_BUILDS, CommonImages.OVERLAY_ERROR, false, false)); } else { setTitleImage(CommonImages.getImage(BuildImages.VIEW_BUILDS)); } if (!buildsSummary.isEmpty()) { setContentDescription(buildsSummary.toString()); } else { setContentDescription(""); } if (lastRefresh != null) { statusMessage = NLS.bind("Last update: {0}", DateFormat.getDateTimeInstance().format(lastRefresh)); } } else { setTitleImage(CommonImages.getImageWithOverlay(BuildImages.VIEW_BUILDS, CommonImages.OVERLAY_WARNING, false, false)); statusMessage = "Last update failed"; } if (statusMessage != null) { final IViewSite viewSite = getViewSite(); if (viewSite != null) { final IStatusLineManager statusLine = viewSite.getActionBars().getStatusLineManager(); if (statusLine != null) { statusLine.setMessage(statusMessage); } } } }
Source:
public EObject getInput() { EObject input = null; if (inputRef == null || inputRef.get() == null) { if (getSession() != null && getSession().isOpen() && getURI().hasFragment()) { EObject eObject = getSession().getTransactionalEditingDomain().getResourceSet().getEObject(getURI(), false); if (eObject != null) { input = eObject; inputRef = new WeakReference<EObject>(eObject); } } } else { input = inputRef.get(); } return input; }

Target:
public EObject getInput() { EObject input = inputRef != null ? inputRef.get() : null; if (input == null) { if (getSession() != null && getSession().isOpen() && getURI().hasFragment()) { input = getSession().getTransactionalEditingDomain().getResourceSet().getEObject(getURI(), false); if (input != null) { inputRef = new WeakReference<EObject>(input); } } } return input; }
Source:
public SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder sib = new SearchIndexBuilder().addAllAnnotations(this); sib.add(new CollectionSearchIndex<TopLevelItem>() { protected TopLevelItem get(String key) { return getItem(key); } protected Collection<TopLevelItem> all() { return getItems(); } @Override protected String getName(TopLevelItem o) { return o.getName(); } }); addDisplayNamesToSearchIndex(sib, getItems(false)); return sib; }

Target:
public SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder sib = new SearchIndexBuilder().addAllAnnotations(this); sib.add(new CollectionSearchIndex<TopLevelItem>() { protected TopLevelItem get(String key) { return getItem(key); } protected Collection<TopLevelItem> all() { return getItems(); } @Override protected String getName(TopLevelItem o) { return o.getName(); } }); addDisplayNamesToSearchIndex(sib, getItems(true)); return sib; }
Source:
public void testOnTaskDetailsClosed() { TaskSummary taskSummary = createTestTaskSummary(null, TASK_STATUS_EXITED, ""); getPresenter().selectSummaryItem(taskSummary); assertEquals(taskSummary, getPresenter().getSelectedTask()); getPresenter().onTaskDetailsClosed(newCloseEventMock(PerspectiveIds.TASK_ADMIN_LIST_SCREEN)); assertEquals(taskSummary, getPresenter().getSelectedTask()); getPresenter().onTaskDetailsClosed(newCloseEventMock(PerspectiveIds.TASK_DETAILS_SCREEN)); assertNull(getPresenter().getSelectedTask()); }

Target:
public void testOnTaskDetailsClosed() { TaskSummary taskSummary = createTestTaskSummary(TASK_ID, TASK_STATUS_EXITED, ""); getPresenter().selectSummaryItem(taskSummary); assertEquals(taskSummary, getPresenter().getSelectedTask()); getPresenter().onTaskDetailsClosed(newCloseEventMock(PerspectiveIds.TASK_ADMIN_LIST_SCREEN)); assertEquals(taskSummary, getPresenter().getSelectedTask()); getPresenter().onTaskDetailsClosed(newCloseEventMock(PerspectiveIds.TASK_DETAILS_SCREEN)); assertNull(getPresenter().getSelectedTask()); }
Source:
public Optional<InsightCard.Category> selectMarketingInsightToGenerate(final DateTime currentTime, final Set<InsightCard.Category> marketingSeenCategories, final Random random) { final Integer dayOfMonth = currentTime.getDayOfMonth(); LOGGER.debug("The day of the month is {}", dayOfMonth); switch (dayOfMonth) { case 1: case 4: case 7: case 10: case 13: case 16: case 19: final Set<InsightCard.Category> allowedCategories; if (!marketingSeenCategories.isEmpty()) { allowedCategories = getAllowedCategories(marketingInsightPool, marketingSeenCategories); } else { allowedCategories = marketingInsightPool; } final Optional<InsightCard.Category> pickedRandomInsight = pickRandomInsightCategory(allowedCategories, random); return pickedRandomInsight; } return Optional.absent(); }

Target:
public Optional<InsightCard.Category> selectMarketingInsightToGenerate(final DateTime currentTime, final Set<InsightCard.Category> marketingSeenCategories, final Random random) { final Integer dayOfMonth = currentTime.getDayOfMonth(); LOGGER.debug("The day of the month is {}", dayOfMonth); switch (dayOfMonth) { case 1: case 4: case 7: case 10: case 13: case 16: case 19: final Optional<InsightCard.Category> pickedRandomInsight = pickRandomInsightCategory(marketingInsightPool, marketingSeenCategories, random); return pickedRandomInsight; } return Optional.absent(); }
Source:
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Class<?> parameterType = parameterContext.getParameter().getType(); final boolean expectsPath = parameterType == Path.class; if (!expectsPath && parameterType != File.class) { throw new ParameterResolutionException("Can only resolve parameter of type " + Path.class.getName() + " or " + File.class.getName() + " but was: " + parameterType.getName()); } final Path path = extensionContext.getStore(NAMESPACE) .getOrComputeIfAbsent(KEY, key -> tempDirProvider.get(parameterContext, extensionContext, TEMP_DIR_PREFIX), CloseablePath.class) .get(); if (expectsPath) { return path; } try { return path.toFile(); } catch (final UnsupportedOperationException uoe) { return new File(path.toAbsolutePath().toString()); } }

Target:
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { Class<?> parameterType = parameterContext.getParameter().getType(); boolean expectsPath = parameterType == Path.class; if (!expectsPath && parameterType != File.class) { throw new ParameterResolutionException("Can only resolve parameter of type " + Path.class.getName() + " or " + File.class.getName() + " but was: " + parameterType.getName()); } Path path = extensionContext.getStore(NAMESPACE) .getOrComputeIfAbsent(KEY, key -> tempDirProvider.get(parameterContext, extensionContext, TEMP_DIR_PREFIX), CloseablePath.class) .get(); if (expectsPath) { return path; } try { return path.toFile(); } catch (UnsupportedOperationException uoe) { throw new ParameterResolutionException("Unsupported FileSystem in tempDirProvider: " + tempDirProvider, uoe); } }
Source:
private void addCnxn(NIOServerCnxn cnxn) throws IOException { InetAddress addr = cnxn.getSocketAddress(); if (addr == null) { throw new IOException("Scoket of " + cnxn + " has been closed"); } Set<NIOServerCnxn> set = ipMap.get(addr); if (set == null) { set = Collections.newSetFromMap( new ConcurrentHashMap<NIOServerCnxn, Boolean>(2)); Set<NIOServerCnxn> existingSet = ipMap.putIfAbsent(addr, set); if (existingSet != null) { set = existingSet; } } set.add(cnxn); cnxns.add(cnxn); touchCnxn(cnxn); }

Target:
private void addCnxn(NIOServerCnxn cnxn) throws IOException { InetAddress addr = cnxn.getSocketAddress(); if (addr == null) { throw new IOException("Socket of " + cnxn + " has been closed"); } Set<NIOServerCnxn> set = ipMap.get(addr); if (set == null) { set = Collections.newSetFromMap( new ConcurrentHashMap<NIOServerCnxn, Boolean>(2)); Set<NIOServerCnxn> existingSet = ipMap.putIfAbsent(addr, set); if (existingSet != null) { set = existingSet; } } set.add(cnxn); cnxns.add(cnxn); touchCnxn(cnxn); }
Source:
public synchronized void close() { if (isOpen.getAndSet(false)) { LOGGER.info("closing loading cache [%s]", id); loadingCache.close(); reverseLoadingCache.close(); } }

Target:
public synchronized void close() { if (isOpen.getAndSet(false)) { LOGGER.info("Closing loading cache [%s]", id); loadingCache.close(); reverseLoadingCache.close(); } else { LOGGER.info("Closing already closed lookup"); return; } }
Source:
public T newInstance(RowResult next, String[] fields) throws GoraException, IOException { fields = getFieldsToQuery(fields); T persistent = newPersistent(); for (String f : fields) { Schema.Field field = fieldMap.get(f); Schema fieldSchema = field.schema(); Column column = kuduMapping.getFields().get(f); if (next.isNull(column.getName())) { continue; } Object fieldValue = KuduClientUtils.getObjectRow(next, column); Object v = deserializeFieldValue(field, fieldSchema, fieldValue, persistent); persistent.put(field.pos(), v); persistent.setDirty(field.pos()); } return persistent; }

Target:
public T newInstance(RowResult next, String[] fields) throws IOException { fields = getFieldsToQuery(fields); T persistent = newPersistent(); for (String objField : fields) { Schema.Field field = fieldMap.get(objField); Schema fieldSchema = field.schema(); Column column = kuduMapping.getFields().get(objField); if (next.isNull(column.getName())) { continue; } Object fieldValue = KuduClientUtils.getObjectRow(next, column); Object obtainedValue = deserializeFieldValue(field, fieldSchema, fieldValue, persistent); persistent.put(field.pos(), obtainedValue); persistent.setDirty(field.pos()); } return persistent; }
Source:
public static <M> StreamOperatorSpec<M, M> createMergeOperatorSpec(String opId) { return StreamOperatorSpec.<M, M>createStreamOperatorSpec((M message) -> new ArrayList<M>() { { this.add(message); } }, OperatorSpec.OpCode.MERGE, opId); }

Target:
public static <M> StreamOperatorSpec<M, M> createMergeOperatorSpec(String opId) { return new MergeOperatorSpec<>(opId); }
Source:
public TestResult invoke(File ws, VirtualChannel channel) throws IOException { final long nowSlave = System.currentTimeMillis(); FileSet fs = Util.createFileSet(ws, testResults); DirectoryScanner ds = fs.getDirectoryScanner(); TestResult result = new TestResult(buildTime + (nowSlave - nowMaster), ds, keepLongStdio); String[] files = ds.getIncludedFiles(); if (files.length == 0) { throw new AbortException(hudson.tasks.junit.Messages.JUnitResultArchiver_NoTestReportFound()); } LOGGER.info("Found files: " + Arrays.toString(files)); return result; }

Target:
public TestResult invoke(File ws, VirtualChannel channel) throws IOException { final long nowSlave = System.currentTimeMillis(); FileSet fs = Util.createFileSet(ws, testResults); DirectoryScanner ds = fs.getDirectoryScanner(); return new TestResult(buildTime + (nowSlave - nowMaster), ds, keepLongStdio); }
Source:
public void testNormalizePath() { String uglyVolume = "hdfs://nn.somewhere.com:86753/accumulo/blah/../. String metadataEntry = uglyVolume + "/tables/" + id + "/" + dir + "/" + filename; test(metadataEntry, "hdfs://nn.somewhere.com:86753/accumulo", id, dir, filename); }

Target:
public void testNormalizePath() { String uglyVolume = "hdfs://nn.somewhere.com:86753/accumulo/blah/../. String metadataEntry = uglyVolume + "/tables/" + id + "/" + dir + "/" + filename; TabletFile uglyFile = test(metadataEntry, "hdfs://nn.somewhere.com:86753/accumulo", id, dir, filename); TabletFile niceFile = new TabletFile( "hdfs://nn.somewhere.com:86753/accumulo/tables/" + id + "/" + dir + "/" + filename); assertEquals(niceFile, uglyFile); assertEquals(niceFile.hashCode(), uglyFile.hashCode()); }
Source:
public long delayBeforeNextRetry(AmazonWebServiceRequest originalRequest, AmazonClientException exception, int retriesAttempted) { return (retriesAttempted > MAX_RETRIES) ? maxBackoffTime : Math.min(((1L << retriesAttempted) * baseDelay), maxBackoffTime); }

Target:
public long delayBeforeNextRetry(AmazonWebServiceRequest originalRequest, AmazonClientException exception, int retriesAttempted) { return exponentialDelayHelper(retriesAttempted, baseDelay, maxBackoffTime); }
Source:
protected void finishModelStage(final OperationContext context, final ModelNode operation, String attributeName, ModelNode newValue, ModelNode oldValue, final Resource model) throws OperationFailedException { super.finishModelStage(context, operation, attributeName, newValue, oldValue, model); assert !USE_JOURNAL_STORE.isAllowExpression() && !USE_JDBC_STORE.isAllowExpression() : "rework this before enabling expression"; if (attributeName.equals(USE_JOURNAL_STORE.getName()) || attributeName.equals(USE_JDBC_STORE.getName())) { if (newValue.isDefined() && newValue.asBoolean()) { final String mutualAttributeName = attributeName.equals(USE_JDBC_STORE.getName()) ? USE_JOURNAL_STORE.getName() : USE_JDBC_STORE.getName(); ModelNode resourceModel = model.getModel(); if (resourceModel.hasDefined(mutualAttributeName) && resourceModel.get(mutualAttributeName).asBoolean()) { resourceModel.get(mutualAttributeName).set(new ModelNode(false)); context.addResponseWarning(Level.WARNING, "Please note that only journal store or jdbc store can be used, thus '" + mutualAttributeName + "' has been disabled."); } } } context.addStep(JdbcStoreValidationStep.INSTANCE, OperationContext.Stage.MODEL); }

Target:
protected void finishModelStage(final OperationContext context, final ModelNode operation, String attributeName, ModelNode newValue, ModelNode oldValue, final Resource model) throws OperationFailedException { super.finishModelStage(context, operation, attributeName, newValue, oldValue, model); assert !USE_JOURNAL_STORE.isAllowExpression() && !USE_JDBC_STORE.isAllowExpression() : "rework this before enabling expression"; if (attributeName.equals(USE_JOURNAL_STORE.getName()) || attributeName.equals(USE_JDBC_STORE.getName())) { if (newValue.isDefined() && newValue.asBoolean()) { final String mutualAttributeName = attributeName.equals(USE_JDBC_STORE.getName()) ? USE_JOURNAL_STORE.getName() : USE_JDBC_STORE.getName(); ModelNode resourceModel = model.getModel(); if (resourceModel.hasDefined(mutualAttributeName) && resourceModel.get(mutualAttributeName).asBoolean()) { resourceModel.get(mutualAttributeName).set(new ModelNode(false)); } } } context.addStep(JdbcStoreValidationStep.INSTANCE, OperationContext.Stage.MODEL); }
Source:
public void onWritePossible() throws IOException { while (out.isReady()) { try { buffer.clear(); if (in.read(buffer) < 0) { try { in.close(); } catch (IOException e) { LOG.log(Level.SEVERE, e.getMessage(), e); } buffer = null; } else { buffer.flip(); } } catch(Throwable t) { LOG.log(Level.SEVERE, t.getMessage(), t); buffer = null; } finally { if (buffer != null) { outChannel.write(buffer); } else { try { out.close(); } finally { context.complete(); } return; } } } }

Target:
public void onWritePossible() throws IOException { while (out.isReady()) { try { buffer.clear(); if (in.read(buffer) < 0) { buffer = null; } else { buffer.flip(); } } catch (Throwable t) { LOG.log(Level.SEVERE, t.getMessage(), t); buffer = null; } finally { if (buffer != null) { outChannel.write(buffer); } else { try { in.close(); } catch (IOException e) { LOG.log(Level.SEVERE, e.getMessage(), e); } try { out.close(); } finally { context.complete(); } return; } } } }
Source:
public <T extends WithKey> String getKey(@Nonnull final T resource) { return resource.getKey(); }

Target:
private <T extends WithKey> String getKey(@Nonnull final T resource) { return resource.getKey(); }
Source:
private static FilePath locate(TopLevelItem item, String fullName, Node node, boolean create) { switch (MODE) { case DISABLED: return null; case MULTIBRANCH_ONLY: if (!(item.getParent() instanceof MultiBranchProject)) { return null; } break; case ENABLED: break; default: throw new AssertionError(); } FilePath workspace = getWorkspaceRoot(node); if (workspace == null) { return null; } if (fullName.contains("\n") || fullName.equals(INDEX_FILE_NAME)) { throw new IllegalArgumentException(); } try { synchronized (node) { Map<String, String> index = load(workspace); String path = index.get(fullName); if (path != null) { return workspace.child(path); } if (PATH_MAX != 0 && item.getParent() instanceof MultiBranchProject) { path = minimize(fullName); FilePath dir = workspace.child(path); if (dir.isDirectory()) { index.put(fullName, path); save(index, workspace); return dir; } } FilePath dir = workspace.child(fullName); if (dir.isDirectory()) { index.put(fullName, fullName); save(index, workspace); return dir; } if (!create) { return null; } String mnemonic = mnemonicOf(fullName); for (int i = 1; ; i++) { path = StringUtils.right(i > 1 ? mnemonic + "_" + i : mnemonic, MAX_LENGTH); if (!index.containsKey(path)) { dir = workspace.child(path); if (!dir.isDirectory()) { index.put(fullName, path); save(index, workspace); return dir; } } } } } catch (IOException | InterruptedException x) { LOGGER.log(Level.WARNING, "could not manage workspaces on " + node, x); return null; } }

Target:
private static FilePath locate(TopLevelItem item, String fullName, Node node, boolean create) { switch (MODE) { case DISABLED: return null; case MULTIBRANCH_ONLY: if (!(item.getParent() instanceof MultiBranchProject)) { return null; } break; case ENABLED: break; default: throw new AssertionError(); } FilePath workspace = getWorkspaceRoot(node); if (workspace == null) { return null; } if (fullName.contains("\n") || fullName.equals(INDEX_FILE_NAME)) { throw new IllegalArgumentException("Dangerous job name `" + fullName + "`"); } try { synchronized (node) { Map<String, String> index = load(workspace); String path = index.get(fullName); if (path != null) { return workspace.child(path); } if (PATH_MAX != 0 && item.getParent() instanceof MultiBranchProject) { path = minimize(fullName); FilePath dir = workspace.child(path); if (dir.isDirectory()) { index.put(fullName, path); save(index, workspace); return dir; } } FilePath dir = workspace.child(fullName); if (dir.isDirectory()) { index.put(fullName, fullName); save(index, workspace); return dir; } if (!create) { return null; } String mnemonic = mnemonicOf(fullName); for (int i = 1; ; i++) { path = StringUtils.right(i > 1 ? mnemonic + "_" + i : mnemonic, MAX_LENGTH); if (!index.containsKey(path)) { dir = workspace.child(path); if (!dir.isDirectory()) { index.put(fullName, path); save(index, workspace); return dir; } } } } } catch (IOException | InterruptedException x) { LOGGER.log(Level.WARNING, "could not manage workspaces on " + node, x); return null; } }
Source:
public JobResult updateWorkspace(UpdateWorkspaceParameters updateWorkspaceParameters) { if (updateWorkspaceParameters.getAddedProjectsUri().isEmpty()) { if (!findInitializedLanguageServer().isPresent()) { JobResult jobResult = new JobResult(); jobResult.setMessage( "Skipped. Language server not initialized. Workspace updating is not required."); return jobResult; } } Type type = new TypeToken<JobResult>() {}.getType(); return doGetOne(Commands.UPDATE_WORKSPACE, singletonList(updateWorkspaceParameters), type, 60); }

Target:
public JobResult updateWorkspace(UpdateWorkspaceParameters updateWorkspaceParameters) { if (updateWorkspaceParameters.getAddedProjectsUri().isEmpty()) { if (!findInitializedLanguageServer().isPresent()) { return new JobResult( Severity.OK, 0, "Skipped. Language server not initialized. Workspace updating is not required."); } } Type type = new TypeToken<JobResult>() {}.getType(); return doGetOne( Commands.UPDATE_WORKSPACE, singletonList(updateWorkspaceParameters), type, REIMPORT_MAVEN_PROJECTS_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS); }
Source:
public T insert(SQLiteDatabase db, T entityAdapter, boolean isSyncAdapter) { Log.d("Logging EntityProcessor", "before insert"); T result = mDelegate.insert(db, entityAdapter, isSyncAdapter); Log.d("Logging EntityProcessor", "after insert on " + entityAdapter.id()); return result; }

Target:
public T insert(SQLiteDatabase db, T entityAdapter, boolean isSyncAdapter) { Log.d(TAG, "before insert"); T result = mDelegate.insert(db, entityAdapter, isSyncAdapter); Log.d(TAG, "after insert on " + entityAdapter.id()); return result; }
Source:
public void testCloseChannelOnSendError() throws Exception { when(transport.submit(anyObject())).thenReturn(Observable.<Void>error(new Exception("msg"))); final CountDownLatch onErrorLatch = new CountDownLatch(1); channel.asLifecycleObservable().subscribe(new Subscriber<Void>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { onErrorLatch.countDown(); } @Override public void onNext(Void aVoid) { } }); channel.sendOnTransport("My Message"); verify(channel, times(1)).close(); Assert.assertTrue(onErrorLatch.await(10, TimeUnit.SECONDS)); }

Target:
public void testCloseChannelOnSendError() throws Exception { when(transport.submit(anyObject())).thenReturn(Observable.<Void>error(new Exception("msg"))); channel.asLifecycleObservable().subscribe(subscriber); channel.sendOnTransport("My Message"); verify(channel, times(1)).close(); subscriber.awaitTerminalEvent(10, TimeUnit.SECONDS); Assert.assertEquals(1, subscriber.getOnErrorEvents().size()); }
Source:
public void testGetClientIp() { String clientIp = IpUtil.getClientIp( "37.228.105.17", "101.209.27.230,%20101.209.27.230" ); assertEquals("Return IP address is not the client's IP in XFF", "101.209.27.230", clientIp); }

Target:
public void testGetClientIp() { String clientIp = IpUtil.getClientIp( "37.228.105.17", "127.0.0.1,10.0.0.1,192.168.27.230,169.254.27.230,%20101.209.27.230,101.209.27.230" ); assertEquals("Return IP address is not the client's IP in XFF", "101.209.27.230", clientIp); }
Source:
public Map<Sha256Hash, Long> lookupStreamIdsByHash(Transaction t, final Set<Sha256Hash> hashes) { if (hashes.isEmpty()) { return ImmutableMap.of(); } UserPhotosStreamHashAidxTable idx = tables.getUserPhotosStreamHashAidxTable(t); Set<UserPhotosStreamHashAidxTable.UserPhotosStreamHashAidxRow> rows = getHashIndexRowsForHashes(hashes); Multimap<UserPhotosStreamHashAidxTable.UserPhotosStreamHashAidxRow, UserPhotosStreamHashAidxTable.UserPhotosStreamHashAidxColumnValue> m = idx.getRowsMultimap(rows); Map<Long, Sha256Hash> hashForStreams = Maps.newHashMap(); for (UserPhotosStreamHashAidxTable.UserPhotosStreamHashAidxRow r : m.keySet()) { for (UserPhotosStreamHashAidxTable.UserPhotosStreamHashAidxColumnValue v : m.get(r)) { Long streamId = v.getColumnName().getStreamId(); Sha256Hash hash = r.getHash(); if (hashForStreams.containsKey(streamId)) { AssertUtils.assertAndLog(hashForStreams.get(streamId).equals(hash), "(BUG) Stream ID has 2 different hashes: " + streamId); } hashForStreams.put(streamId, hash); } } Map<Long, StreamMetadata> metadata = getMetadata(t, hashForStreams.keySet()); Map<Sha256Hash, Long> ret = Maps.newHashMap(); for (Map.Entry<Long, StreamMetadata> e : metadata.entrySet()) { if (e.getValue().getStatus() != Status.STORED) { continue; } Sha256Hash hash = hashForStreams.get(e.getKey()); ret.put(hash, e.getKey()); } return ret; }

Target:
public Map<Sha256Hash, Long> lookupStreamIdsByHash(Transaction t, final Set<Sha256Hash> hashes) { if (hashes.isEmpty()) { return ImmutableMap.of(); } UserPhotosStreamHashAidxTable idx = tables.getUserPhotosStreamHashAidxTable(t); Set<UserPhotosStreamHashAidxTable.UserPhotosStreamHashAidxRow> rows = getHashIndexRowsForHashes(hashes); Multimap<UserPhotosStreamHashAidxTable.UserPhotosStreamHashAidxRow, UserPhotosStreamHashAidxTable.UserPhotosStreamHashAidxColumnValue> m = idx.getRowsMultimap(rows); Map<Long, Sha256Hash> hashForStreams = Maps.newHashMap(); for (UserPhotosStreamHashAidxTable.UserPhotosStreamHashAidxRow r : m.keySet()) { for (UserPhotosStreamHashAidxTable.UserPhotosStreamHashAidxColumnValue v : m.get(r)) { Long streamId = v.getColumnName().getStreamId(); Sha256Hash hash = r.getHash(); if (hashForStreams.containsKey(streamId)) { AssertUtils.assertAndLog(log, hashForStreams.get(streamId).equals(hash), "(BUG) Stream ID has 2 different hashes: " + streamId); } hashForStreams.put(streamId, hash); } } Map<Long, StreamMetadata> metadata = getMetadata(t, hashForStreams.keySet()); Map<Sha256Hash, Long> ret = Maps.newHashMap(); for (Map.Entry<Long, StreamMetadata> e : metadata.entrySet()) { if (e.getValue().getStatus() != Status.STORED) { continue; } Sha256Hash hash = hashForStreams.get(e.getKey()); ret.put(hash, e.getKey()); } return ret; }
Source:
private static boolean hasServiceFeesToPay(final @NonNull InvoiceRow row, final CurrencyCode currencyCode) { return row.getServiceFeeAmt() != null && !Amount.zero(currencyCode).equals(row.getServiceFeeAmt()); }

Target:
private static boolean hasServiceFeesToPay(final @NonNull InvoiceRow row, final CurrencyCode currencyCode) { return row.getServiceFeeAmt() != null && !row.getServiceFeeAmt().isZero(); }
Source:
private static List<LifecycleCallbackMethodReference> toLifecycleCallbackMethodRefs(Method method, List<SourceMethod> candidates, Map<SourceMethod, List<Parameter>> parameterAssignmentsForSourceMethod, MappingBuilderContext ctx, Set<String> existingVariableNames) { List<LifecycleCallbackMethodReference> result = new ArrayList<LifecycleCallbackMethodReference>(); for ( SourceMethod candidate : candidates ) { markMapperReferenceAsUsed( ctx.getMapperReferences(), candidate ); result.add( new LifecycleCallbackMethodReference( candidate, parameterAssignmentsForSourceMethod.get( candidate ), method.getReturnType(), existingVariableNames ) ); } return result; }

Target:
private static List<LifecycleCallbackMethodReference> toLifecycleCallbackMethodRefs(Method method, List<SourceMethod> candidates, Map<SourceMethod, List<Parameter>> parameterAssignmentsForSourceMethod, MappingBuilderContext ctx, Set<String> existingVariableNames) { List<LifecycleCallbackMethodReference> result = new ArrayList<LifecycleCallbackMethodReference>(); for ( SourceMethod candidate : candidates ) { markMapperReferenceAsUsed( ctx.getMapperReferences(), candidate ); result.add( new LifecycleCallbackMethodReference( candidate, parameterAssignmentsForSourceMethod.get( candidate ), method.getReturnType(), method.getResultType(), existingVariableNames ) ); } return result; }
Source:
public Optional<?> getProperty(T pojo, String propertyName) { try { return ReflectionAdapterUtils.getFields(pojo.getClass()).stream() .filter(f -> Objects.equals(propertyName, f.getName())) .findFirst(); } catch (IllegalAccessException e) { LOG.error("Error obtaining fields from definition " + getId(pojo)); return Optional.empty(); } }

Target:
public Optional<?> getProperty(T pojo, String propertyName) { try { return ReflectionAdapterUtils.getFields(pojo.getClass()).stream() .filter(f -> Objects.equals(propertyName, f.getName())) .findFirst(); } catch (SecurityException e) { LOG.error("Error obtaining fields from definition " + getId(pojo)); return Optional.empty(); } }
Source:
public void visitNode(Tree tree) { ClassTree classTree = (ClassTree) tree; if (hasSemantic() && classTree.symbol().metadata().isAnnotatedWith(CONFIGURATION_ANNOTATION)) { AutowiredFieldVisitor autowiredFieldVisitor = new AutowiredFieldVisitor(); classTree.accept(autowiredFieldVisitor); BeanMethodVisitor beanMethodVisitor = new BeanMethodVisitor(autowiredFieldVisitor.autowiredFields.keySet()); classTree.accept(beanMethodVisitor); beanMethodVisitor.beanMethodsThatUseAutowiredFields.entrySet().stream() .filter(beanMethodsThatUseAutowiredField -> beanMethodsThatUseAutowiredField.getValue().size() == 1) .forEach(beanMethodsThatUseAutowiredField -> reportIssue( autowiredFieldVisitor.autowiredFields.get(beanMethodsThatUseAutowiredField.getKey()).simpleName(), String.format(MESSAGE_FORMAT, beanMethodsThatUseAutowiredField.getValue().get(0)))); } }

Target:
public void visitNode(Tree tree) { ClassTree classTree = (ClassTree) tree; if (classTree.symbol().metadata().isAnnotatedWith(CONFIGURATION_ANNOTATION)) { Map<Symbol, VariableTree> autowiredFields = new HashMap<>(); classTree.members().forEach(m -> collectAutowiredFields(m, autowiredFields)); Map<Symbol, List<MethodTree>> methodsThatUseAutowiredFields = new HashMap<>(); autowiredFields.keySet().forEach(f -> methodsThatUseAutowiredFields.put(f, new ArrayList<>())); classTree.members().forEach(m -> collectMethodsThatUseAutowiredFields(m, methodsThatUseAutowiredFields)); methodsThatUseAutowiredFields.entrySet().stream() .filter(methodsForField -> methodsForField.getValue().size() == 1 && methodsForField.getValue().get(0).symbol().metadata().isAnnotatedWith(BEAN_ANNOTATION)) .forEach(methodsForField -> reportIssue( autowiredFields.get(methodsForField.getKey()).simpleName(), String.format(MESSAGE_FORMAT, methodsForField.getValue().get(0).simpleName().name()))); } }
Source:
public DocumentMovedEvent(DocumentReference documentReference) { String move; super(documentReference); this.move = move; }

Target:
public DocumentMovedEvent(DocumentReference documentReference) { this(documentReference, null); }
Source:
private void handleAddBreadcrumb(Object arg) { if (arg instanceof Breadcrumb) { Breadcrumb crumb = (Breadcrumb) arg; Map<String, String> metadata = new HashMap<String, String>(); if (crumb.getMetadata() != null) { for (Map.Entry<String, String> entry : crumb.getMetadata().entrySet()) { if (entry.getValue() != null) { metadata.put(makeSafe(entry.getKey()), makeSafe(entry.getValue())); } } } addBreadcrumb(crumb.getName(), crumb.getType().toString(), crumb.getTimestamp(), metadata); } else { warn("Attempted to add non-breadcrumb: " + arg); } }

Target:
private void handleAddBreadcrumb(Object arg) { if (arg instanceof Breadcrumb) { Breadcrumb crumb = (Breadcrumb) arg; Map<String, String> metadata = new HashMap<>(); if (crumb.getMetadata() != null) { for (Map.Entry<String, String> entry : crumb.getMetadata().entrySet()) { if (entry.getValue() != null) { metadata.put(makeSafe(entry.getKey()), makeSafe(entry.getValue())); } } } addBreadcrumb(crumb.getName(), crumb.getType().toString(), crumb.getTimestamp(), metadata); } else { warn("Attempted to add non-breadcrumb: " + arg); } }
Source:
private SpoilerManager(XMPPConnection connection) { super(connection); ServiceDiscoveryManager.getInstanceFor(connection).addFeature(NAMESPACE_0); }

Target:
private SpoilerManager(XMPPConnection connection) { super(connection); }
Source:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(DbFacade.getInstance().getRoleDao().get( getParameters().<Guid>getParameter(UserRolesVdcParameters.RoleId, Guid.class))); }

Target:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(DbFacade.getInstance().getRoleDao().get( getParameters().<Guid>getParameter(UserRolesVdcParameters.RoleId))); }
Source:
public void setHasResource(boolean hasResource) { this.hasResource = hasResource; }

Target:
private void setHasResource(boolean hasResource) { this.hasResource = hasResource; }
Source:
private void updateMatchedBoards() { String[] prefixes = keyword.split("\\s+"); matchedBoards = boards.stream() .filter(board -> { String[] parts = board.trim().toLowerCase().split("\\s+"); if (prefixes.length > parts.length) { return false; } for (String prefix : prefixes) { if (!board.matches(String.format("(?i:.*\\b%s.*)", prefix))) { return false; } } return true; }) .collect(Collectors.toList()); }

Target:
private void updateMatchedBoards() { String[] keywords = userInput.split("\\s+"); matchedBoards = boards.stream() .filter(board -> { String[] parts = board.trim().toLowerCase().split("\\s+"); if (keywords.length > parts.length) { return false; } for (String keyword : keywords) { if (!board.matches(String.format("(?i:.*\\b%s.*)", keyword))) { return false; } } return true; }) .collect(Collectors.toList()); }
Source:
public Object execute(T input, CalculationMarketData marketData, ReportingRules reportingRules) { List<R> results = IntStream.range(0, marketData.getScenarioCount()) .mapToObj(index -> new DefaultSingleCalculationMarketData(marketData, index)) .map(data -> delegate.execute(input, data, reportingRules)) .collect(toImmutableList()); return (results.size() == 1) ? results.get(0) : results; }

Target:
public Object execute(T input, CalculationMarketData marketData, ReportingRules reportingRules) { List<R> results = IntStream.range(0, marketData.getScenarioCount()) .mapToObj(index -> new DefaultSingleCalculationMarketData(marketData, index)) .map(data -> delegate.execute(input, data, reportingRules)) .collect(toImmutableList()); return (marketData.getScenarioCount() == 1) ? results.get(0) : results; }
Source:
public ArrayList<LunModel> getLunsToRefresh() { ArrayList<LunModel> luns = new ArrayList<LunModel>(); if (!getIsGrouppedByTarget()) { List<LunModel> items = (List<LunModel>) getItems(); for (LunModel lun : items) { if (lun.getIsIncluded() && lun.isAdditionalAvailableSizeSelected() && Linq.firstOrDefault(luns, new Linq.LunPredicate(lun)) == null) { luns.add(lun); } } } return luns; }

Target:
public ArrayList<LunModel> getLunsToRefresh() { ArrayList<LunModel> luns = new ArrayList<LunModel>(); if (!getIsGrouppedByTarget()) { List<LunModel> items = (List<LunModel>) getItems(); for (LunModel lun : items) { if (lun.getIsIncluded()) { if (lun.isAdditionalAvailableSizeSelected() && Linq.firstOrDefault(luns, new Linq.LunPredicate(lun)) == null) { luns.add(lun); } } } } return luns; }
Source:
public AABB transform(Transform transform, float margin) { Vector3f localHalfExtents = new Vector3f(); localHalfExtents.sub(max, min); localHalfExtents.mul(0.5f); localHalfExtents.x += margin; localHalfExtents.y += margin; localHalfExtents.z += margin; Vector3f localCenter = new Vector3f(max); localCenter.add(min); localCenter.mul(0.5f); Matrix3f absBasis = transform.getBasis(); absBasis.m00 = Math.abs(absBasis.m00); absBasis.m01 = Math.abs(absBasis.m01); absBasis.m02 = Math.abs(absBasis.m02); absBasis.m10 = Math.abs(absBasis.m10); absBasis.m11 = Math.abs(absBasis.m11); absBasis.m12 = Math.abs(absBasis.m12); absBasis.m20 = Math.abs(absBasis.m20); absBasis.m21 = Math.abs(absBasis.m21); absBasis.m22 = Math.abs(absBasis.m22); Vector3f center = new Vector3f(localCenter); absBasis.transform(center); center.add(transform.origin); Vector3f extent = new Vector3f(); extent.x = absBasis.getRow(0).dot(localHalfExtents); extent.y = absBasis.getRow(1).dot(localHalfExtents); extent.z = absBasis.getRow(2).dot(localHalfExtents); Vector3f worldMin = new Vector3f(); worldMin.sub(center, extent); Vector3f worldMax = new Vector3f(center).add(extent); return AABB.createMinMax(worldMin, worldMax); }

Target:
public AABB transform(Transform transform, float margin) { Vector3f localHalfExtents = new Vector3f(); localHalfExtents.sub(max, min); localHalfExtents.mul(HALVING_FACTOR); localHalfExtents.x += margin; localHalfExtents.y += margin; localHalfExtents.z += margin; Vector3f localCenter = new Vector3f(max); localCenter.add(min); localCenter.mul(HALVING_FACTOR); Matrix3f absBasis = transform.getBasis(); absBasis.m00 = Math.abs(absBasis.m00); absBasis.m01 = Math.abs(absBasis.m01); absBasis.m02 = Math.abs(absBasis.m02); absBasis.m10 = Math.abs(absBasis.m10); absBasis.m11 = Math.abs(absBasis.m11); absBasis.m12 = Math.abs(absBasis.m12); absBasis.m20 = Math.abs(absBasis.m20); absBasis.m21 = Math.abs(absBasis.m21); absBasis.m22 = Math.abs(absBasis.m22); Vector3f center = new Vector3f(localCenter); absBasis.transform(center); center.add(transform.origin); Vector3f extent = new Vector3f(); extent.x = absBasis.getRow(0).dot(localHalfExtents); extent.y = absBasis.getRow(1).dot(localHalfExtents); extent.z = absBasis.getRow(2).dot(localHalfExtents); Vector3f worldMin = new Vector3f(); worldMin.sub(center, extent); Vector3f worldMax = new Vector3f(center).add(extent); return AABB.createMinMax(worldMin, worldMax); }
Source:
public static void afterAll() { System.setProperty(Framework.NUXEO_TESTING_SYSTEM_PROP, ORIGINAL_TESTING_PROPERTY_VALUE); }

Target:
public static void afterAll() { System.setProperty(NUXEO_TESTING_SYSTEM_PROP, ORIGINAL_TESTING_PROPERTY_VALUE); }
Source:
public LogPage log(LogRequest logRequest) throws GitException { LogCommand logCommand = getGit().log(); String sFilePath = null; try { setRevisionRange(logCommand, logRequest); setPaging(logCommand, logRequest); if (logRequest != null) { sFilePath = logRequest.getFilePath(); if (sFilePath != null && !sFilePath.isEmpty()) { logCommand.addPath(sFilePath); } } Iterator<RevCommit> revIterator = logCommand.call().iterator(); List<Revision> commits = new ArrayList<Revision>(); while (revIterator.hasNext()) { RevCommit commit = revIterator.next(); Revision revision = getRevision(commit, sFilePath); commits.add(revision); } return new LogPage(commits); } catch (GitAPIException | IOException e) { LOG.error("Failed to retrieve log. ", e); throw new GitException(e); } }

Target:
public LogPage log(LogRequest logRequest) throws GitException { LogCommand logCommand = getGit().log(); String sFilePath = null; try { setRevisionRange(logCommand, logRequest); setPaging(logCommand, logRequest); if (logRequest != null) { sFilePath = logRequest.getFilePath(); if (sFilePath != null && !sFilePath.isEmpty()) { logCommand.addPath(sFilePath); } } Iterator<RevCommit> revIterator = logCommand.call().iterator(); List<Revision> commits = new ArrayList<Revision>(); while (revIterator.hasNext()) { RevCommit commit = revIterator.next(); Revision revision = getRevision(commit, sFilePath); commits.add(revision); } return new LogPage(commits); } catch (GitAPIException | IOException exception) { String errorMessage = exception.getMessage(); LOG.error("Failed to retrieve log. ", errorMessage); if (ERROR_LOG_NO_HEAD_EXISTS.equals(errorMessage)) { throw new GitException(errorMessage, ErrorCodes.INIT_COMMIT_WAS_NOT_PERFORMED); }else{ throw new GitException(exception); } } }
Source:
protected void executeCommand() { VDSReturnValue vdsReturnaValue = runVdsCommand(VDSCommandType.StopRebalanceGlusterVolume, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); if (!vdsReturnaValue.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REBALANCE_STOP_FAILED, vdsReturnaValue.getVdsError() .getMessage()); setSucceeded(false); return; } GlusterVolumeTaskStatusEntity rebalanceStatusEntity = (GlusterVolumeTaskStatusEntity) vdsReturnaValue.getReturnValue(); JobExecutionStatus stepStatus = rebalanceStatusEntity.getStatusSummary().getStatus(); if (JobExecutionStatus.FINISHED == stepStatus || JobExecutionStatus.FAILED == stepStatus) { endStepJob(stepStatus, getStepMessageMap(stepStatus), true); } else { endStepJob(JobExecutionStatus.ABORTED, getStepMessageMap(JobExecutionStatus.ABORTED), false); } releaseVolumeLock(); setSucceeded(vdsReturnaValue.getSucceeded()); getReturnValue().setActionReturnValue(rebalanceStatusEntity); }

Target:
protected void executeCommand() { VDSReturnValue vdsReturnaValue = runVdsCommand(VDSCommandType.StopRebalanceGlusterVolume, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); if (!vdsReturnaValue.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REBALANCE_STOP_FAILED, vdsReturnaValue.getVdsError() .getMessage()); setSucceeded(false); return; } GlusterVolumeTaskStatusEntity rebalanceStatusEntity = (GlusterVolumeTaskStatusEntity) vdsReturnaValue.getReturnValue(); JobExecutionStatus stepStatus = rebalanceStatusEntity.getStatusSummary().getStatus(); if (stepStatus != null) { endStepJob(stepStatus, getStepMessageMap(stepStatus), GlusterTaskUtils.getInstance().isTaskSuccess(stepStatus)); } else { endStepJob(JobExecutionStatus.ABORTED, getStepMessageMap(JobExecutionStatus.ABORTED), false); } releaseVolumeLock(); setSucceeded(vdsReturnaValue.getSucceeded()); getReturnValue().setActionReturnValue(rebalanceStatusEntity); }
Source:
public boolean doesChecksumExistInDatasetVersion(DatasetVersion datasetVersion, String selectedChecksum) { if (datasetVersion == null){ throw new NullPointerException("datasetVersion cannot be null"); } String query = "SELECT df.md5 FROM datafile df, filemetadata fm" + " WHERE fm.datasetversion_id = " + datasetVersion.getId() + " AND fm.datafile_id = df.id" + " AND df.md5 = '" + selectedChecksum + "';"; Query nativeQuery = em.createNativeQuery(query); List<String> checksumList = nativeQuery.getResultList(); return checksumList.size() > 0; }

Target:
public boolean doesChecksumExistInDatasetVersion(DatasetVersion datasetVersion, String selectedChecksum) { if (datasetVersion == null){ throw new NullPointerException("datasetVersion cannot be null"); } String query = "SELECT df.md5 FROM datafile df, filemetadata fm" + " WHERE fm.datasetversion_id = " + datasetVersion.getId() + " AND fm.datafile_id = df.id" + " AND df.md5 = '" + selectedChecksum + "';"; Query nativeQuery = em.createNativeQuery(query); List<?> checksumList = nativeQuery.getResultList(); return !checksumList.isEmpty(); }
Source:
public Object fromBytes(byte[] bytes) { try { final Object object; final MessageType type = MessageType.values()[bytes[0]]; final byte[] data = Arrays.copyOfRange(bytes, 1, bytes.length); switch (type) { case USER_MESSAGE: object = userMessageSerde.fromBytes(data); break; case WATERMARK: object = watermarkSerde.fromBytes(data); break; case END_OF_STREAM: object = eosSerde.fromBytes(data); break; default: throw new UnsupportedOperationException(String.format("Message type %s is not supported", type.name())); } return object; } catch (UnsupportedOperationException ue) { throw new SamzaException(ue); } catch (Exception e) { LOGGER.error("Error deserializing with intermediate message serde. If you are upgrading from samza version older" + " than 0.13.1, please upgrade to samza 1.5 first."); throw e; } }

Target:
public Object fromBytes(byte[] bytes) { try { final Object object; final MessageType type; try { type = MessageType.values()[bytes[0]]; } catch (ArrayIndexOutOfBoundsException e) { throw new SamzaException("Error reading the message type from intermediate message. This may happen if you " + "have recently upgraded from samza version older than 0.13.1 or there are still old messages in the " + "intermediate stream.", e); } final byte[] data = Arrays.copyOfRange(bytes, 1, bytes.length); switch (type) { case USER_MESSAGE: object = userMessageSerde.fromBytes(data); break; case WATERMARK: object = watermarkSerde.fromBytes(data); break; case END_OF_STREAM: object = eosSerde.fromBytes(data); break; default: throw new UnsupportedOperationException(String.format("Message type %s is not supported", type.name())); } return object; } catch (UnsupportedOperationException ue) { throw new SamzaException(ue); } catch (Exception e) { throw e; } }