auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void validateSubject(final Assertion assertion) throws WSSecurityException { if (assertion.getStatements() == null || assertion.getStatements().isEmpty()) { assertAttAuthzStatements(assertion); } if (!assertion.getAuthnStatements().isEmpty() && assertion.getSubject() == null) { throw new WSSecurityException(ErrorCode.FAILURE, "Assertions containing AuthnStatements require a Subject"); } if (!assertion.getAuthzDecisionStatements().isEmpty() && assertion.getSubject() == null) { throw new WSSecurityException(ErrorCode.FAILURE, "Assertions containing AuthzDecisionStatements require a Subject"); } if (assertion.getSubject() != null) { validateSubject(assertion.getSubject()); } }

Target:
protected void validateSubject(final Assertion assertion) throws WSSecurityException { if (CollectionUtils.isEmpty(assertion.getStatements())) { assertAttAuthzStatements(assertion); } if (CollectionUtils.isNotEmpty(assertion.getAuthnStatements()) && assertion.getSubject() == null) { throw new WSSecurityException(ErrorCode.FAILURE, "Assertions containing AuthnStatements require a Subject"); } if (CollectionUtils.isNotEmpty(assertion.getAuthzDecisionStatements()) && assertion.getSubject() == null) { throw new WSSecurityException(ErrorCode.FAILURE, "Assertions containing AuthzDecisionStatements require a Subject"); } if (assertion.getSubject() != null) { validateSubject(assertion.getSubject()); } }
Source:
protected void onUIDNotExecuted(Exception e) { if (e.getMessage() == null) { return; } notificationService.addNotification(new ImmediateNotification(i18n.get("UIDNotExecuted"), e.getMessage(), Severity.ERROR, Collections.singletonList(new ReportAction(i18n, reportingService, e)))); logger.error("UID.exe not executed", e); }

Target:
protected void onUIDNotExecuted(Exception e) { logger.error("UID.exe not executed", e); if (e.getMessage() == null) { return; } notificationService.addNotification(new ImmediateNotification(i18n.get("UIDNotExecuted"), e.getMessage(), Severity.ERROR, Collections.singletonList(new ReportAction(i18n, reportingService, e)))); }
Source:
public synchronized ArrayList<String> getNames() { if (names == null) { names = new ArrayList<String>(proto.getNameIdsCount()); for (int id : proto.getNameIdsList()) { names.add("TestElement"); } } return names; }

Target:
public synchronized ArrayList<String> getNames() { if (names == null) { names = new ArrayList<String>(proto.getNameIdsCount()); for (int id : proto.getNameIdsList()) { names.add(resources.getString(id)); } } return names; }
Source:
private Database restoreDatabase(int id, String name, String encoding) throws SQLException { Statement s = connection.createStatement(); Database d = new Database(name, encoding); ResultSet tRS = s.executeQuery("SELECT * from `maxwell`.`tables` where database_id = " + id + " ORDER by id"); while (tRS.next()) { String tName = tRS.getString("name"); String tEncoding = tRS.getString("encoding"); String tPKs = null; try { tPKs = tRS.getString("pk"); } catch ( SQLException e ) int tID = tRS.getInt("id"); restoreTable(d, tName, tID, tEncoding, tPKs); } return d; }

Target:
private Database restoreDatabase(int id, String name, String encoding) throws SQLException { Statement s = connection.createStatement(); Database d = new Database(name, encoding); ResultSet tRS = s.executeQuery("SELECT * from `maxwell`.`tables` where database_id = " + id + " ORDER by id"); while (tRS.next()) { String tName = tRS.getString("name"); String tEncoding = tRS.getString("encoding"); String tPKs = tRS.getString("pk"); int tID = tRS.getInt("id"); restoreTable(d, tName, tID, tEncoding, tPKs); } return d; }
Source:
public void eventDispatched(final MIStoppedEvent e) { if (fRunToLineActiveOperation != null) { if (runToLineContinue(e)) { return; } } if (fStepInToSelectionActiveOperation != null) { evaluateStepIntoSelection(e); return; } broadcastStop(e); }

Target:
public void eventDispatched(final MIStoppedEvent e) { if (processRunToLineStoppedEvent(e)) { return; } if (!processStepIntoSelection(e)) { broadcastStop(e); } }
Source:
private boolean notRacyClean(long read) { return read - lastModified > fsTimestampResolution.toMillis() * 11 / 10; }

Target:
private boolean notRacyClean(long read) { return read - lastModified > (fsTimestampResolution.toNanos() + 1) * 11 / 10_000_000; }
Source:
private Mono<TransactionCoordinator> createTransactionCoordinator() { if (isDisposed()) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format( "Cannot create coordinator send link '%s' from a closed session.", TRANSACTION_LINK_NAME)))); } final TransactionCoordinator existing = transactionCoordinator.get(); if (existing != null) { logger.verbose("Coordinator[{}]: Returning existing transaction coordinator.", TRANSACTION_LINK_NAME); return Mono.just(existing); } final String linkName = TRANSACTION_LINK_NAME; return createProducer(linkName, linkName, new Coordinator(), retryOptions, null, false) .map(link -> { final TransactionCoordinator newCoordinator = new TransactionCoordinator(link, messageSerializer); if (transactionCoordinator.compareAndSet(null, newCoordinator)) { return newCoordinator; } else { return transactionCoordinator.get(); } }); }

Target:
private Mono<TransactionCoordinator> createTransactionCoordinator() { if (isDisposed()) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format( "Cannot create coordinator send link '%s' from a closed session.", TRANSACTION_LINK_NAME)))); } final TransactionCoordinator existing = transactionCoordinator.get(); if (existing != null) { logger.verbose("Coordinator[{}]: Returning existing transaction coordinator.", TRANSACTION_LINK_NAME); return Mono.just(existing); } return createProducer(TRANSACTION_LINK_NAME, TRANSACTION_LINK_NAME, new Coordinator(), retryOptions, null, false) .map(link -> { final TransactionCoordinator newCoordinator = new TransactionCoordinator(link, messageSerializer); if (transactionCoordinator.compareAndSet(null, newCoordinator)) { return newCoordinator; } else { return transactionCoordinator.get(); } }); }
Source:
public static int[] intArrayFromString(String str) { if (str.isEmpty()) return new int[0]; String[] split = str.split(","); int[] result = new int[split.length]; for (int i = 0; i < split.length; i++) { result[i] = Integer.parseInt(split[i]); } return result; }

