auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void augmentTerminationURIs(Map<String, String> terminateURIs, URI baseUri) { String baseURI = UriBuilder.fromUri(baseUri) .path(LRAParticipantResource.RESOURCE_PATH) .path(id.getName()) .build().toASCIIString(); terminateURIs.computeIfAbsent(COMPLETE, s -> completeMethod != null ? getURI(baseURI, COMPLETE) : null); terminateURIs.computeIfAbsent(COMPENSATE, s -> compensateMethod != null ? getURI(baseURI, COMPENSATE) : null); terminateURIs.computeIfAbsent(STATUS, s -> statusMethod != null ? getURI(baseURI, STATUS) : null); terminateURIs.computeIfAbsent(FORGET, s -> forgetMethod != null ? getURI(baseURI, FORGET) : null); }

Target:
public void augmentTerminationURIs(Map<String, String> terminateURIs, URI baseUri) { String baseURI = UriBuilder.fromUri(baseUri) .path(LRAParticipantResource.RESOURCE_PATH) .path(javaClass.getName()) .build().toASCIIString(); if (!terminateURIs.containsKey(COMPLETE) && completeMethod != null) { terminateURIs.put(COMPLETE, getURI(baseURI, COMPLETE)); } if (!terminateURIs.containsKey(COMPENSATE) && compensateMethod != null) { terminateURIs.put(COMPENSATE, getURI(baseURI, COMPENSATE)); } if (!terminateURIs.containsKey(STATUS) && statusMethod != null) { terminateURIs.put(STATUS, getURI(baseURI, STATUS)); } if (!terminateURIs.containsKey(FORGET) && forgetMethod != null) { terminateURIs.put(FORGET, getURI(baseURI, FORGET)); } if (!terminateURIs.containsKey(AFTER) && afterLRAMethod != null) { terminateURIs.put(AFTER, getURI(baseURI, AFTER)); } }
Source:
void unsubscribeAChild() { State oldState; State newState; do { oldState = state.get(); newState = oldState.removeChild(); } while (!state.compareAndSet(oldState, newState)); unsubscribeActualIfApplicable(newState); }

Target:
void unsubscribeAChild() { State oldState; State newState; final AtomicReference<State> localState = this.state; do { oldState = localState.get(); newState = oldState.removeChild(); } while (!localState.compareAndSet(oldState, newState)); unsubscribeActualIfApplicable(newState); }
Source:
protected void afterInit(SiteRun run) throws Exception { List<Module> modules = Lists.newArrayList(); modules.add(new AbstractModule() { @Override protected void configure() { bind(File.class).annotatedWith(SitePath.class).toInstance(getSitePath()); bind(Browser.class); bind(String.class).annotatedWith(SecureStoreClassName.class) .toProvider(SecureStoreClassNameProvider.class); bind(SecureStore.class).toProvider(SecureStoreProvider.class); } }); modules.add(new GerritServerConfigModule()); Guice.createInjector(modules).injectMembers(this); start(run); }

Target:
protected void afterInit(SiteRun run) throws Exception { List<Module> modules = Lists.newArrayList(); modules.add(new AbstractModule() { @Override protected void configure() { bind(File.class).annotatedWith(SitePath.class).toInstance(getSitePath()); bind(Browser.class); bind(SecureStore.class).toProvider(SecureStoreProvider.class); } }); modules.add(new GerritServerConfigModule()); Guice.createInjector(modules).injectMembers(this); start(run); }
Source:
public void assignRandomTexture() { if(!world.isRemote) { if(getTexturePool().length > 0) { setTexture(getTexturePool()[rand.nextInt(getTexturePool().length)]); } } }

Target:
public void assignRandomTexture() { if(!world.isRemote && getTexturePool() != null) { if(getTexturePool().length > 0) { setTexture(getTexturePool()[rand.nextInt(getTexturePool().length)]); } } }
Source:
private void startAuthMethodChoice() { List<AuthUI.IdpConfig> idpConfigs = getArguments().providerInfo; if (getArguments().isSingleProviderFlow()) { AuthUI.IdpConfig firstIdpConfig = idpConfigs.get(0); String firstProvider = firstIdpConfig.getProviderId(); switch (firstProvider) { case EmailAuthProvider.PROVIDER_ID: setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException( EmailActivity.createIntent(getApplication(), getArguments()), RequestCodes.EMAIL_FLOW))); break; case PhoneAuthProvider.PROVIDER_ID: setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException( PhoneActivity.createIntent( getApplication(), getArguments(), firstIdpConfig.getParams()), RequestCodes.PHONE_FLOW))); break; default: redirectSignIn(firstProvider, null); break; } } else { setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException( AuthMethodPickerActivity.createIntent(getApplication(), getArguments()), RequestCodes.AUTH_PICKER_FLOW))); } }

Target:
private void startAuthMethodChoice() { if (getArguments().isSingleProviderFlow()) { AuthUI.IdpConfig firstIdpConfig = getArguments().providerInfo.get(0); String firstProvider = firstIdpConfig.getProviderId(); switch (firstProvider) { case EmailAuthProvider.PROVIDER_ID: setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException( EmailActivity.createIntent(getApplication(), getArguments()), RequestCodes.EMAIL_FLOW))); break; case PhoneAuthProvider.PROVIDER_ID: setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException( PhoneActivity.createIntent( getApplication(), getArguments(), firstIdpConfig.getParams()), RequestCodes.PHONE_FLOW))); break; default: redirectSignIn(firstProvider, null); break; } } else { setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException( AuthMethodPickerActivity.createIntent(getApplication(), getArguments()), RequestCodes.AUTH_PICKER_FLOW))); } }
Source:
protected String getTokenFromSession(final WebContext context) { return ((Optional<String>) context.getSessionStore().get(context, Pac4jConstants.CSRF_TOKEN)).orElse(null); }