Target:
public static int[] intArrayFromString(String str) { if (str.isEmpty()) { return new int[0]; } String[] split = str.split(","); int[] result = new int[split.length]; for (int i = 0; i < split.length; i++) { result[i] = Integer.parseInt(split[i]); } return result; }
Source:
public String contents() { return abstractContent; }

Target:
public String contents() { return title + "\n" + abstractContent; }
Source:
public ComponentWsResponse component(ComponentWsRequest request) { GetRequest getRequest = new GetRequest(path(ACTION_COMPONENT)) .setParam(DEPRECATED_PARAM_COMPONENT_ID, request.getComponentId()) .setParam(PARAM_COMPONENT, request.getComponent()) .setParam(PARAM_ADDITIONAL_FIELDS, inlineMultipleParamValue(request.getAdditionalFields())) .setParam(PARAM_METRIC_KEYS, inlineMultipleParamValue(request.getMetricKeys())) .setParam(PARAM_DEVELOPER_ID, request.getDeveloperId()) .setParam(PARAM_DEVELOPER_KEY, request.getDeveloperKey()); return call(getRequest, ComponentWsResponse.parser()); }

Target:
public ComponentWsResponse component(ComponentWsRequest request) { GetRequest getRequest = new GetRequest(path(ACTION_COMPONENT)) .setParam(DEPRECATED_PARAM_COMPONENT_ID, request.getComponentId()) .setParam(DEPRECATED_PARAM_COMPONENT_KEY, request.getComponentKey()) .setParam(PARAM_COMPONENT, request.getComponent()) .setParam(PARAM_BRANCH, request.getBranch()) .setParam(PARAM_ADDITIONAL_FIELDS, inlineMultipleParamValue(request.getAdditionalFields())) .setParam(PARAM_METRIC_KEYS, inlineMultipleParamValue(request.getMetricKeys())) .setParam(PARAM_DEVELOPER_ID, request.getDeveloperId()) .setParam(PARAM_DEVELOPER_KEY, request.getDeveloperKey()); return call(getRequest, ComponentWsResponse.parser()); }
Source:
private void scrollIntoView(WebElement e, WebDriver driver) { int eYCoord = e.getLocation().getY(); int eXCoord = e.getLocation().getX(); String id = e.getAttribute("id"); WebElement response = (WebElement) ((JavascriptExecutor)driver).executeScript(scrollJs, eYCoord, eXCoord, id); if(response!=null && response.getAttribute("style").contains("bottom: 0px")){ try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } }

Target:
private void scrollIntoView(WebElement e, WebDriver driver) { final int eYCoord = e.getLocation().getY(); final int eXCoord = e.getLocation().getX(); final String id = e.getAttribute("id"); final JavascriptExecutor executor = (JavascriptExecutor) driver; new Wait<>(Boolean.TRUE) .withTimeout(5, TimeUnit.SECONDS) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return (Boolean)executor.executeScript(scrollJs, eYCoord, eXCoord, id); } }) ; }
Source:
public void testRebaseWithUnstagedTopicChange() throws Exception { writeTrashFile(FILE1, "file1"); git.add().addFilepattern(FILE1).call(); RevCommit commit = git.commit().setMessage("commit1").call(); createBranch(commit, "refs/heads/topic"); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "file2"); git.add().addFilepattern("file2").call(); git.commit().setMessage("commit2").call(); checkoutBranch("refs/heads/master"); writeTrashFile(FILE1, "modified file1"); git.add().addFilepattern(FILE1).call(); git.commit().setMessage("commit3").call(); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "unstaged file2"); RebaseResult result = git.rebase().setUpstream("refs/heads/master") .call(); assertEquals(result.getStatus(), Status.CONFLICTS); assertEquals(result.getConflicts().size(), 1); assertEquals(result.getConflicts().get(0), "file2"); }

Target:
public void testRebaseWithUnstagedTopicChange() throws Exception { writeTrashFile(FILE1, "file1"); git.add().addFilepattern(FILE1).call(); RevCommit commit = git.commit().setMessage("commit1").call(); createBranch(commit, "refs/heads/topic"); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "file2"); git.add().addFilepattern("file2").call(); git.commit().setMessage("commit2").call(); checkoutBranch("refs/heads/master"); writeTrashFile(FILE1, "modified file1"); git.add().addFilepattern(FILE1).call(); git.commit().setMessage("commit3").call(); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "unstaged file2"); RebaseResult result = git.rebase().setUpstream("refs/heads/master") .call(); assertEquals(Status.CONFLICTS, result.getStatus()); assertEquals(1, result.getConflicts().size()); assertEquals("file2", result.getConflicts().get(0)); }
Source:
Datapoint poll(int pollerIndex) { final long now = clock.now(); final long step = Pollers.POLLING_INTERVALS[pollerIndex]; final long stepTime = now / step; rollCount(pollerIndex, now); final int prevPos = 2 * pollerIndex + PREVIOUS; final long value = data[prevPos].getAndSet(init); final long last = lastPollTime[pollerIndex].getAndSet(now); final long missed = (now - last) / step - 1; if (last / step == now / step) { REPOLLED_INTERVALS.increment(); return new Datapoint(now / step * step, value); } else if (last > 0L && missed > 0L) { MISSED_INTERVALS.increment(missed); return Datapoint.UNKNOWN; } else { POLLED_INTERVALS.increment(); return new Datapoint(now / step * step, value); } }

Target:
Datapoint poll(int pollerIndex) { final long now = clock.now(); final long step = Pollers.POLLING_INTERVALS[pollerIndex]; rollCount(pollerIndex, now); final int prevPos = 2 * pollerIndex + PREVIOUS; final long value = data[prevPos].getAndSet(init); final long last = lastPollTime[pollerIndex].getAndSet(now); final long missed = (now - last) / step - 1; if (last / step == now / step) { REPOLLED_INTERVALS.increment(); return new Datapoint(now / step * step, value); } else if (last > 0L && missed > 0L) { MISSED_INTERVALS.increment(missed); return Datapoint.UNKNOWN; } else { POLLED_INTERVALS.increment(); return new Datapoint(now / step * step, value); } }
Source:
public boolean applyDefaultNetworkRulesOnNic(final Connect conn, final String vmName, final Long vmId, final NicTO nic, boolean isFirstNic, boolean checkBeforeApply) { final List<String> nicSecIps = nic.getNicSecIps(); String secIpsStr; final StringBuilder sb = new StringBuilder(); if (nicSecIps != null) { for (final String ip : nicSecIps) { sb.append(ip).append(";"); } secIpsStr = sb.toString(); } else { secIpsStr = "0;"; } return defaultNetworkRules(conn, vmName, nic, vmId, secIpsStr, isFirstNic, checkBeforeApply); }