Target:
protected String getTokenFromSession(final WebContext context) { return (String) context.getSessionStore().get(context, Pac4jConstants.CSRF_TOKEN).orElse(null); }
Source:
public void testActionsWithInvert(final IntervalListTools.Action action, final long bases, final int intervals) throws IOException { final IntervalList il = tester(action, true); Assert.assertEquals(il.getBaseCount(), bases, "unexpcted number of bases found."); Assert.assertEquals(il.getIntervals().size(), intervals, "unexpcted number of intervals found."); }

Target:
public void testActionsWithInvert(final IntervalListTools.Action action, final long bases, final int intervals) throws IOException { final IntervalList il = tester(action, true); Assert.assertEquals(il.getBaseCount(), bases, "unexpected number of bases found."); Assert.assertEquals(il.getIntervals().size(), intervals, "unexpected number of intervals found."); }
Source:
public GridShmemCommunicationClient( int connIdx, MetricRegistry mreg, int port, long connTimeout, IgniteLogger log, MessageFormatter formatter ) throws IgniteCheckedException { super(connIdx); assert mreg != null; assert port > 0 && port < 0xffff; assert connTimeout >= 0; shmem = new IpcSharedMemoryClientEndpoint(port, (int)connTimeout, log); writeBuf = ByteBuffer.allocate(8 << 10); writeBuf.order(ByteOrder.nativeOrder()); this.formatter = formatter; sentBytesCntMetric = mreg == null ? null : mreg.longMetric(SENT_BYTES_METRIC_NAME, SENT_BYTES_METRIC_DESC); }

Target:
public GridShmemCommunicationClient( int connIdx, MetricRegistry mreg, int port, long connTimeout, IgniteLogger log, MessageFormatter formatter ) throws IgniteCheckedException { super(connIdx); assert mreg != null; assert port > 0 && port < 0xffff; assert connTimeout >= 0; shmem = new IpcSharedMemoryClientEndpoint(port, (int)connTimeout, log); writeBuf = ByteBuffer.allocate(8 << 10); writeBuf.order(ByteOrder.nativeOrder()); this.formatter = formatter; sentBytesCntMetric = mreg.findMetric(SENT_BYTES_METRIC_NAME); }
Source:
private void initializeFragments() { TaskFragment mTaskFragment = TaskFragment.newInstance(0); mFragmentManager = getSupportFragmentManager(); mFragmentManager.addOnBackStackChangedListener( new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { Fragment f = getSupportFragmentManager().findFragmentById(R.id.container); if (f != null){ updateTitle(f); } } }); updateTitle(mTaskFragment); android.support.v4.app.FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.add(R.id.container, mTaskFragment); ft.commit(); }

Target:
private void initializeFragments() { TaskFragment taskFragment = TaskFragment.newInstance(0); mFragmentManager = getSupportFragmentManager(); mFragmentManager.addOnBackStackChangedListener( new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { Fragment f = getSupportFragmentManager().findFragmentById(R.id.container); if (f != null){ updateTitle(f); } } }); updateTitle(taskFragment); android.support.v4.app.FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.add(R.id.container, taskFragment); ft.commit(); }
Source:
public void forbidsCloneMethodReturnTypeNotMatchingClassName() throws Exception { final String file = "CloneMethodReturnTypeMustMatchClassName.java"; new PMDAssert( file, Matchers.is(false), Matchers.containsString( String.format( PMDValidatorTest.BRACKETS, "CloneMethodReturnTypeMustMatchClassName" ) ) ).validate(); }

Target:
public void forbidsCloneMethodReturnTypeNotMatchingClassName() throws Exception { new PMDAssert( "CloneMethodReturnTypeMustMatchClassName.java", Matchers.is(false), Matchers.containsString( String.format( PMDValidatorTest.BRACKETS, "CloneMethodReturnTypeMustMatchClassName" ) ) ).validate(); }
Source:
public Class<?> getReturnType(Class<?> firstArgumentType) { return BigInteger.class; }

Target:
public Class<?> getReturnType(Class<?> firstArgumentType) { return Long.class; }
Source:
public void startApp() { quitCommand = new Command("Quit", Command.SCREEN, 1); textBox = new TextBox("Hello World", "Some text", 40, 0); textBox.addCommand(quitCommand); textBox.setCommandListener(this); display.setCurrent(textBox); try { do { Thread.sleep(1000); } while (!textBox.isShown()); } catch (Exception e) { System.out.println("FAIL"); } System.out.println("PAINTED"); }

Target:
public void startApp() { quitCommand = new Command("Quit", Command.SCREEN, 1); textBox = new TextBox("Hello World", "Some text", 40, 0); textBox.addCommand(quitCommand); textBox.setCommandListener(this); display.setCurrent(textBox); try { do { Thread.sleep(100); } while (!textBox.isShown()); } catch (InterruptedException e) { System.out.println("FAIL"); } System.out.println("PAINTED"); }
Source:
int maybeCommitActiveTasksPerUserRequested() { if (rebalanceInProgress) { return -1; } else { if (eosBetaEnabled && !eosUpgradeModeEnabled) { for (final Task task : activeTaskIterable()) { if (task.commitRequested() && task.commitNeeded()) { return commitAll(); } } return 0; } else { final Map<TaskId, Map<TopicPartition, OffsetAndMetadata>> consumedOffsetsAndMetadataPerTask = new HashMap<>(); for (final Task task : activeTaskIterable()) { if (task.commitRequested() && task.commitNeeded()) { task.prepareCommit(); final Map<TopicPartition, OffsetAndMetadata> offsetAndMetadata = task.committableOffsetsAndMetadata(); if (!offsetAndMetadata.isEmpty()) { consumedOffsetsAndMetadataPerTask.put(task.id(), offsetAndMetadata); } } } commitOffsetsOrTransaction(consumedOffsetsAndMetadataPerTask); for (final Task task : tasks.values()) { if (consumedOffsetsAndMetadataPerTask.containsKey(task.id())) { task.postCommit(); } } return consumedOffsetsAndMetadataPerTask.size(); } } }