Target:
public boolean applyDefaultNetworkRulesOnNic(final Connect conn, final String vmName, final Long vmId, final NicTO nic, boolean isFirstNic, boolean checkBeforeApply) { final List<String> nicSecIps = nic.getNicSecIps(); String secIpsStr; final StringBuilder sb = new StringBuilder(); if (nicSecIps != null) { for (final String ip : nicSecIps) { sb.append(ip).append(SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR); } secIpsStr = sb.toString(); } else { secIpsStr = "0" + SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR; } return defaultNetworkRules(conn, vmName, nic, vmId, secIpsStr, isFirstNic, checkBeforeApply); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IResource[] resources = LaunchUtils.getContext(HandlerUtil .getCurrentSelection(event)); final IQ7NamedElement[] elements = TestSuiteUtils.getElements(resources, false, false); List<String> disabledTags = null; if (elements.length == 1) { try { disabledTags = TagsUtil.extractTags(elements[0].getTags()); } catch (ModelException e) { e.printStackTrace(); } } if (disabledTags == null) { disabledTags = new ArrayList<String>(); } final SelectTagDialog dialog = new SelectTagDialog( HandlerUtil.getActiveShell(event), disabledTags); if (dialog.open() == SelectTagDialog.OK) { Job job = new Job(Messages.AddTagAction_Job) { @Override protected IStatus run(final IProgressMonitor monitor) { monitor.beginTask(Messages.AddTagAction_Task, elements.length); try { WriteAccessChecker writeAccessChecker = new WriteAccessChecker(); if (!writeAccessChecker.makeResourceWritable(elements)) { return Status.CANCEL_STATUS; } } catch (CoreException e) { return e.getStatus(); } for (IQ7NamedElement element : elements) { if (monitor.isCanceled()) break; try { doAddTag(element, dialog.getResult(), dialog.getTagName(), monitor); } catch (ModelException e) { RcpttPlugin.log(e); } monitor.worked(1); } monitor.done(); return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IResource[] resources = LaunchUtils.getContext(HandlerUtil .getCurrentSelection(event)); final IQ7NamedElement[] elements = TestSuiteUtils.getElements(resources, false, false); List<String> disabledTags = null; if (elements.length == 1) { try { disabledTags = TagsUtil.extractTags(elements[0].getTags()); } catch (ModelException e) { e.printStackTrace(); } } if (disabledTags == null) { disabledTags = new ArrayList<String>(); } final SelectTagDialog dialog = new SelectTagDialog( HandlerUtil.getActiveShell(event), disabledTags); if (dialog.open() == SelectTagDialog.OK) { Job job = new Job(Messages.AddTagAction_Job) { @Override protected IStatus run(final IProgressMonitor monitor) { monitor.beginTask(Messages.AddTagAction_Task, elements.length); try { WriteAccessChecker writeAccessChecker = new WriteAccessChecker(dialog.getShell()); if (!writeAccessChecker.makeResourceWritable(elements)) { return Status.CANCEL_STATUS; } } catch (CoreException e) { return e.getStatus(); } for (IQ7NamedElement element : elements) { if (monitor.isCanceled()) break; try { doAddTag(element, dialog.getResult(), dialog.getTagName(), monitor); } catch (ModelException e) { RcpttPlugin.log(e); } monitor.worked(1); } monitor.done(); return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } return null; }
Source:
public Injector getParentInjector() { ISuite suite = m_testContext.getSuite(); Injector injector = suite.getParentInjector(); if (injector == null) { Module parentModule = GuiceHelper.getParentModule(m_testContext); List<Module> modules = new ArrayList<>(); if (parentModule != null) { modules.add(parentModule); } injector = GuiceHelper.createInjector(m_testContext, modules); suite.setParentInjector(injector); } return injector; }

Target:
public Injector getParentInjector() { ISuite suite = m_testContext.getSuite(); Injector injector = suite.getParentInjector(); if (injector == null) { injector = GuiceHelper.createInjector(m_testContext, Collections.emptyList()); suite.setParentInjector(injector); } return injector; }
Source:
public void flush() throws IOException, SQLException { File file = closeCurrentFile(); UploadAndCopyTask task = new UploadAndCopyTask(file, batchRows, s3KeyPrefix + UUID.randomUUID().toString()); executorService.submit(task); fileCount++; totalRows += batchRows; batchRows = 0; openNewFile(); }

Target:
public void flush() throws IOException, SQLException { File file = closeCurrentFile(); String s3KeyName = s3KeyPrefix + UUID.randomUUID().toString(); UploadTask uploadTask = new UploadTask(file, batchRows, s3KeyName); Future<Void> uploadFuture = executorService.submit(uploadTask); uploadAndCopyFutures.add(uploadFuture); CopyTask copyTask = new CopyTask(uploadFuture, s3KeyName); uploadAndCopyFutures.add(executorService.submit(copyTask)); fileCount++; totalRows += batchRows; batchRows = 0; openNewFile(); }
Source:
private void generateNewPassword(U userAccount) { assertNotNew(userAccount); if (!userAccount.getUserAccountData().isPasswordGenerationPossible()) { throw Exceptions.createHandled() .withNLSKey("UserAccountConroller.cannotGeneratePasswordForOwnUser") .handle(); } userAccount.getUserAccountData().getLogin().forceGenerationOfPassword(); userAccount.getMapper().update(userAccount); auditLog.neutral("AuditLog.passwordGenerated") .causedByCurrentUser() .forUser(userAccount.getUniqueName(), userAccount.getUserAccountData().getLogin().getUsername()) .forTenant(String.valueOf(userAccount.getTenant().getId()), userAccount.getTenant().fetchValue().getTenantData().getName()) .log(); }

Target:
private void generateNewPassword(U userAccount) { assertNotNew(userAccount); if (!userAccount.getUserAccountData().isPasswordGenerationPossible()) { throw Exceptions.createHandled() .withNLSKey("UserAccountConroller.cannotGeneratePasswordForOwnUser") .handle(); } userAccount.getUserAccountData().getLogin().forceGenerationOfPassword(); userAccount.getMapper().update(userAccount); auditLog.neutral("AuditLog.passwordGenerated") .causedByCurrentUser() .forUser(userAccount.getUniqueName(), userAccount.getUserAccountData().getLogin().getUsername()) .forTenant(String.valueOf(userAccount.getTenant().getId()), matchingTenants.fetchCachedRequiredTenant(userAccount.getTenant()).getTenantData().getName()) .log(); }
Source:
public void update(int delta) throws SlickException { collisionHandler.checkCollision(Model.getCurrentRoom().getBubbles()); for (Player player : Model.getPlayers()) { if (!collisionHandler.checkCollision(player)) { player.setFalling(true); } if (!anyLive()) { notifyObserver(); loseLife(player); } collisionHandler.checkCollision(player.getRopes()); } if (this.getTimers().getLevelTimeLeft() <= 0) { fireEvent(new ControllerEvent(this, ControllerEvent.OUTOFTIME, "Out of time")); notifyObserver(); for (Player p : Model.getPlayers()) { loseLife(p); } } ArrayList<PowerUp> powers = Model.getShortPower(); if (powers.size() > 0) { for (PowerUp power : powers) { if (collisionHandler.checkCollision(power)) { if (timeLeft >= getTimers().getLevelTimeLeft() + 30000) { Model.deleteShortPower(power); } } power.move(); if (!collisionHandler.checkCollision(power)) { timeLeft = getTimers().getLevelTimeLeft(); } } } for (Player p : Model.getPlayers()) { p.move(); } notifyObserver(); processInput(delta); updateRopes(); updateBubble(); }

Target:
public void update(int delta) throws SlickException { collisionHandler.checkCollision(Model.getCurrentRoom().getBubbles()); for (Player player : Model.getPlayers()) { if (!collisionHandler.checkCollision(player)) { player.setFalling(true); } if (!anyLife()) { notifyObserver(); loseLife(player); } collisionHandler.checkCollision(player.getRopes()); } if (this.getTimers().getLevelTimeLeft() <= 0) { fireEvent(new ControllerEvent(this, ControllerEvent.OUTOFTIME, "Out of time")); notifyObserver(); for (Player p : Model.getPlayers()) { loseLife(p); } } List<PowerUp> powers = Model.getShortPower(); if (powers.size() > 0) { for (PowerUp power : powers) { if (collisionHandler.checkCollision(power)) { if (timeLeft >= getTimers().getLevelTimeLeft() + 30000) { Model.deleteShortPower(power); } } power.move(); if (!collisionHandler.checkCollision(power)) { timeLeft = getTimers().getLevelTimeLeft(); } } } for (Player p : Model.getPlayers()) { p.move(); } notifyObserver(); processInput(delta); updateRopes(); updateBubble(); }
Source:
private static String propertiesAsString(Properties properties) { StringBuilder props = new StringBuilder(); boolean apos = false; for(Object obj : properties.keySet()) { String value = (String) properties.get(obj); if(apos) { props.append("'"); } props.append((String) obj + ">" + value); apos = true; } return props.toString(); }

Target:
private static String propertiesAsString(Properties properties) { StringBuilder props = new StringBuilder(); boolean apos = false; for(Object obj : properties.keySet()) { String value = properties.get(obj).toString(); if(apos) { props.append("<'>"); } props.append(obj.toString() + "<>" + value); apos = true; } return props.toString(); }
Source:
public RemoteViews getViewAt(int position) { final RemoteViews remoteView = new RemoteViews( context.getPackageName(), R.layout.bookmarks_widget_list_row); ItemList item = listItemList.get(position); remoteView.setTextViewText(R.id.Suratitle, item.sura + ""); remoteView.setTextViewText(R.id.Surametadata, context.getResources().getText(R.string.quran_page) + " " + item.page); remoteView.setImageViewResource(R.id.WidgetFavIcon, R.drawable.ic_favorite); Bundle extras = new Bundle(); extras.putInt("page", item.page); Intent fillInIntent = new Intent(); fillInIntent.putExtras(extras); remoteView.setOnClickFillInIntent(R.id.widget_item, fillInIntent); return remoteView; }

Target:
public RemoteViews getViewAt(int position) { final RemoteViews remoteView = new RemoteViews( context.getPackageName(), R.layout.bookmarks_widget_list_row); SuraPageItem item = suraPageItemList.get(position); remoteView.setTextViewText(R.id.sura_title, item.sura + ""); remoteView.setTextViewText(R.id.sura_meta_data, context.getResources().getText(R.string.quran_page) + " " + item.page); remoteView.setImageViewResource(R.id.widget_favorite_icon, R.drawable.ic_favorite); Bundle extras = new Bundle(); extras.putInt("page", item.page); Intent fillInIntent = new Intent(); fillInIntent.putExtras(extras); remoteView.setOnClickFillInIntent(R.id.widget_item, fillInIntent); return remoteView; }
Source:
public ResponseEntity<?> get(@PathVariable final String name, final NativeWebRequest request) { final EventType eventType = eventTypeService.get(name); return status(HttpStatus.OK).body(eventType); }

Target:
public ResponseEntity<?> get(@PathVariable final String name, final NativeWebRequest request) throws NoSuchEventTypeException, InternalNakadiException{ final EventType eventType = eventTypeService.get(name); return status(HttpStatus.OK).body(eventType); }
Source:
public void setUp() { refToRelease = new LinkedList<ReferenceCounted>(); request = new DefaultFullBinaryMemcacheRequest( Unpooled.copiedBuffer("key", CharsetUtil.UTF_8), Unpooled.wrappedBuffer(new byte[]{1, 3, 4, 9}), Unpooled.copiedBuffer("some value", CharsetUtil.UTF_8)); request.setReserved((short) 534); request.setMagic((byte) 0x03); request.setOpcode((byte) 0x02); request.setKeyLength((short) 32); request.setExtrasLength((byte) 34); request.setDataType((byte) 43); request.setTotalBodyLength(345); request.setOpaque(3); request.setCas(345345L); refToRelease.add(request); }

Target:
public void setUp() { request = new DefaultFullBinaryMemcacheRequest( Unpooled.copiedBuffer("key", CharsetUtil.UTF_8), Unpooled.wrappedBuffer(new byte[]{1, 3, 4, 9}), Unpooled.copiedBuffer("some value", CharsetUtil.UTF_8)); request.setReserved((short) 534); request.setMagic((byte) 0x03); request.setOpcode((byte) 0x02); request.setKeyLength((short) 32); request.setExtrasLength((byte) 34); request.setDataType((byte) 43); request.setTotalBodyLength(345); request.setOpaque(3); request.setCas(345345L); }
Source:
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) { if (obj instanceof EditedStyleItem) { final EditedStyleItem item = (EditedStyleItem) obj; ResourceValue resValue; if (item.isAttr()) { resValue = myConfiguration.getResourceResolver().findResValue(item.getValue(), false); if (resValue == null) { LOG.error("Unable to resolve " + item.getValue()); } } else { resValue = item.getItemResourceValue(); } final Color color = ResourceHelper.resolveColor(myConfiguration.getResourceResolver(), resValue); myComponent.configure(item, color); myComponent.setBorder(isSelected ? mySelectedBorder : myUnselectedBorder); } else { LOG.error(String.format("Object passed to ColorRendererEditor has class %1$s instead of ItemResourceValueWrapper", obj.getClass().getName())); } return myComponent; }

Target:
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) { if (obj instanceof EditedStyleItem) { final EditedStyleItem item = (EditedStyleItem) obj; final Color color = ResourceHelper.resolveColor(myConfiguration.getResourceResolver(), item.getItemResourceValue()); myComponent.configure(item, color); myComponent.setBorder(isSelected ? mySelectedBorder : myUnselectedBorder); } else { LOG.error(String.format("Object passed to ColorRendererEditor has class %1$s instead of ItemResourceValueWrapper", obj.getClass().getName())); } return myComponent; }
Source:
public FluxSender adapt(MessageChannel bindingTarget, MethodParameter parameter) { DisposableFluxSender disposableFluxSender = new DisposableFluxSender(); FluxSender fluxSender = resultPublisher -> { MonoProcessor<Void> sendResult = MonoProcessor.create(); disposableFluxSender.setDisposable(resultPublisher .doOnError(e -> this.log.error("Error during processing: ", e)) .retry() .subscribe( result -> bindingTarget.send(result instanceof Message<?> ? (Message<?>) result : MessageBuilder.withPayload(result).build()), sendResult::onError, sendResult::onComplete)); return sendResult; }; disposableFluxSender.setWrappedFluxSender(fluxSender); return disposableFluxSender; }

Target:
public FluxSender adapt(MessageChannel bindingTarget, MethodParameter parameter) { return new DefaultFluxSender(result -> bindingTarget.send(result instanceof Message<?> ? (Message<?>) result : MessageBuilder.withPayload(result).build())); }
Source:
private BigInteger postJob(CloseableHttpClient httpClient, JSONObject credentials, File bundle, JSONObject submitConfig) throws ClientProtocolException, IOException { String url = getSubmitURL(credentials, bundle); HttpPost postJobWithConfig = new HttpPost(url); postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); postJobWithConfig.addHeader("Authorization", getAPIKey(credentials.get("userid").toString(), credentials.get("password").toString())); FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM); StringBody configBody = new StringBody(submitConfig.serialize(), ContentType.APPLICATION_JSON); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("bin", bundleBody).addPart("json", configBody) .build(); postJobWithConfig.setEntity(reqEntity); JSONObject jsonResponse = getJsonResponse(httpClient, postJobWithConfig); Topology.STREAMS_LOGGER.info("Streaming Analytics Service submit job response:" + jsonResponse.serialize()); Object jobId = jsonResponse.get("jobId"); if (jobId == null) return BigInteger.valueOf(-1); return new BigInteger(jobId.toString()); }

Target:
private BigInteger postJob(CloseableHttpClient httpClient, JSONObject credentials, File bundle, JSONObject submitConfig) throws ClientProtocolException, IOException { String url = getSubmitURL(credentials, bundle); HttpPost postJobWithConfig = new HttpPost(url); postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAPIKey(credentials.get("userid").toString(), credentials.get("password").toString())); FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM); StringBody configBody = new StringBody(submitConfig.serialize(), ContentType.APPLICATION_JSON); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("bin", bundleBody).addPart("json", configBody) .build(); postJobWithConfig.setEntity(reqEntity); JSONObject jsonResponse = getJsonResponse(httpClient, postJobWithConfig); Topology.STREAMS_LOGGER.info("Streaming Analytics Service submit job response:" + jsonResponse.serialize()); Object jobId = jsonResponse.get("jobId"); if (jobId == null) return BigInteger.valueOf(-1); return new BigInteger(jobId.toString()); }
Source:
private void handleConsumed(ConsumerRecord record) { Span span = startAndFinishConsumerSpan(record); tracing.propagation().keys().forEach(key -> record.headers().remove(key)); tracing.propagation().injector(injector) .inject(span.context(), record); }

Target:
private void handleConsumed(ConsumerRecord record) { Span span = startAndFinishConsumerSpan(record); tracing.propagation().keys().forEach(key -> record.headers().remove(key)); injector.inject(span.context(), record); }
Source:
private void sortSymbols(List<TypedVar> symbols) { Collections.sort(symbols, new Comparator<TypedVar>() { @Override public int compare(TypedVar o1, TypedVar o2) { return o1.getName().compareTo(o2.getName()); } }); }

Target:
private void sortSymbols(List<TypedVar> symbols) { Collections.sort(symbols, Ordering.natural().onResultOf(new Function<TypedVar, Comparable>() { @Nullable @Override public Comparable apply(@Nullable TypedVar input) { if (input == null) return null; return input.getName(); } })); }
Source:
public ReferenceCountingResourceHolder.Releaser increment() { synchronized (lock) { if (refcount <= 0) { throw new ISE("Already closed!"); } refcount++; final AtomicBoolean didRelease = new AtomicBoolean(); return new Releaser() { @Override public void release() { if (didRelease.compareAndSet(false, true)) { decrement(); } else { log.warn("WTF?! release called but we are already released!"); } } @Override protected void finalize() throws Throwable { if (didRelease.compareAndSet(false, true)) { log.warn("Not released! Object was[%s], releasing on finalize of releaser.", object); decrement(); } } }; } }