Target:
int maybeCommitActiveTasksPerUserRequested() { if (rebalanceInProgress) { return -1; } else { for (final Task task : activeTaskIterable()) { if (task.commitRequested() && task.commitNeeded()) { return commitInternal(activeTaskIterable()); } } return 0; } }
Source:
public NotesMergeConflictException(NonNoteEntry base, NonNoteEntry ours, NonNoteEntry theirs) { super(MessageFormat.format( JGitText.get().mergeConflictOnNonNoteEntries, base.name(), ours.name(), theirs.name())); }

Target:
public NotesMergeConflictException(NonNoteEntry base, NonNoteEntry ours, NonNoteEntry theirs) { super(MessageFormat.format( JGitText.get().mergeConflictOnNonNoteEntries, name(base), name(ours), name(theirs))); }
Source:
public Certificate parseCertificate(final String cert) { final PemReader certPem = new PemReader(new StringReader(cert)); try { return readCertificateFromPemObject(certPem.readPemObject()); } catch (final Exception e) { throw new InvalidParameterValueException("Invalid Certificate format. Expected X509 certificate. Failed due to " + e.getMessage()); } finally { IOUtils.closeQuietly(certPem); } }

Target:
public Certificate parseCertificate(final String cert) { Preconditions.checkArgument(!Strings.isNullOrEmpty(cert)); final PemReader certPem = new PemReader(new StringReader(cert)); try { return readCertificateFromPemObject(certPem.readPemObject()); } catch (final CertificateException | IOException e) { throw new InvalidParameterValueException("Invalid Certificate format. Expected X509 certificate. Failed due to " + e.getMessage()); } finally { IOUtils.closeQuietly(certPem); } }
Source:
@Override public Path interceptRemainingPath(Path remainingPath) { return remainingPath; }

Target:
public Path interceptRemainingPath(Path remainingPath) { return remainingPath; }
Source:
private void createTooltipShell(Shell parent) { final Display display = parent.getDisplay(); if (fTipShell != null && !fTipShell.isDisposed()) { fTipShell.dispose(); } elementCount = 0; longestString = 0; fTipShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL); fTipShell.addDisposeListener(e -> e.display.removeFilter(SWT.MouseMove, fListener)); fTipShell.addDisposeListener(e -> e.display.removeFilter(SWT.FocusOut, fFocusLostListener)); fTipShell.addListener(SWT.Deactivate, e -> { if (fTipShell.isDisposed()) { fTipShell.dispose(); } }); fToolTipContent = new StringBuilder(); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.marginWidth = 2; gridLayout.marginHeight = 2; fTipShell.setLayout(gridLayout); fTipShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fTipViewer = new Browser(fTipShell, SWT.NO_SCROLL); fTipViewer.setLayout(new GridLayout(3, false)); fTipViewer.addLocationListener(new LocationListener() { @Override public void changing(LocationEvent event) { String timePrefix = "time://"; if (event.location.startsWith(timePrefix)) { String time = event.location.substring(timePrefix.length()); try { long val = Long.parseLong(time); TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(event.getSource(), TmfTimestamp.fromNanos(val))); } catch (NumberFormatException e) { } event.doit = false; } } @Override public void changed(LocationEvent event) { } }); setupControl(fTipViewer); }

Target:
private void createTooltipShell(Shell parent) { final Display display = parent.getDisplay(); if (fTipShell != null && !fTipShell.isDisposed()) { fTipShell.dispose(); } fElementCount = 0; fLongestString = 0; fTipShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL | SWT.RESIZE); fTipShell.addDisposeListener(e -> e.display.removeFilter(SWT.MouseMove, fListener)); fTipShell.addDisposeListener(e -> e.display.removeFilter(SWT.FocusOut, fFocusLostListener)); fTipShell.addListener(SWT.Deactivate, e -> { if (!fTipShell.isDisposed()) { fTipShell.dispose(); } }); fToolTipContent = new StringBuilder(); fTipShell.setLayout(new FillLayout()); fTipShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fTipViewer = new Browser(fTipShell, SWT.NO_SCROLL); fTipViewer.addLocationListener(new LocationListener() { @Override public void changing(LocationEvent event) { String timePrefix = "time://"; if (event.location.startsWith(timePrefix)) { String time = event.location.substring(timePrefix.length()); Long val = Longs.tryParse(time); if (val != null) { TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(event.getSource(), TmfTimestamp.fromNanos(val))); } event.doit = false; } } @Override public void changed(LocationEvent event) { } }); setupControl(fTipViewer); }
Source:
public void removeResultGroupRelations(PerunSession sess, Group resultGroup) { jdbc.update("DELETE FROM groups_groups WHERE result_gid = ?", resultGroup.getId()); jdbc.update("DELETE FROM groups_members WHERE group_id = ? AND membership_type != ?", resultGroup.getId(), MembershipType.DIRECT.getCode()); }

Target:
public void removeResultGroupRelations(PerunSession sess, Group resultGroup) { jdbc.update("DELETE FROM groups_groups WHERE result_gid = ?", resultGroup.getId()); }
Source:
AlternateHandle.Id getAlternateId() { return wrapped.getAlternateId(); }