Target:
public Releaser increment() { synchronized (lock) { if (refcount <= 0) { throw new ISE("Already closed!"); } refcount++; return new Releaser() { final AtomicBoolean didRelease = new AtomicBoolean(); @Override public void close() { if (didRelease.compareAndSet(false, true)) { decrement(); } else { log.warn("WTF?! release called but we are already released!"); } } @Override protected void finalize() throws Throwable { if (didRelease.compareAndSet(false, true)) { log.warn("Not released! Object was[%s], releasing on finalize of releaser.", object); decrement(); } } }; } }
Source:
public String toString() { if (_partitions.size() > 0) { try { List<Integer> partitionList = _partitionsV2.stream().map(Integer::parseInt).collect(Collectors.toList()); return String.format("%s(%s), partitionsV2=%s, partitions=%s, dependencies=%s", getDatastreamTaskName(), _connectorType, LogUtils.logNumberArrayInRange(partitionList), LogUtils.logNumberArrayInRange(_partitions), _dependencies); } catch (NumberFormatException e) { LOG.error(e.getMessage()); return String.format("%s(%s), partitionsV2=%s, partitions=%s, dependencies=%s", getDatastreamTaskName(), _connectorType, String.join(",", _partitionsV2), LogUtils.logNumberArrayInRange(_partitions), _dependencies); } } return String.format("%s(%s), partitionsV2=%s, partitions=%s, dependencies=%s", getDatastreamTaskName(), _connectorType, String.join(",", _partitionsV2), LogUtils.logNumberArrayInRange(_partitions), _dependencies); }

Target:
public String toString() { String partitionsV2FormatLog = String.join(",", _partitionsV2); if (_partitions.size() > 0) { try { List<Integer> partitionList = _partitionsV2.stream().map(Integer::parseInt).collect(Collectors.toList()); partitionsV2FormatLog = LogUtils.logNumberArrayInRange(partitionList); } catch (NumberFormatException e) { LOG.error(e.getMessage()); } } return String.format("%s(%s), partitionsV2=%s, partitions=%s, dependencies=%s", getDatastreamTaskName(), _connectorType, partitionsV2FormatLog, LogUtils.logNumberArrayInRange(_partitions), _dependencies); }
Source:
private Map<String, String> readAccountMetadataFromBlobID(String blobID) { long startTimeMs = System.currentTimeMillis(); Future<GetBlobResult> resultF = accountService.router.get().getBlob(blobID, new GetBlobOptionsBuilder().build()); try { GetBlobResult result = resultF.get(); accountService.accountServiceMetrics.accountFetchFromAmbryTimeInMs.update( System.currentTimeMillis() - startTimeMs); int blobSize = (int) result.getBlobInfo().getBlobProperties().getBlobSize(); InputStream input = new ReadableStreamChannelInputStream(result.getBlobDataChannel()); byte[] bytes = Utils.readBytesFromStream(input, blobSize); JSONObject object = new JSONObject(new String(bytes, Charsets.UTF_8)); Map<String, String> map = new HashMap<>(); object.keySet().stream().forEach(key -> map.put(key, object.getString(key))); return map; } catch (Exception e) { logger.debug("Failed to read account metadata from blob id={}", blobID, e); accountService.accountServiceMetrics.accountFetchFromAmbryServerErrorCount.inc(); } return null; }

Target:
private Map<String, String> readAccountMetadataFromBlobID(String blobID) { long startTimeMs = System.currentTimeMillis(); Future<GetBlobResult> resultF = router.get().getBlob(blobID, new GetBlobOptionsBuilder().build()); try { GetBlobResult result = resultF.get(); accountServiceMetrics.accountFetchFromAmbryTimeInMs.update(System.currentTimeMillis() - startTimeMs); int blobSize = (int) result.getBlobInfo().getBlobProperties().getBlobSize(); InputStream input = new ReadableStreamChannelInputStream(result.getBlobDataChannel()); byte[] bytes = Utils.readBytesFromStream(input, blobSize); JSONObject object = new JSONObject(new String(bytes, Charsets.UTF_8)); Map<String, String> map = new HashMap<>(); object.keySet().stream().forEach(key -> map.put(key, object.getString(key))); return map; } catch (Exception e) { logger.error("Failed to read account metadata from blob id={}", blobID, e); accountServiceMetrics.accountFetchFromAmbryServerErrorCount.inc(); } return null; }
Source:
public void addExtentSummary(ExtentSummary product) throws Exception { if (!product.isValid()) { LOGGER.log(Level.FINE,"[" + getName() + "] product " + product.getId() + " has no extent information; won't add to extent table"); return; } Connection connection = connect(); PreparedStatement addProduct = connection.prepareStatement( "INSERT INTO " + EXTENT_TABLE + "(" + EXTENT_INDEX_ID + "," + EXTENT_START_TIME + "," + EXTENT_END_TIME + "," + EXTENT_MIN_LAT + "," + EXTENT_MAX_LAT + "," + EXTENT_MIN_LONG + "," + EXTENT_MAX_LONG + ") VALUES (?, ?, ?, ?, ?, ?, ?)" ); addProduct.setLong(1, product.getId()); if (product.getStartTime() != null) { addProduct.setLong(2, product.getStartTime().getTime()); } else { addProduct.setNull(2,Types.BIGINT); } if (product.getEndTime() != null) { addProduct.setLong(3, product.getEndTime().getTime()); } else { addProduct.setNull(3,Types.BIGINT); } if (product.getMinLatitude() != null) { addProduct.setDouble(4, product.getMinLatitude()); } else { addProduct.setNull(4,Types.DECIMAL); } if (product.getMaxLatitude() != null) { addProduct.setDouble(5, product.getMaxLatitude()); } else { addProduct.setNull(5, Types.DECIMAL); } if (product.getMinLongitude() != null) { addProduct.setDouble(6, product.getMinLongitude()); } else { addProduct.setNull(6,Types.DECIMAL); } if (product.getMaxLongitude() != null) { addProduct.setDouble(7, product.getMaxLongitude()); } else { addProduct.setNull(7,Types.DECIMAL); } addProduct.executeUpdate(); addProduct.clearParameters(); addProduct.close(); }