Target:
private AlternateHandle.Id getAlternateId() { return wrapped.getAlternateId(); }
Source:
private void readTable(String tableName, int startRow, int numRowsToRead) { if (worker != null && !worker.isDone()) { worker.cancel(false); worker = null; } worker = new SwingWorker<ArrayList<Map<String, Object>>, Void>() { @Override protected ArrayList<Map<String, Object>> doInBackground() throws Exception { try { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery( "SELECT * FROM " + tableName + " LIMIT " + Integer.toString(numRowsToRead) + " OFFSET " + Integer.toString(startRow - 1) ); return resultSetToArrayList(resultSet); } catch (SQLException ex) { LOGGER.log(Level.SEVERE, "Failed to get data for table.", ex); } return null; } @Override protected void done() { if (isCancelled()) { return; } super.done(); try { ArrayList<Map<String, Object>> rows = get(); if (Objects.nonNull(rows)) { selectedTableView.setupTable(rows); }else{ selectedTableView.setupTable(Collections.emptyList()); } } catch (InterruptedException | ExecutionException ex) { LOGGER.log(Level.SEVERE, "Unexpected exception while reading table.", ex); } } }; worker.execute(); }

Target:
private void readTable(String tableName, int startRow, int numRowsToRead) { if (worker != null && !worker.isDone()) { worker.cancel(false); worker = null; } worker = new SwingWorker<ArrayList<Map<String, Object>>, Void>() { @Override protected ArrayList<Map<String, Object>> doInBackground() throws Exception { try { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery( "SELECT * FROM " + tableName + " LIMIT " + Integer.toString(numRowsToRead) + " OFFSET " + Integer.toString(startRow - 1) ); return resultSetToArrayList(resultSet); } catch (SQLException ex) { LOGGER.log(Level.SEVERE, "Failed to get data for table " + tableName, ex); } return null; } @Override protected void done() { if (isCancelled()) { return; } super.done(); try { ArrayList<Map<String, Object>> rows = get(); if (Objects.nonNull(rows)) { selectedTableView.setupTable(rows); }else{ selectedTableView.setupTable(Collections.emptyList()); } } catch (InterruptedException | ExecutionException ex) { LOGGER.log(Level.SEVERE, "Unexpected exception while reading table " + tableName, ex); } } }; worker.execute(); }
Source:
public static void main(String[] args) { if (args.length < 4 || args.length > 8) { System.out.println("Please specify your access key, webhook id, enabled or not, url of webhook and events.\n" + "Events can be a maximum of 4 between conversation.created, conversation.updated, message.created, message.updated\n" + "If third argument is enabled, then status of the webhook will be updated to enabled, otherwise will be disabled\n" + "Usage : java -jar <this jar file> test_accesskey webhook_title webhook-url"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Updating conversation webhook.."); String[] arrayOfEvents = new String[args.length - 4]; System.arraycopy(args, 4, arrayOfEvents, 0, args.length - 4); ConversationWebhookUpdateRequest request = new ConversationWebhookUpdateRequest( args[2].equals("enabled") ? ConversationWebhookStatus.ENABLED : ConversationWebhookStatus.DISABLED, args[3], parseConversationWebHookEvents(arrayOfEvents) ); final ConversationWebhook conversationWebhookResponse = messageBirdClient.updateConversationWebhook(args[1], request); System.out.println(conversationWebhookResponse.toString()); } catch (GeneralException | UnauthorizedException exception) { exception.printStackTrace(); } }

Target:
public static void main(String[] args) { if (args.length < 1 || args.length > 8) { System.out.println("Please at least specify your access key and a max of 8 arguments.\n" + "You can also specify a webhook id, enabled or not, url of webhook and events. Default value would be used if you don't\n" + "Events can be a maximum of 4 between conversation.created, conversation.updated, message.created, message.updated\n" + "If third argument is enabled, then status of the webhook will be updated to enabled, otherwise will be disabled\n\n" + "Usage : java -jar <this jar file> test_accesskey(Required) webhook_title(Optional) enabled(Optional) webhook-url(Optional) event1(Optional) event2(Optional) event3(Optional) event4(Optional)"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Updating conversation webhook.."); ConversationWebhookUpdateRequest request = new ConversationWebhookUpdateRequest( getStatus(args) , getWebhookUrl(args), getConversationWebHookEvents(args) ); final ConversationWebhook conversationWebhookResponse = messageBirdClient.updateConversationWebhook(args[1], request); System.out.println(conversationWebhookResponse); } catch (GeneralException | UnauthorizedException exception) { exception.printStackTrace(); } }
Source:
public ByteBuffer getExplicitLac() { LOG.debug("fileInfo:GetLac: {}", explicitLac); ByteBuffer retLac = null; synchronized(this) { if (explicitLac != null) { explicitLac.rewind(); retLac = ByteBuffer.wrap(explicitLac.array()); } } return retLac; }

Target:
public ByteBuffer getExplicitLac() { LOG.debug("fileInfo:GetLac: {}", explicitLac); ByteBuffer retLac = null; synchronized(this) { if (explicitLac != null) { retLac = ByteBuffer.allocate(explicitLac.capacity()); explicitLac.rewind(); retLac.put(explicitLac); explicitLac.rewind(); retLac.flip(); } } return retLac; }
Source:
private void generateActionSignature(Method method) { generateDoc(method); Name methodName = new Name(method.getBase().getName()); methodName.addWords(method.getName().getWords()); javaBuffer.addLine( "Response %s(Action action) {", jaxrsNames.getMethodName(methodName) ); javaBuffer.addLine("throw new UnsupportedOperationException();"); javaBuffer.addLine("}"); }

Target:
private void generateActionSignature(Method method) { generateDoc(method); javaBuffer.addImport(Response.class); javaBuffer.addImport(javaPackages.getXjcPackageName(), "Action"); Name methodName = new Name(method.getBase().getName()); methodName.addWords(method.getName().getWords()); javaBuffer.addLine("Response %s(Action action) {", jaxrsNames.getMethodName(methodName)); javaBuffer.addLine("throw new UnsupportedOperationException();"); javaBuffer.addLine("}"); }
Source:
public void addAPIRevisionDeployment(String apiId, String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeployments) throws APIManagementException { APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiId); if (apiIdentifier == null) { throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId)); } APIRevision apiRevision = apiMgtDAO.getRevisionByRevisionUUID(apiRevisionId); if (apiRevision == null) { throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API Revision with Revision UUID: " + apiRevisionId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiRevisionId)); } APITemplateBuilder builder = null; APIGatewayManager gatewayManager = APIGatewayManager.getInstance(); APIIdentifier revisionApiIdentifier = getLightweightAPIByUUID(apiRevisionId, tenantDomain).getId(); API api = getRevisionAPI(revisionApiIdentifier, apiRevision); api.setSwaggerDefinition(getOpenAPIDefinition(revisionApiIdentifier)); Set<String> environments = new HashSet<>(); for (APIRevisionDeployment apiRevisionDeployment : apiRevisionDeployments) { environments.add(apiRevisionDeployment.getDeployment()); } api.setEnvironments(environments); try { builder = getAPITemplateBuilder(api); } catch (Exception e) { handleException("Error while publishing to Gateway ", e); } Map<String, String> failedEnvironment = gatewayManager.deployAPIRevisionToGateway(api, builder, tenantDomain); apiMgtDAO.addAPIRevisionDeployment(apiRevisionId, apiRevisionDeployments); }

Target:
public void addAPIRevisionDeployment(String apiId, String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeployments) throws APIManagementException { APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiId); if (apiIdentifier == null) { throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId)); } APIRevision apiRevision = apiMgtDAO.getRevisionByRevisionUUID(apiRevisionId); if (apiRevision == null) { throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API Revision with Revision UUID: " + apiRevisionId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiRevisionId)); } APITemplateBuilder builder = null; APIGatewayManager gatewayManager = APIGatewayManager.getInstance(); APIIdentifier revisionApiIdentifier = getLightweightAPIByUUID(apiRevisionId, tenantDomain).getId(); API api = getRevisionAPI(revisionApiIdentifier, apiRevision); Set<String> environments = new HashSet<>(); for (APIRevisionDeployment apiRevisionDeployment : apiRevisionDeployments) { environments.add(apiRevisionDeployment.getDeployment()); } api.setEnvironments(environments); try { builder = getAPITemplateBuilder(api); } catch (Exception e) { handleException("Error while publishing to Gateway ", e); } Map<String, String> failedEnvironment = gatewayManager.deployAPIRevisionToGateway(api, builder, tenantDomain); apiMgtDAO.addAPIRevisionDeployment(apiRevisionId, apiRevisionDeployments); }
Source:
public void process(Exchange exchange) { String issueKey = exchange.getIn().getHeader(ISSUE_KEY, String.class); if (issueKey == null) { throw new IllegalArgumentException("Missing exchange input header named " + ISSUE_KEY); } String comment = exchange.getIn().getBody(String.class); if (comment == null) { throw new IllegalArgumentException("Missing exchange body, it should specify the string comment."); } Integer minutesSpent = exchange.getIn().getHeader(MINUTES_SPENT, Integer.class); if (null == minutesSpent) { throw new IllegalArgumentException("Missing exchange input header named " + MINUTES_SPENT); } JiraRestClient client = ((JiraEndpoint) getEndpoint()).getClient(); IssueRestClient issueClient = client.getIssueClient(); Issue issue = issueClient.getIssue(issueKey).claim(); WorklogInput worklogInput = WorklogInput .create(issue.getSelf(), comment, new DateTime(), minutesSpent); issueClient.addWorklog(issue.getWorklogUri(), worklogInput); }

Target:
public void process(Exchange exchange) { String issueKey = exchange.getIn().getHeader(ISSUE_KEY, String.class); if (issueKey == null) { throw new IllegalArgumentException("Missing exchange input header named " + ISSUE_KEY); } String comment = exchange.getIn().getBody(String.class); if (comment == null) { throw new IllegalArgumentException("Missing exchange body, it should specify the string comment."); } int minutesSpent = exchange.getIn().getHeader(MINUTES_SPENT, DEFAULT_MINUTES_SPENT, int.class); if (DEFAULT_MINUTES_SPENT == minutesSpent) { throw new IllegalArgumentException("Missing exchange input header named " + MINUTES_SPENT); } JiraRestClient client = ((JiraEndpoint) getEndpoint()).getClient(); IssueRestClient issueClient = client.getIssueClient(); Issue issue = issueClient.getIssue(issueKey).claim(); WorklogInput worklogInput = WorklogInput.create(issue.getSelf(), comment, new DateTime(), minutesSpent); issueClient.addWorklog(issue.getWorklogUri(), worklogInput); }
Source:
protected void reloadCache() { schemaMappingCache.invalidateAll(); Set<String> schemas = getSchemaNames(); for (String key : schemaTableMapping.keySet()) { schemaTableMapping.get(key).invalidateAll(); schemaTableMapping.remove(key); } for (final String schema : schemas) { getTableNames(schema); } }

Target:
protected void reloadCache() { schemaMappingCache.invalidateAll(); Set<String> schemas = getSchemaNames(); schemaTableMapping.keySet().forEach(key -> { schemaTableMapping.get(key).invalidateAll(); }); schemaTableMapping.clear(); for (final String schema : schemas) { getTableNames(schema); } }
Source:
default void addPlugins( AbstractJavacPluginParams.Builder builder, BuildRuleResolver resolver, BuildTarget owner, AbstractJavacPluginProperties.Type type) { for (BuildTarget pluginTarget : getPlugins()) { BuildRule pluginRule = resolver.getRule(pluginTarget); if (!(pluginRule instanceof JavacPlugin)) { throw new HumanReadableException( String.format( "%s: only java_annotation_processor or javac_plugin rules can be specified " + "as plugins. %s is not a java_annotation_processor nor javac_plugin.", owner, pluginTarget)); } JavacPlugin javacPluginRule = (JavacPlugin) pluginRule; if (javacPluginRule.getUnresolvedProperties().getType() == type) { builder.addPluginProperties(javacPluginRule.getPluginProperties()); } } }

Target:
default void addPlugins( AbstractJavacPluginParams.Builder builder, BuildRuleResolver resolver, BuildTarget owner, AbstractJavacPluginProperties.Type type) { for (BuildTarget pluginTarget : getPlugins()) { BuildRule pluginRule = resolver.getRule(pluginTarget); if (!(pluginRule instanceof JavacPlugin)) { throw new HumanReadableException( String.format( "%s: only java_annotation_processor or java_plugin rules can be specified " + "as plugins. %s is not a java_annotation_processor nor java_plugin.", owner, pluginTarget)); } JavacPlugin javacPluginRule = (JavacPlugin) pluginRule; if (javacPluginRule.getUnresolvedProperties().getType() == type) { builder.addPluginProperties(javacPluginRule.getPluginProperties()); } } }
Source:
public HomePagePresenter(EventBus eventBus, MyView view, MyProxy proxy) { super(eventBus, view, proxy, ApplicationPresenter.SLOT_SetMainContent); }

Target:
HomePagePresenter(EventBus eventBus, MyView view, MyProxy proxy) { super(eventBus, view, proxy, ApplicationPresenter.SLOT_SetMainContent); }
Source:
private ArtifactoryHttpClient(String artifactoryUrl, String username, String password, String accessToken, Log log) { this.artifactoryUrl = StringUtils.stripEnd(artifactoryUrl, "/"); this.username = username; this.password = password; this.accessToken = accessToken; this.log = log; this.insecureTls = false; }

Target:
private ArtifactoryHttpClient(String artifactoryUrl, String username, String password, String accessToken, Log log) { this.artifactoryUrl = StringUtils.stripEnd(artifactoryUrl, "/"); this.username = username; this.password = password; this.accessToken = accessToken; this.log = log; }
Source:
public void getAssociationLnObjects(final DeviceMessageMetadata deviceMessageMetadata, final com.alliander.osgp.domain.core.valueobjects.smartmetering.GetAssociationLnObjectsRequest request) throws FunctionalException { LOGGER.debug("getAssociationLnObjects for organisationIdentification: for deviceIdentification: {}", deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification()); final SmartMeter smartMeteringDevice = this.domainHelperService.findSmartMeter(deviceMessageMetadata .getDeviceIdentification()); final GetAssociationLnObjectsRequest requestDto = new GetAssociationLnObjectsRequest(); this.osgpCoreRequestMessageSender.send(new RequestMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), smartMeteringDevice.getIpAddress(), requestDto), deviceMessageMetadata.getMessageType(), deviceMessageMetadata.getMessagePriority(), deviceMessageMetadata.getScheduleTime()); }

Target:
public void getAssociationLnObjects(final DeviceMessageMetadata deviceMessageMetadata, final com.alliander.osgp.domain.core.valueobjects.smartmetering.GetAssociationLnObjectsRequest request) throws FunctionalException { LOGGER.debug("getAssociationLnObjects for organisationIdentification: for deviceIdentification: {}", deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification()); final SmartMeter smartMeteringDevice = this.domainHelperService.findSmartMeter(deviceMessageMetadata .getDeviceIdentification()); final GetAssociationLnObjectsRequestDto requestDto = new GetAssociationLnObjectsRequestDto(); this.osgpCoreRequestMessageSender.send(new RequestMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), smartMeteringDevice.getIpAddress(), requestDto), deviceMessageMetadata.getMessageType(), deviceMessageMetadata.getMessagePriority(), deviceMessageMetadata.getScheduleTime()); }
Source:
public void saveCurrentPropertyForAll() { boolean error = false; List<Property> ppList = getProperties(); for (Property pp : ppList) { this.property = pp; Property processProperty = new Property(); processProperty.setTitle(this.property.getTitle()); processProperty.setValue(this.property.getValue()); for (Task task : this.steps) { Process process = task.getProcess(); if (!task.equals(this.currentStep)) { process = prepareProcessWithProperty(process, processProperty); } else { if (!process.getProperties().contains(this.property)) { process.getProperties().add(this.property); } } List<Property> props = process.getProperties(); for (Property nextProcessProperty : props) { if (nextProcessProperty.getTitle() == null) { process.getProperties().remove(nextProcessProperty); } } try { this.serviceManager.getProcessService().save(process); } catch (DataException e) { error = true; logger.error(e.getMessage(), e); Helper.setFehlerMeldung("Properties for process " + process.getTitle() + " could not be saved"); } } } if (!error) { Helper.setMeldung("propertySaved"); } }

Target:
public void saveCurrentPropertyForAll() { List<Property> ppList = getProperties(); for (Property pp : ppList) { this.property = pp; Property processProperty = new Property(); processProperty.setTitle(this.property.getTitle()); processProperty.setValue(this.property.getValue()); for (Task task : this.steps) { Process process = task.getProcess(); if (!task.equals(this.currentStep)) { process = prepareProcessWithProperty(process, processProperty); } else { if (!process.getProperties().contains(this.property)) { process.getProperties().add(this.property); } } List<Property> props = process.getProperties(); for (Property nextProcessProperty : props) { if (nextProcessProperty.getTitle() == null) { process.getProperties().remove(nextProcessProperty); } } try { this.serviceManager.getProcessService().save(process); Helper.setMeldung("propertySaved"); } catch (DataException e) { Helper.setErrorMessage("Properties for process " + process.getTitle() + " could not be saved", logger, e); } } } }
Source:
private void ensureSize() { while (true) { long addressToRemove; Lock entryWriteLock; lruLock.lock(); try { if (currentSize <= maxSize) { break; } int hashCode = UNSAFE.getInt(firstAddress + 24); entryWriteLock = locks.getLockFromHashCode(hashCode).writeLock(); if (!entryWriteLock.tryLock()) { addressToRemove = 0; } else { addressToRemove = UNSAFE.getLong(firstAddress); } } finally { lruLock.unlock(); } if (addressToRemove == 0) { entryWriteLock.lock(); try { lruLock.lock(); try { if (currentSize <= maxSize) { break; } int hashCode = UNSAFE.getInt(firstAddress + 24); Lock innerLock = locks.getLockFromHashCode(hashCode).writeLock(); if (innerLock == entryWriteLock) { addressToRemove = UNSAFE.getLong(firstAddress); } else { addressToRemove = 0; } } finally { lruLock.unlock(); } } finally { if (addressToRemove == 0) { entryWriteLock.unlock(); } } } if (addressToRemove != 0) { if (trace) { log.tracef("Removing entry: %d due to eviction due to size %d being larger than maximum of %d", addressToRemove, currentSize, maxSize); } try { InternalCacheEntry<WrappedBytes, WrappedBytes> ice = offHeapEntryFactory.fromMemory(addressToRemove); passivator.passivate(ice); performRemove(addressToRemove, offHeapEntryFactory.getKey(addressToRemove)); evictionManager.onEntryEviction(Collections.singletonMap(ice.getKey(), ice)); } finally { entryWriteLock.unlock(); } } } }