Target:
public void addExtentSummary(ExtentSummary product) throws Exception { if (!product.isValid()) { LOGGER.log(Level.FINE,"[" + getName() + "] product " + product.getIndexId() + " has no extent information; won't add to extent table"); return; } Connection connection = connect(); String sql = "INSERT INTO " + EXTENT_TABLE + "(" + EXTENT_INDEX_ID + "," + EXTENT_START_TIME + "," + EXTENT_END_TIME + "," + EXTENT_MIN_LAT + "," + EXTENT_MAX_LAT + "," + EXTENT_MIN_LONG + "," + EXTENT_MAX_LONG + ") VALUES (?, ?, ?, ?, ?, ?, ?)"; try (PreparedStatement addProduct = connection.prepareStatement(sql)) { addProduct.setLong(1, product.getIndexId()); if (product.getStartTime() != null) { addProduct.setLong(2, product.getStartTime().getTime()); } else { addProduct.setNull(2, Types.BIGINT); } if (product.getEndTime() != null) { addProduct.setLong(3, product.getEndTime().getTime()); } else { addProduct.setNull(3, Types.BIGINT); } if (product.getMinLatitude() != null) { addProduct.setBigDecimal(4, product.getMinLatitude()); } else { addProduct.setNull(4, Types.DECIMAL); } if (product.getMaxLatitude() != null) { addProduct.setBigDecimal(5, product.getMaxLatitude()); } else { addProduct.setNull(5, Types.DECIMAL); } if (product.getMinLongitude() != null) { addProduct.setBigDecimal(6, product.getMinLongitude()); } else { addProduct.setNull(6, Types.DECIMAL); } if (product.getMaxLongitude() != null) { addProduct.setBigDecimal(7, product.getMaxLongitude()); } else { addProduct.setNull(7, Types.DECIMAL); } addProduct.executeUpdate(); addProduct.clearParameters(); } }
Source:
public void testFindSubscription() throws Throwable { Subscription subscription = subscriptionFactory.createCreditCardSubscription(defaultPlanWithTrialDays.getId(), defaultCard.getId(), defaultCustomer); subscription.save(); Subscription foundSubscription = new Subscription().find(subscription.getId()); Assert.assertEquals(subscription.getId(), foundSubscription.getId()); Assert.assertEquals(subscription.getPostbackUrl(), foundSubscription.getPostbackUrl()); Assert.assertEquals(subscription.getCharges(), foundSubscription.getCharges()); Assert.assertEquals(subscription.getCreatedAt(), foundSubscription.getCreatedAt()); Assert.assertEquals(subscription.getCurrentPeriodEnd(), foundSubscription.getCurrentPeriodEnd()); Assert.assertEquals(subscription.getCurrentPeriodStart(), foundSubscription.getCurrentPeriodStart()); Assert.assertEquals(subscription.getCurrentTransaction(), foundSubscription.getCurrentTransaction()); Assert.assertEquals(subscription.getCustomer().getId(), foundSubscription.getCustomer().getId()); Assert.assertEquals(subscription.getMetadata(), foundSubscription.getMetadata()); Assert.assertEquals(PaymentMethod.CREDIT_CARD, foundSubscription.getPaymentMethod()); Assert.assertEquals(subscription.getPlan().getId(), foundSubscription.getPlan().getId()); Assert.assertEquals(subscription.getStatus(), foundSubscription.getStatus()); Assert.assertEquals(1, subscription.getMetadata().size()); }

Target:
public void testFindSubscription() throws Throwable { Subscription subscription = subscriptionFactory.createCreditCardSubscription(defaultPlanWithTrialDays.getId(), defaultCard.getId(), defaultCustomer); subscription.save(); Subscription foundSubscription = new Subscription().find(subscription.getId()); Assert.assertEquals(subscription.getId(), foundSubscription.getId()); Assert.assertEquals(subscription.getPostbackUrl(), foundSubscription.getPostbackUrl()); Assert.assertEquals(subscription.getCharges(), foundSubscription.getCharges()); Assert.assertEquals(subscription.getCreatedAt(), foundSubscription.getCreatedAt()); Assert.assertEquals(subscription.getCurrentPeriodEnd(), foundSubscription.getCurrentPeriodEnd()); Assert.assertEquals(subscription.getCurrentPeriodStart(), foundSubscription.getCurrentPeriodStart()); Assert.assertEquals(subscription.getCurrentTransaction(), foundSubscription.getCurrentTransaction()); Assert.assertEquals(subscription.getCustomer().getId(), foundSubscription.getCustomer().getId()); Assert.assertEquals(PaymentMethod.CREDIT_CARD, foundSubscription.getPaymentMethod()); Assert.assertEquals(subscription.getPlan().getId(), foundSubscription.getPlan().getId()); Assert.assertEquals(subscription.getStatus(), foundSubscription.getStatus()); Assert.assertEquals("some_metadata",foundSubscription.getMetadata().keySet().iterator().next()); Assert.assertEquals("123456",foundSubscription.getMetadata().values().iterator().next()); }
Source:
public IPartHost getOrCreateHost( EntityPlayer player, int side, TileEntity te ) { World w = te.getWorldObj(); int x = te.xCoord; int y = te.yCoord; int z = te.zCoord; if ( te instanceof IMultipartTile && this.canConvertTiles && player.getHeldItem().getItem() instanceof IPartItem ) { Block blk = AEApi.instance().blocks().blockMultiPart.block(); ItemStack what = AEApi.instance().blocks().blockMultiPart.stack( 1 ); try { this.mergeIntoMicroblockContainer.invoke( null, what, player, w, x, y, z, side, blk, 0 ); } catch ( Throwable e ) { this.canConvertTiles = false; return null; } } TileEntity tx = w.getTileEntity( x, y, z ); if ( tx instanceof IPartHost ) return ( IPartHost ) tx; return null; }