Target:
private void ensureSize() { while (true) { long addressToRemove; Lock entryWriteLock; lruLock.lock(); try { if (currentSize <= maxSize) { break; } int hashCode = UNSAFE.getInt(firstAddress + 24); entryWriteLock = locks.getLockFromHashCode(hashCode).writeLock(); if (!entryWriteLock.tryLock()) { addressToRemove = 0; } else { addressToRemove = UNSAFE.getLong(firstAddress); } } finally { lruLock.unlock(); } if (addressToRemove == 0) { entryWriteLock.lock(); try { lruLock.lock(); try { if (currentSize <= maxSize) { break; } int hashCode = UNSAFE.getInt(firstAddress + 24); Lock innerLock = locks.getLockFromHashCode(hashCode).writeLock(); if (innerLock == entryWriteLock) { addressToRemove = UNSAFE.getLong(firstAddress); } else { addressToRemove = 0; } } finally { lruLock.unlock(); } } finally { if (addressToRemove == 0) { entryWriteLock.unlock(); } } } if (addressToRemove != 0) { if (trace) { log.tracef("Removing entry: %d due to eviction due to size %d being larger than maximum of %d", addressToRemove, currentSize, maxSize); } InternalCacheEntry<WrappedBytes, WrappedBytes> ice = null; try { ice = offHeapEntryFactory.fromMemory(addressToRemove); performRemove(addressToRemove, offHeapEntryFactory.getKey(addressToRemove)); evictionManager.onEntryEviction(Collections.singletonMap(ice.getKey(), ice)); } finally { entryWriteLock.unlock(); if (ice != null) { passivator.passivate(ice); } } } } }
Source:
public boolean signalContainer(ContainerSignalContext ctx) throws IOException { String pid = ctx.getPid(); Signal signal = ctx.getSignal(); LOG.debug("Sending signal to pid as user {}", signal.getValue(), pid, ctx.getUser()); if (!containerIsAlive(pid)) { return false; } try { killContainer(pid, signal); } catch (IOException e) { if (!containerIsAlive(pid)) { return false; } throw e; } return true; }

Target:
public boolean signalContainer(ContainerSignalContext ctx) throws IOException { String user = ctx.getUser(); String pid = ctx.getPid(); Signal signal = ctx.getSignal(); LOG.debug("Sending signal to pid as user {}", signal.getValue(), pid, user); if (!containerIsAlive(pid)) { return false; } try { killContainer(pid, signal); } catch (IOException e) { if (!containerIsAlive(pid)) { return false; } throw e; } return true; }
Source:
private String runSshCommand(URIish sshUri, FS fs, String command) throws IOException { RemoteSession session = null; Process process = null; StreamCopyThread errorThread = null; try (MessageWriter stderr = new MessageWriter()) { session = SshSessionFactory.getInstance().getSession(sshUri, null, fs, 5_000); process = session.exec(command, 0); errorThread = new StreamCopyThread(process.getErrorStream(), stderr.getRawStream()); errorThread.start(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), Constants.CHARSET))) { return reader.readLine(); } } finally { if (errorThread != null) { try { errorThread.halt(); } catch (InterruptedException e) { } finally { errorThread = null; } } if (process != null) { process.destroy(); } if (session != null) { SshSessionFactory.getInstance().releaseSession(session); } } }

Target:
private String runSshCommand(URIish sshUri, FS fs, String command) throws IOException { RemoteSession session = null; Process process = null; StreamCopyThread errorThread = null; try (MessageWriter stderr = new MessageWriter()) { session = SshSessionFactory.getInstance().getSession(sshUri, null, fs, 5_000); process = session.exec(command, 0); errorThread = new StreamCopyThread(process.getErrorStream(), stderr.getRawStream()); errorThread.start(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), Constants.CHARSET))) { return reader.readLine(); } } finally { if (process != null) { process.destroy(); } if (errorThread != null) { try { errorThread.halt(); } catch (InterruptedException e) { } finally { errorThread = null; } } if (session != null) { SshSessionFactory.getInstance().releaseSession(session); } } }
Source:
private void cleanupInvalidRegistrationIDsForVariant(String variantID, MulticastResult multicastResult, List<String> registrationIDs) { final List<Result> results = multicastResult.getResults(); final Set<String> inactiveTokens = new HashSet<String>(); for (int i = 0; i < results.size(); i++) { final Result result = results.get(i); final String errorCodeName = result.getErrorCodeName(); if (errorCodeName != null) { logger.info(String.format("Processing [%s] error code from GCM response, for registration ID: [%s]", errorCodeName, registrationIDs.get(i))); } String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { Installation installation = clientInstallationService.findInstallationForVariantByDeviceToken(variantID,registrationIDs.get(i)); installation.setDeviceToken(canonicalRegId); logger.info(String.format("Based on returned canonical id from GCM, updating Android installations with registration id [%s] with new token [%s] ", registrationIDs.get(i), canonicalRegId)); clientInstallationService.updateInstallation(installation); } else { if (GCM_ERROR_CODES.contains(errorCodeName)) { inactiveTokens.add(registrationIDs.get(i)); } } } logger.info(String.format("Based on GCM error response codes, deleting %d invalid Android installations", inactiveTokens.size())); clientInstallationService.removeInstallationsForVariantByDeviceTokens(variantID, inactiveTokens); }