Target:
public IPartHost getOrCreateHost( EntityPlayer player, int side, TileEntity te ) { final World w = te.getWorldObj(); final int x = te.xCoord; final int y = te.yCoord; final int z = te.zCoord; final boolean isPartItem = player != null && player.getHeldItem() != null && player.getHeldItem().getItem() instanceof IPartItem; if ( te instanceof IMultipartTile && this.canConvertTiles && isPartItem ) { final Block blk = AEApi.instance().blocks().blockMultiPart.block(); final ItemStack what = AEApi.instance().blocks().blockMultiPart.stack( 1 ); try { this.mergeIntoMicroblockContainer.invoke( null, what, player, w, x, y, z, side, blk, 0 ); } catch ( Throwable e ) { this.canConvertTiles = false; return null; } } final TileEntity tx = w.getTileEntity( x, y, z ); if ( tx instanceof IPartHost ) return ( IPartHost ) tx; return null; }
Source:
public String getPodPhase() { Pod pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod != null) { return pod.getStatus().getPhase(); } return "Unkown"; }

Target:
public String getPodPhase() { Pod pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod != null) { return pod.getStatus().getPhase(); } return "Unknown"; }
Source:
public void testIncreaseStoragePoolMasterVersion() { int result = dao.increaseStoragePoolMasterVersion(existingPool.getId()); assertEquals(result, existingPool.getmaster_domain_version() + 1); }

Target:
public void testIncreaseStoragePoolMasterVersion() { int result = dao.increaseStoragePoolMasterVersion(existingPool.getId()); storage_pool dbPool = dao.get(existingPool.getId()); assertEquals(result, existingPool.getmaster_domain_version() + 1); assertEquals(result, dbPool.getmaster_domain_version()); }
Source:
public <T> Iterable<T> map(Class<T> type, Response<RowModel> response) { Collection<T> result = new ArrayList<>(); RowModel model; while ((model = response.next()) != null) { if (model.variables().length > 1) { throw new RuntimeException( "Scalar response queries must only return one column. Make sure your cypher query only returns one item."); } for (int i = 0; i < model.variables().length; i++) { final Object o = model.getValues()[0]; T value = Optional.ofNullable(ConvertibleTypes.REGISTRY.get(type.getCanonicalName())) .map(ac -> (AttributeConverter<T, Object>)(type.isArray() ? ac.forArray : ac.forScalar)) .map(c -> c.toEntityAttribute(o)) .orElse((T)Utils.coerceTypes(type, o)); result.add((T) value); } } return result; }

Target:
public <T> Iterable<T> map(Class<T> type, Response<RowModel> response) { Collection<T> result = new ArrayList<>(); RowModel model; while ((model = response.next()) != null) { result.add(extractColumnValue(type, model)); } return result; }
Source:
public ValueMatcher makeRowOffsetMatcher(final ImmutableBitmap rowBitmap) { final IntIterator iter = descending ? BitmapOffset.getReverseBitmapOffsetIterator(rowBitmap) : rowBitmap.iterator(); if(!iter.hasNext()) { return new ValueMatcher() { @Override public boolean matches() { return false; } }; } if (descending) { return new ValueMatcher() { int iterOffset = Integer.MAX_VALUE; @Override public boolean matches() { int currentOffset = holder.get().getOffset(); if (iterOffset == currentOffset) { return true; } if (iterOffset < currentOffset) { return false; } while (iter.hasNext()) { iterOffset = iter.next(); if (iterOffset == currentOffset) { return true; } else if (iterOffset < currentOffset) { return false; } } return false; } }; } else { return new ValueMatcher() { int iterOffset = -1; @Override public boolean matches() { int currentOffset = holder.get().getOffset(); if (iterOffset == currentOffset) { return true; } if (iterOffset > currentOffset) { return false; } while (iter.hasNext()) { iterOffset = iter.next(); if (iterOffset == currentOffset) { return true; } else if (iterOffset > currentOffset) { return false; } } return false; } }; } }

Target:
public ValueMatcher makeRowOffsetMatcher(final ImmutableBitmap rowBitmap) { final IntIterator iter = descending ? BitmapOffset.getReverseBitmapOffsetIterator(rowBitmap) : rowBitmap.iterator(); if(!iter.hasNext()) { return new BooleanValueMatcher(false); } if (descending) { return new ValueMatcher() { int iterOffset = Integer.MAX_VALUE; @Override public boolean matches() { int currentOffset = holder.get().getOffset(); while (iterOffset > currentOffset && iter.hasNext()) { iterOffset = iter.next(); } return iterOffset == currentOffset; } }; } else { return new ValueMatcher() { int iterOffset = -1; @Override public boolean matches() { int currentOffset = holder.get().getOffset(); while (iterOffset < currentOffset && iter.hasNext()) { iterOffset = iter.next(); } return iterOffset == currentOffset; } }; } }
Source:
public void setInstant(Instant instant) { assert instant != null : "instant may not be null"; this.instant = instant; }

Target:
public void setInstant(Instant instant) { this.instant = Objects.requireNonNull(instant,"instant may not be null"); }