Target:
private void cleanupInvalidRegistrationIDsForVariant(String variantID, MulticastResult multicastResult, List<String> registrationIDs) { final List<Result> results = multicastResult.getResults(); final Set<String> inactiveTokens = new HashSet<String>(); for (int i = 0; i < results.size(); i++) { final Result result = results.get(i); final String errorCodeName = result.getErrorCodeName(); if (errorCodeName != null) { logger.info(String.format("Processing [%s] error code from GCM response, for registration ID: [%s]", errorCodeName, registrationIDs.get(i))); } String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { Installation installation = clientInstallationService.findInstallationForVariantByDeviceToken(variantID, canonicalRegId); if (installation != null) { inactiveTokens.add(registrationIDs.get(i)); } else { installation = clientInstallationService.findInstallationForVariantByDeviceToken(variantID,registrationIDs.get(i)); installation.setDeviceToken(canonicalRegId); logger.info(String.format("Based on returned canonical id from GCM, updating Android installations with registration id [%s] with new token [%s] ", registrationIDs.get(i), canonicalRegId)); clientInstallationService.updateInstallation(installation); } } else { if (GCM_ERROR_CODES.contains(errorCodeName)) { inactiveTokens.add(registrationIDs.get(i)); } } } if (! inactiveTokens.isEmpty()) { logger.info(String.format("Based on GCM response data and error codes, deleting %d invalid or duplicated Android installations", inactiveTokens.size())); clientInstallationService.removeInstallationsForVariantByDeviceTokens(variantID, inactiveTokens); } }
Source:
public Map<String, CacheEntry> getLayerBuildMap() { return _layerBuilds.getMap(); }

Target:
Map<String, CacheEntry> getLayerBuildMap() { return _layerBuilds.getMap(); }
Source:
public Collection<AccountGroup.Id> missing(final AccountGroup.Id key) { return new ArrayList<AccountGroup.Id> (); }

Target:
public Collection<AccountGroup.Id> missing(final AccountGroup.Id key) { return Collections.emptyList(); }
Source:
public void testRemoveNonUniqueCaches() throws Exception { lists1.add(LIST_ID1); lists1.add(LIST_ID2); lists2.add(LIST_ID1); lists3.add(LIST_ID2); lists3.add(LIST_ID3); final Set<Geocache> toBeRemoved = RemoveNotUniqueHelper.removeNonUniqueCaches(geoCaches); assertThat(toBeRemoved.size()).isEqualTo(2); assertThat(toBeRemoved.contains(gc1)).isTrue(); assertThat(toBeRemoved.contains(gc2)).isFalse(); assertThat(toBeRemoved.contains(gc3)).isTrue(); }

Target:
public void testRemoveNonUniqueCaches() { lists1.add(LIST_ID1); lists1.add(LIST_ID2); lists2.add(LIST_ID1); lists3.add(LIST_ID2); lists3.add(LIST_ID3); final Set<Geocache> toBeRemoved = RemoveNotUniqueHelper.removeNonUniqueCaches(geoCaches); assertThat(toBeRemoved.size()).isEqualTo(2); assertThat(toBeRemoved.contains(gc1)).isTrue(); assertThat(toBeRemoved.contains(gc2)).isFalse(); assertThat(toBeRemoved.contains(gc3)).isTrue(); }
Source:
void forColon() { ArrayList<Integer> ll = new ArrayList<Integer>(); for (int x:ll) for (int x : ll) }

Target:
void forColon() { int ll[] = new int[10]; for (int x:ll) for (int x :ll) for (int x: ll) for (int x : ll) }
Source:
public Iterable<Bout> search(final String term) throws IOException { throw new UnsupportedOperationException("#search()"); }

Target:
public Iterable<Bout> search(final String term) throws IOException { final List<Bout> result = new ArrayList<>(16); for (final Bout bout : this.iterate()) { if (bout.messages().search(term).iterator().hasNext()) { result.add(bout); } } return result; }
Source:
public static org.jboss.jbossts.txbridge.outbound.OutboundBridge getOutboundBridge() { txbridgeLogger.logger.trace("OutboundBridgeManager.getOutboundBridge()"); try { Transaction transaction = (Transaction)TransactionManager.transactionManager(new InitialContext()).getTransaction(); Uid outboundMappingUid = new Uid(); if(!outboundBridgeMappings.containsKey(outboundMappingUid)) { createMapping(transaction, outboundMappingUid); } return outboundBridgeMappings.get(outboundMappingUid); } catch(SystemException | NamingException e) { txbridgeLogger.logger.error(e); } return null; }

Target:
public static org.jboss.jbossts.txbridge.outbound.OutboundBridge getOutboundBridge() { txbridgeLogger.logger.trace("OutboundBridgeManager.getOutboundBridge()"); try { Transaction transaction = (Transaction)TransactionManager.transactionManager(new InitialContext()).getTransaction(); transctionToUidMappings.putIfAbsent(transaction, new Uid()); Uid outboundMappingUid = transctionToUidMappings.get(transaction); if(!outboundBridgeMappings.containsKey(outboundMappingUid)) { createMapping(transaction, outboundMappingUid); } return outboundBridgeMappings.get(outboundMappingUid); } catch(SystemException | NamingException e) { txbridgeLogger.logger.error(e); } return null; }