auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void modifyAST(IIndex index, IMarker marker) { IASTTranslationUnit ast; try { ITranslationUnit tu = getTranslationUnitViaEditor(marker); ast = tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); } catch (CoreException e) { CheckersUiActivator.log(e); return; } IASTNode astNode = null; if (isCodanProblem(marker)) { astNode = getASTNodeFromMarker(marker, ast); } if (astNode == null || !(astNode instanceof IASTCastExpression)) { return; } ASTRewrite r = ASTRewrite.create(ast); INodeFactory factory = ast.getASTNodeFactory(); IASTCastExpression oldcast = (IASTCastExpression) astNode; IASTCastExpression newcast = factory.newCastExpression(getCastType(), oldcast.getTypeId().copy(CopyStyle.withLocations), oldcast.getOperand().copy(CopyStyle.withLocations)); r.replace(oldcast, newcast, null); Change c = r.rewriteAST(); try { c.perform(new NullProgressMonitor()); } catch (CoreException e) { CheckersUiActivator.log(e); return; } try { marker.delete(); } catch (CoreException e) { CheckersUiActivator.log(e); } }

Target:
public void modifyAST(IIndex index, IMarker marker) { IASTTranslationUnit ast; try { ITranslationUnit tu = getTranslationUnitViaEditor(marker); ast = tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); } catch (CoreException e) { CheckersUiActivator.log(e); return; } IASTNode astNode = null; if (isCodanProblem(marker)) { astNode = getASTNodeFromMarker(marker, ast); } if (astNode == null || !(astNode instanceof IASTCastExpression)) { return; } ASTRewrite r = ASTRewrite.create(ast); INodeFactory factory = ast.getASTNodeFactory(); IASTCastExpression oldcast = (IASTCastExpression) astNode; IASTCastExpression newcast = factory.newCastExpression(getCastType(), oldcast.getTypeId().copy(CopyStyle.withLocations), oldcast.getOperand().copy(CopyStyle.withLocations)); r.replace(oldcast, newcast, null); Change c = r.rewriteAST(); try { c.perform(new NullProgressMonitor()); marker.delete(); } catch (CoreException e) { CheckersUiActivator.log(e); } }
Source:
synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) { List<String> newSegments = new ArrayList<>(); for (String onlineSegment : onlineSegments) { if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) { newSegments.add(onlineSegment); } } List<String> newSegmentZKMetadataPaths = new ArrayList<>(); for (String segment: newSegments) { newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment); } List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true); for (int i = 0; i < newSegments.size(); i++) { String segment = newSegments.get(i); Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i)); _segmentToTimeRangeMSCache.put(segment, range); } _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments); _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache); }

Target:
public synchronized void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) { for (String segment : onlineSegments) { _intervalMap.computeIfAbsent(segment, k -> extractIntervalFromSegmentZKMetaZNRecord(k, _propertyStore.get(_segmentZKMetadataPathPrefix + k, null, AccessOption.PERSISTENT))); } _intervalMap.keySet().retainAll(onlineSegments); _intervalTree = new IntervalTree<>(_intervalMap); }
Source:
private TracingContext traceToMap(Map<String, Object> map) { long startParse = System.nanoTime(); return () -> { long now = System.nanoTime(); long duration = now - startParse; long startOffset = now - startRequestNanos; map.put("startOffset", startOffset); map.put("duration", duration); }; }

Target:
private TracingContext traceToMap(Map<String, Object> map) { long start = System.nanoTime(); return () -> { long now = System.nanoTime(); long duration = now - start; long startOffset = now - startRequestNanos; map.put("startOffset", startOffset); map.put("duration", duration); }; }
Source:
public void testIllegalMinMax() { try { new FixedDoubleHistogram(-200, 3.0, 3.0); fail("exception expected"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("bucketCount")); } }

Target:
public void testIllegalMinMax() { try { new FixedDoubleHistogram(200, 3.0, 3.0); fail("exception expected"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("min")); assertTrue(e.getMessage().contains("must be smaller than")); } }
Source:
public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) { P4Client p4 = getP4(baseDir, false); return p4.latestChange(); }

Target:
public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) { P4Client p4 = getP4(execCtx.isServer() ? baseDir : workingdir(baseDir)); return p4.latestChange(); }
Source:
public void putJobCompletedNotification() throws IOException, SignatureException { UUID notificationUUID = null; try { final PutJobCompletedNotificationRegistrationSpectraS3Response response = client .putJobCompletedNotificationRegistrationSpectraS3( new PutJobCompletedNotificationRegistrationSpectraS3Request("test@test.test")); notificationUUID = response.getJobCompletedNotificationRegistrationResult().getId(); assertThat(response.getStatusCode(), is(201)); } finally { client.deleteJobCompletedNotificationRegistrationSpectraS3( new DeleteJobCompletedNotificationRegistrationSpectraS3Request(notificationUUID)); } }

Target:
public void putJobCompletedNotification() throws IOException, SignatureException { UUID notificationUUID = null; try { final PutJobCompletedNotificationRegistrationSpectraS3Response response = client .putJobCompletedNotificationRegistrationSpectraS3( new PutJobCompletedNotificationRegistrationSpectraS3Request("test@test.test")); notificationUUID = response.getJobCompletedNotificationRegistrationResult().getId(); assertThat(response.getStatusCode(), is(201)); } finally { if (notificationUUID != null) { client.deleteJobCompletedNotificationRegistrationSpectraS3( new DeleteJobCompletedNotificationRegistrationSpectraS3Request(notificationUUID)); } } }
Source:
public static Pair<Boolean, String> checkFingerPrint(String expected, PublicKey key) throws Exception { if (key == null) { return null; } if (expected == null) { return new Pair<>(false, getFingerPrint(key)); } String comps[] = expected.split(":", 2); DigestFactory factory; if (comps[0].length() > 2) { factory = BuiltinDigests.fromString(comps[0]); if (factory == null) { return new Pair<>(false, getFingerPrint(key)); } } else { factory = BuiltinDigests.md5; expected = "MD5:" + expected; } String fingerprint = getFingerPrint(factory, key); return new Pair<>(expected.equals(fingerprint), fingerprint); }

Target:
public static Pair<Boolean, String> checkFingerPrint(String expected, PublicKey key) throws Exception { if (key == null) { return null; } if (GenericUtils.isEmpty(expected)) { return new Pair<>(false, getFingerPrint(key)); } String comps[] = GenericUtils.trimToEmpty(expected).split(":", 2); if (GenericUtils.length(comps) < 2) { return new Pair<>(false, getFingerPrint(key)); } DigestFactory factory; if (comps[0].length() > 2) { factory = BuiltinDigests.fromString(comps[0]); if (factory == null) { return new Pair<>(false, getFingerPrint(key)); } expected = comps[0].toUpperCase() + ":" + comps[1]; } else { factory = BuiltinDigests.md5; expected = factory.getName().toUpperCase() + ":" + expected; } String fingerprint = getFingerPrint(factory, key); boolean matches = BuiltinDigests.md5.getName().equals(factory.getName()) ? expected.equalsIgnoreCase(fingerprint) : expected.equals(fingerprint); return new Pair<>(matches, fingerprint); }
Source:
private boolean isValidationNecessaryOnReads(TableReference tableRef) { return isValidationNecessary(tableRef) && validateLocksOnReads; }

Target:
private boolean isValidationNecessaryOnReads(TableReference tableRef) { return validateLocksOnReads && isValidationNecessary(tableRef); }
Source:
public Trader(String name, double cashInHand) { super(); this.name = name; this.cashInHand = cashInHand; this.stocksOwned = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }

Target:
public Trader(String name, double cashInHand) { this.name = name; this.cashInHand = cashInHand; this.stocksOwned = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }
Source:
public boolean isEnabled() { GitHistoryPage page = getPage(); if (page == null) return false; String head; try { head = page.getInputInternal().getRepository().getFullBranch(); } catch (IOException e) { head = null; } IStructuredSelection sel = getSelection(page); if (sel.size() != 1) return false; Object o = sel.getFirstElement(); if (!(o instanceof PlotCommit)) return false; PlotCommit commit = (PlotCommit) o; int refCount = commit.getRefCount(); for (int i = 0; i < refCount; i++) { String refName = commit.getRef(i).getName(); if (refName.equals(head)) continue; if (refName.startsWith(Constants.R_HEADS) || refName.startsWith(Constants.R_REMOTES)) return true; } return false; }

Target:
public boolean isEnabled() { GitHistoryPage page = getPage(); Repository repository = getRepository(page); if (repository == null) return false; List<Ref> branchesOfCommit; try { branchesOfCommit = getBranchesOfCommit(page, repository); } catch (IOException e) { Activator.logError("Could not calculate Enablement", e); return false; } return !branchesOfCommit.isEmpty(); }
Source:
public void testStartProcessFromNodeIdsWithTimer() throws Exception { final String processId = "simple.restartWithTimer"; assertNotNull(deploymentService); KModuleDeploymentUnit deploymentUnit = new KModuleDeploymentUnit(GROUP_ID, ARTIFACT_ID, VERSION); deploymentService.deploy(deploymentUnit); units.add(deploymentUnit); assertNotNull(processService); Long processInstanceId = processService.startProcess(deploymentUnit.getIdentifier(), processId, singletonMap("var_a", 3)); assertNotNull(processInstanceId); Thread.sleep(3000); processService.abortProcessInstance(processInstanceId); Collection<NodeInstanceDesc> timed = runtimeDataService.getProcessInstanceFullHistoryByType(processInstanceId, EntryType.SKIPPED, new QueryContext(0, 0)); assertThat(timed.size(), is(1)); Collection<NodeInstanceDesc> aborted = runtimeDataService.getProcessInstanceFullHistoryByType(processInstanceId, EntryType.ABORTED, new QueryContext(0, 0)); assertThat(aborted.size(), is(1)); String[] nodeIds = aborted.stream().map(e -> e.getNodeId()).toArray(String[]::new); processInstanceId = processService.startProcessFromNodeIds(deploymentUnit.getIdentifier(), processId, singletonMap("var_a", 3), nodeIds); runtimeDataService.getTasksByProcessInstanceId(processInstanceId).forEach(e -> { Task task = this.userTaskService.getTask(e); assertThat(task.getName(), is("Third Task")); this.userTaskService.start(e, "katy"); this.userTaskService.complete(e, "katy", emptyMap()); }); ProcessInstance pi = processService.getProcessInstance(processInstanceId); assertNull(pi); }

Target:
public void testStartProcessFromNodeIdsWithTimer() throws InterruptedException { final String processId = "simple.restartWithTimer"; assertNotNull(deploymentService); KModuleDeploymentUnit deploymentUnit = new KModuleDeploymentUnit(GROUP_ID, ARTIFACT_ID, VERSION); deploymentService.deploy(deploymentUnit); units.add(deploymentUnit); assertNotNull(processService); Long processInstanceId = processService.startProcess(deploymentUnit.getIdentifier(), processId, singletonMap("var_a", 3)); assertNotNull(processInstanceId); TimeUnit.SECONDS.sleep(3); processService.abortProcessInstance(processInstanceId); Collection<NodeInstanceDesc> skipped = runtimeDataService.getProcessInstanceFullHistoryByType(processInstanceId, EntryType.SKIPPED, new QueryContext(0, 0)); assertThat(skipped.size(), is(1)); Collection<NodeInstanceDesc> aborted = runtimeDataService.getProcessInstanceFullHistoryByType(processInstanceId, EntryType.ABORTED, new QueryContext(0, 0)); assertThat(aborted.size(), is(1)); String[] nodeIds = aborted.stream().map(NodeInstanceDesc::getNodeId).toArray(String[]::new); processInstanceId = processService.startProcessFromNodeIds(deploymentUnit.getIdentifier(), processId, singletonMap("var_a", 3), nodeIds); runtimeDataService.getTasksByProcessInstanceId(processInstanceId).forEach(e -> { Task task = this.userTaskService.getTask(e); assertThat(task.getName(), is("Third Task")); this.userTaskService.start(e, "katy"); this.userTaskService.complete(e, "katy", emptyMap()); }); ProcessInstance pi = processService.getProcessInstance(processInstanceId); assertNull(pi); }
Source:
protected boolean isAnyAppConfiguredInSourceServerXml() { boolean bConfigured = false; Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.size() > 0) { log.debug("Application configuration is found in server.xml."); bConfigured = true; } return bConfigured; }

Target:
protected boolean isAnyAppConfiguredInSourceServerXml() { Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.size() > 0) { log.debug("Application configuration is found in server.xml."); return true; } else { return false; } }
Source:
protected void exportAsContext() { if (EDatabaseConnTemplate.isSchemaNeeded(getConnection().getDatabaseType()) && schemaText != null && StringUtils.isEmpty(schemaText.getText())) { MessageDialog.openWarning(getShell(), Messages.getString("AbstractForm.ExportAsContext"), Messages.getString("DatabaseForm.checkSchema")); } collectContextParams(); super.exportAsContext(); }

Target:
protected void exportAsContext() { if (EDatabaseConnTemplate.isSchemaNeeded(getConnection().getDatabaseType()) && schemaText != null && StringUtils.isBlank(schemaText.getText())) { boolean confirm = MessageDialog.openConfirm(getShell(), Messages.getString("AbstractForm.ExportAsContext"), Messages.getString("DatabaseForm.checkSchema")); if(!confirm) { return; } } collectContextParams(); super.exportAsContext(); }
Source:
public boolean validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().asConvertible().integer(); getModel().getNumOfDesktops().validateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().validateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().getMaxAssignedVmsPerUser().validateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(1, 1000000) }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid()); getModel().setIsPoolTabValid(true); return super.validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid(); }

Target:
public boolean validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().asConvertible().integer(); getModel().getNumOfDesktops().validateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().validateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().getMaxAssignedVmsPerUser().validateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(1, Short.MAX_VALUE) }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid()); getModel().setIsPoolTabValid(true); return super.validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid() && getModel().getMaxAssignedVmsPerUser().getIsValid(); }
Source:
private void doConcurrentPutInTx(String s) throws Exception { for (int i = 0; i < totalNumberOfBuckets; i++) { synchronized (list) { list.add(i); } } Thread[] threads = new Thread[totalNumberOfBuckets]; for (int i = 0; i < totalNumberOfBuckets; i++) { threads[i] = new Thread(() -> doPutOpInTx(s)); } for (int i = 0; i < totalNumberOfBuckets; i++) { threads[i].start(); } for (int i = 0; i < totalNumberOfBuckets; i++) { threads[i].join(); } }

Target:
private void doConcurrentPutInTx(String s) throws Exception { for (int i = 0; i < totalNumberOfBuckets; i++) { queue.add(i); } ExecutorService pool = Executors.newCachedThreadPool(); Collection<Callable<Object>> tasks = new ArrayList<>(); Callable<Object> task = () -> { doPutOpInTx(s); return null; }; for (int i = 0; i < totalNumberOfBuckets; i++) { tasks.add(task); } List<Future<Object>> futures = pool.invokeAll(tasks); for (Future future : futures) { future.get(); } }
Source:
private void addEditLink(WebMvcLinkBuilder selfLinkBuilder, GoalDto goalResource) { goalResource.add(selfLinkBuilder.withRel(JsonRootLinkRelationProvider.EDIT_REL)); }

Target:
private void addEditLink(WebMvcLinkBuilder selfLinkBuilder, GoalDto goalResource) { goalResource.add(selfLinkBuilder.withRel(IanaLinkRelations.EDIT)); }
Source:
public VM() { mVmStatic = new VmStatic(); mVmDynamic = new VmDynamic(); mVmStatistics = new VmStatistics(); mVmStatic.setImages(new java.util.ArrayList<DiskImage>()); mVmStatic.setInterfaces(new java.util.ArrayList<VmNetworkInterface>()); mDiskMap = new java.util.HashMap<String, DiskImage>(); mCdPath = ""; mFloppyPath = ""; mRunAndPause = false; _diskSize = 0; }

Target:
public VM() { mVmStatic = new VmStatic(); mVmDynamic = new VmDynamic(); mVmStatistics = new VmStatistics(); mVmStatic.setImages(new ArrayList<DiskImage>()); mVmStatic.setInterfaces(new ArrayList<VmNetworkInterface>()); mDiskMap = new java.util.HashMap<String, DiskImage>(); mCdPath = ""; mFloppyPath = ""; mRunAndPause = false; _diskSize = 0; }
Source:
private void setCurentCommitInfo(String revision) { fCommitInfo.reset(); Iterator<Map.Entry<String, RevisionInfo>> itr1 = fRevisions.entrySet().iterator(); while (itr1.hasNext()) { Entry<String, RevisionInfo> entry = itr1.next(); if (entry.getKey().equals(revision)) { System.out.println("Looking at the Current patchset : " + entry.getValue().getNumber()); fCommitInfo.setCommit(revision); fCommitInfo.setMessage(entry.getValue().getCommit().getMessage()); fCommitInfo.setParents(entry.getValue().getCommit().getParents()); fCommitInfo.setAuthor(entry.getValue().getCommit().getAuthor()); fCommitInfo.setCommitter(entry.getValue().getCommit().getCommitter()); } else { System.out.println("Looking at the other patchset : " + entry.getValue().getNumber()); } } }

Target:
private void setCurentCommitInfo(String revision) { fCommitInfo.reset(); Iterator<Map.Entry<String, RevisionInfo>> itr1 = fRevisions.entrySet().iterator(); while (itr1.hasNext()) { Entry<String, RevisionInfo> entry = itr1.next(); if (entry.getKey().equals(revision)) { fCommitInfo.setCommit(revision); fCommitInfo.setMessage(entry.getValue().getCommit().getMessage()); fCommitInfo.setParents(entry.getValue().getCommit().getParents()); fCommitInfo.setAuthor(entry.getValue().getCommit().getAuthor()); fCommitInfo.setCommitter(entry.getValue().getCommit().getCommitter()); } } }
Source:
public void testQueryProcessByVariables() { Map<String, Object> variables = Collections.<String, Object> singletonMap("var_a", "a1"); Map<String, Object> attributes = Collections.<String, Object> singletonMap("processId", "test.test_A"); List<ProcessInstanceWithVarsDesc> data = advanceVariableDataService.queryProcessByVariables(attributes, variables, new QueryContext()); Assert.assertEquals(3, data.size()); for (ProcessInstanceWithVarsDesc p : data) { Assert.assertEquals("a1", p.getVariables().get("var_a")); Assert.assertEquals("test.test_A", p.getProcessId()); } }

Target:
public void testQueryProcessByVariables() { List<QueryParam> variables = list(equalsTo("var_a", "a1"), equalsTo("var_b", "1")); List<QueryParam> attributes = list(equalsTo(PROCESS_ATTR_DEFINITION_ID, "test.test_A")); List<ProcessInstanceWithVarsDesc> data = advanceVariableDataService.queryProcessByVariables(attributes, variables, queryContext); if (queryContext.getCount() > 0) { Assert.assertThat(data.size(), is(queryContext.getCount())); } for (ProcessInstanceWithVarsDesc p : data) { Assert.assertEquals("a1", p.getVariables().get("var_a")); Assert.assertEquals("1", p.getVariables().get("var_b")); Assert.assertEquals("test.test_A", p.getProcessId()); } }
Source:
void updateThreadPoolSize(int numThreads) { m_scheduler.setCorePoolSize(numThreads); LOG.info("Updated PBD to use " + numThreads + " threads to enforce retention policy"); }

Target:
void updateThreadPoolSize(int numThreads) { if (numThreads != m_scheduler.getCorePoolSize()) { m_scheduler.setCorePoolSize(numThreads); LOG.info("Updated PBD to use " + numThreads + " threads to enforce retention policy"); } }
Source:
protected void postProcessHeaderLines() { final List<String> headerLines = getHeaderLines(); final Pattern blankLine = Pattern.compile(EMPTY_LINE_PATTERN); for (final String line : headerLines) { try { if (line.isEmpty()) { headerRegexps.add(blankLine); } else { headerRegexps.add(Pattern.compile(line)); } } catch (final PatternSyntaxException ex) { throw new IllegalArgumentException("line " + (headerRegexps.size() + 1) + " in header specification" + " is not a regular expression", ex); } } }

Target:
protected void postProcessHeaderLines() { final List<String> headerLines = getHeaderLines(); for (String line : headerLines) { try { if (line.isEmpty()) { headerRegexps.add(BLANK_LINE); } else { headerRegexps.add(Pattern.compile(line)); } } catch (final PatternSyntaxException ex) { throw new IllegalArgumentException("line " + (headerRegexps.size() + 1) + " in header specification" + " is not a regular expression", ex); } } }
Source:
public void setActivePart(IAction action, IWorkbenchPart targetPart) { if(targetPart instanceof IMavenProjectHolder) { this.projectHolder = (IMavenProjectHolder) targetPart; } else { this.projectHolder = null; } }

Target:
public void setActivePart(IAction action, IWorkbenchPart targetPart) { mavenProject = (MavenProject) targetPart.getAdapter(MavenProject.class); }
Source:
public boolean tryAdd(final EventData eventData) throws PayloadSizeExceededException { if (eventData == null) { throw new IllegalArgumentException("eventData cannot be null."); } final EventDataImpl eventDataImpl = (EventDataImpl) eventData; final int size; try { size = getSize(eventDataImpl, events.isEmpty()); } catch (java.nio.BufferOverflowException exception) { throw new PayloadSizeExceededException(String.format(Locale.US, "Size of the payload exceeded Maximum message size: %s kb", this.maxMessageSize / 1024)); } if (this.currentSize + size > this.maxMessageSize) { return false; } this.events.add(eventDataImpl); this.currentSize += size; return true; }

Target:
public boolean tryAdd(final EventData eventData) throws PayloadSizeExceededException { if (eventData == null) { throw new IllegalArgumentException("eventData cannot be null"); } final EventDataImpl eventDataImpl = (EventDataImpl) eventData; final int size; try { size = getSize(eventDataImpl, events.isEmpty()); } catch (java.nio.BufferOverflowException exception) { throw new PayloadSizeExceededException(String.format(Locale.US, "Size of the payload exceeded Maximum message size: %s kb", this.maxMessageSize / 1024)); } if (this.currentSize + size > this.maxMessageSize) { return false; } this.events.add(eventDataImpl); this.currentSize += size; return true; }
Source:
private static void doAppendEscapedIdentifier(Appendable sbuf, String value) throws SQLException { try { sbuf.append('"'); for (char ch : value.toCharArray()) { if (ch == '\0') { throw new PSQLException(GT.tr("Zero bytes may not occur in identifiers."), PSQLState.INVALID_PARAMETER_VALUE); } if (ch == '"') { sbuf.append(ch); } sbuf.append(ch); } sbuf.append('"'); } catch (IOException e) { throw new PSQLException(GT.tr("No IOException expected from StringBuffer or StringBuilder"), PSQLState.UNEXPECTED_ERROR, e); } }

Target:
private static void doAppendEscapedIdentifier(Appendable sbuf, String value) throws SQLException { try { sbuf.append('"'); for (int i = 0; i < value.length(); ++i) { char ch = value.charAt(i); if (ch == '\0') { throw new PSQLException(GT.tr("Zero bytes may not occur in identifiers."), PSQLState.INVALID_PARAMETER_VALUE); } if (ch == '"') { sbuf.append(ch); } sbuf.append(ch); } sbuf.append('"'); } catch (IOException e) { throw new PSQLException(GT.tr("No IOException expected from StringBuffer or StringBuilder"), PSQLState.UNEXPECTED_ERROR, e); } }
Source:
public void shouldScheduleDelayedActionOnHandlerThread() { Handler handler = mock(Handler.class); @SuppressWarnings("unchecked") Action0 action = mock(Action0.class); Scheduler scheduler = HandlerScheduler.create(handler); Worker inner = scheduler.createWorker(); inner.schedule(action, 1L, TimeUnit.SECONDS); ArgumentCaptor<Runnable> runnable = ArgumentCaptor.forClass(Runnable.class); verify(handler).postDelayed(runnable.capture(), eq(1000L)); runnable.getValue().run(); verify(action).call(); }

Target:
public void shouldScheduleDelayedActionOnHandlerThread() { Handler handler = mock(Handler.class); @SuppressWarnings("unchecked") Action0 action = mock(Action0.class); Scheduler scheduler = HandlerScheduler.from(handler); Worker inner = scheduler.createWorker(); inner.schedule(action, 1, SECONDS); ArgumentCaptor<Runnable> runnable = ArgumentCaptor.forClass(Runnable.class); verify(handler).postDelayed(runnable.capture(), eq(1000L)); runnable.getValue().run(); verify(action).call(); }
Source:
public void aggregate(ByteBuffer buf, int position) { boolean countNulls = !selector.nameLookupPossibleInAdvance() || NullHandlingHelper.useDefaultValuesForNull(); MutableBitmap mutableBitmap = getMutableBitmap(position); IndexedInts row = selector.getRow(); for (int i = 0; i < row.size(); i++) { int index = row.get(i); if (countNulls || selector.lookupName(index) != null) { mutableBitmap.add(index); } } buf.putLong(position, mutableBitmap.size()); }

Target:
public void aggregate(ByteBuffer buf, int position) { MutableBitmap mutableBitmap = getMutableBitmap(position); IndexedInts row = selector.getRow(); for (int i = 0; i < row.size(); i++) { int index = row.get(i); if (NullHandling.useDefaultValuesForNull() || isNotNull(index)) { mutableBitmap.add(index); } } buf.putLong(position, mutableBitmap.size()); }
Source:
private List<ModelNode> adjustInfinispan(final PathAddress subsystem) throws Exception { final List<ModelNode> list = new ArrayList<>(); list.add(getWriteAttributeOperation(subsystem.append("cache-container", "server").append("transport", "jgroups"), "stack", new ModelNode("udp"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "server"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "server").append("replicated-cache", "default"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "web"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "web").append("distributed-cache", "dist"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "ejb"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "ejb").append("distributed-cache", "dist"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "hibernate"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "hibernate").append("invalidation-cache", "entity"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "hibernate").append("local-cache", "local-query"))); list.add(setStatisticsEnabledTrue( subsystem.append("cache-container", "hibernate").append("replicated-cache", "timestamps"))); return list; }

Target:
private List<ModelNode> adjustInfinispan(final PathAddress subsystem) throws Exception { final List<ModelNode> list = new ArrayList<>(); list.add(getWriteAttributeOperation(subsystem.append("cache-container", "server").append("transport", "jgroups"), "stack", new ModelNode("udp"))); this.adjustInfinispanStatisticsEnabled(list, subsystem); return list; }
Source:
EventBus eventBus() { EventBus bus = new EventBus((exception, context) -> exception.printStackTrace()); bus.register(new DeadEventHandler()); return bus; }

Target:
EventBus eventBus() { EventBus bus = new EventBus(); bus.register(new DeadEventHandler()); return bus; }
Source:
ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) { PackList pList; do { pList = packList.get(); SEARCH: for (;;) { for (PackFile p : pList.packs) { try { ObjectLoader ldr = p.get(curs, objectId); if (ldr != null) return ldr; } catch (PackMismatchException e) { PackList nList = scanPacks(pList); if (pList != nList) { pList = nList; continue SEARCH; } } catch (IOException e) { removePack(p); } } break SEARCH; } } while (searchPacksAgain(pList)); return null; }

Target:
ObjectLoader openPackedObject(WindowCursor curs, AnyObjectId objectId) { PackList pList; do { SEARCH: for (;;) { pList = packList.get(); for (PackFile p : pList.packs) { try { ObjectLoader ldr = p.get(curs, objectId); if (ldr != null) return ldr; } catch (PackMismatchException e) { if (searchPacksAgain(pList)) continue SEARCH; } catch (IOException e) { removePack(p); } } break SEARCH; } } while (searchPacksAgain(pList)); return null; }
Source:
public void bufferExactFailingSupplier() { Scheduler.Worker w = new TestScheduler().createWorker(); TestSubscriber<List<Integer>> observer = new TestSubscriber<List<Integer>>(); FlowableBufferTimed.BufferExactBoundedSubscriber<Integer, List<Integer>> buf = new FlowableBufferTimed.BufferExactBoundedSubscriber<Integer, List<Integer>>(observer, ArrayListSupplier.<Integer>asCallable(), 100, TimeUnit.MILLISECONDS, 10, false, w); buf.onError(new Throwable()); buf.onComplete(); }

Target:
public void bufferExactFailingSupplier() { Flowable.empty() .buffer(1, TimeUnit.SECONDS, Schedulers.computation(), 10, new Callable<List<Object>>() { @Override public List<Object> call() throws Exception { throw new TestException(); } }, false) .test() .awaitDone(1, TimeUnit.SECONDS) .assertFailure(TestException.class) ; }
Source:
private Image getImageForDraw() { if (sprite.look.getLookData() != null) { if (sprite.look.getLookData().getCollisionInformation().getLeftBubblePos() == null || sprite.look.getLookData().getCollisionInformation().getRightBubblePos() == null) { sprite.look.getLookData().getCollisionInformation().loadOrCreateCollisionPolygon(); } CollisionInformation collisionInformation = sprite.look.getLookData().getCollisionInformation(); Pair<Integer, Integer> bubblePosRight = collisionInformation.getRightBubblePos(); Pair<Integer, Integer> bubblePosLeft = collisionInformation.getLeftBubblePos(); imageLeft.setX(calculateLeftImageX(bubblePosLeft.first)); imageLeft.setY(calculateImageY(bubblePosLeft.second)); imageRight.setX(calculateRightImageX(bubblePosRight.first)); imageRight.setY(calculateImageY(bubblePosRight.second)); } else { if (drawRight) { image.setX(sprite.look.getXInUserInterfaceDimensionUnit() + (sprite.look .getWidthInUserInterfaceDimensionUnit() / 2)); } else { image.setX(sprite.look.getXInUserInterfaceDimensionUnit() - sprite.look .getWidthInUserInterfaceDimensionUnit() / 2 - image.getWidth()); } image.setY(sprite.look.getYInUserInterfaceDimensionUnit() + (sprite.look .getHeightInUserInterfaceDimensionUnit() / 2)); } return image; }

Target:
private Image getImageForDraw() { LookData lookData = sprite.look.getLookData(); if (lookData != null) { CollisionInformation collisionInformation = lookData.getCollisionInformation(); if (collisionInformation.getLeftBubblePos() == null || collisionInformation.getRightBubblePos() == null) { collisionInformation.calculateBubblePositions(); } Pair<Integer, Integer> bubblePosRight = collisionInformation.getRightBubblePos(); Pair<Integer, Integer> bubblePosLeft = collisionInformation.getLeftBubblePos(); imageLeft.setX(calculateLeftImageX(bubblePosLeft.first)); imageLeft.setY(calculateImageY(bubblePosLeft.second)); imageRight.setX(calculateRightImageX(bubblePosRight.first)); imageRight.setY(calculateImageY(bubblePosRight.second)); } else { Look look = sprite.look; if (drawRight) { image.setX(look.getXInUserInterfaceDimensionUnit() + (look.getWidthInUserInterfaceDimensionUnit() / 2)); } else { image.setX(look.getXInUserInterfaceDimensionUnit() - look.getWidthInUserInterfaceDimensionUnit() / 2 - image.getWidth()); } image.setY(look.getYInUserInterfaceDimensionUnit() + (look.getHeightInUserInterfaceDimensionUnit() / 2)); } return image; }
Source:
public static User toUser(DecodedJWT jwt) { final String subject = jwt.getSubject(); final List<Role> roles = jwt.getClaims().entrySet().stream() .filter(entry -> entry.getKey().startsWith(ROLE_PREFIX)) .map(entry -> { final String roleName = entry.getKey(); final Claim claim = entry.getValue(); final List<Permission> permissions = claim.asList(String.class).stream().map(Permission::valueOf).collect(Collectors.toList()); return new Role(roleName.substring(roleName.indexOf("_") + 1, roleName.length()), permissions); }).collect(Collectors.toList()); return new User(subject, roles); }

Target:
public static User toUser(DecodedJWT jwt) { final String subject = jwt.getSubject(); final List<Role> roles = jwt.getClaims().entrySet().stream() .filter(entry -> entry.getKey().startsWith(ROLE_PREFIX)) .map(entry -> { final String roleName = entry.getKey(); final Claim claim = entry.getValue(); final List<Permission> permissions = claim.asList(String.class).stream().map(Permission::valueOf).collect(Collectors.toList()); return new Role(roleName.replace(ROLE_PREFIX, ""), permissions); }).collect(Collectors.toList()); return new User(subject, roles); }
Source:
public void readInfo() { this.mvnInfo = null; this.mvnName = null; if (!infofile.exists()) { return; } try { final String content = FileUtils.readFileToString(infofile, Charsets.UTF_8); final int i = content.indexOf(','); LOGGER.log(Level.FINE, "The " + name + " artifact info cached is: " + content); if (i != -1) { this.mvnInfo = content.substring(0, i); this.mvnName = content.substring(i + 1); } else { LOGGER.log(Level.WARNING, "The " + name + " artifact info is invalid"); } } catch (IOException e) { LOGGER.log(Level.WARNING, "The " + name + " artifact info failed to be loaded", e); } }

Target:
public void readInfo() { this.mvnInfo = null; this.mvnName = null; if (!infofile.exists()) { return; } try { final String content = FileUtils.readFileToString(infofile, Charsets.UTF_8); final int i = content.indexOf(','); LOGGER.log(Level.FINE, "The {0} artifact info cached is: {1}", new Object[] {name, content}); if (i != -1) { this.mvnInfo = content.substring(0, i); this.mvnName = content.substring(i + 1); } else { LOGGER.log(Level.WARNING, "The {0} artifact info is invalid", name); } } catch (IOException e) { LOGGER.log(Level.WARNING, "The " + name + " artifact info failed to be loaded", e); } }
Source:
private void refreshSignedOffBy() { String curText = commitText.getText(); if (signedOff) { commitText.setText(signOff(curText)); } else { String s = getSignedOff(); if (s != null) { curText = replaceSignOff(curText, s, EMPTY_STRING); if (curText.endsWith(Text.DELIMITER + Text.DELIMITER)) curText = curText.substring(0, curText.length() - Text.DELIMITER.length()); commitText.setText(curText); } } }

Target:
private void refreshSignedOffBy() { String curText = commitText.getText(); if (signedOff) commitText.setText(signOff(curText)); else { String s = getSignedOff(); if (s != null) { curText = replaceSignOff(curText, s, EMPTY_STRING); if (curText.endsWith(Text.DELIMITER + Text.DELIMITER)) curText = curText.substring(0, curText.length() - Text.DELIMITER.length()); commitText.setText(curText); } } }
Source:
public void put(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(key); ops.set(value); }

Target:
public void put(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); BoundValueOperations<String, String> ops = this.redisTemplate.boundValueOps(key); ops.set(value); }
Source:
public ResponseEntity<?> createDilution(@RequestBody DilutionDto dilutionDto, UriComponentsBuilder b) throws IOException { if (dilutionDto == null) { log.error( "Received null dilutionDto from front end; cannot convert to Dilution. Something likely went wrong in the JS DTO conversion."); throw new RestException("Cannot convert null to Dilution", Status.BAD_REQUEST); } Long id = null; LibraryDilution dilution; try { dilution = Dtos.to(dilutionDto); dilution.setLibrary(libraryService.get(dilutionDto.getLibrary().getId())); id = populateAndSaveDilutionFromDto(dilutionDto, dilution, true); } catch (ConstraintViolationException e) { log.error("Error while creating dilution", e); RestException restException = new RestException(e.getMessage(), Status.BAD_REQUEST); restException.addData("constraintName", e.getConstraintName()); throw restException; } UriComponents uriComponents = b.path("/library/{id}").buildAndExpand(dilution.getLibrary().getId()); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uriComponents.toUri()); headers.set("Id", id.toString()); return new ResponseEntity<>(headers, HttpStatus.CREATED); }

Target:
public ResponseEntity<?> createDilution(@RequestBody DilutionDto dilutionDto, UriComponentsBuilder b) throws IOException { if (dilutionDto == null) { log.error( "Received null dilutionDto from front end; cannot convert to Dilution. Something likely went wrong in the JS DTO conversion."); throw new RestException("Cannot convert null to Dilution", Status.BAD_REQUEST); } Long id = null; LibraryDilution dilution; try { dilution = Dtos.to(dilutionDto); id = dilutionService.create(dilution); } catch (ConstraintViolationException e) { log.error("Error while creating dilution", e); RestException restException = new RestException(e.getMessage(), Status.BAD_REQUEST); restException.addData("constraintName", e.getConstraintName()); throw restException; } UriComponents uriComponents = b.path("/library/{id}").buildAndExpand(dilution.getLibrary().getId()); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uriComponents.toUri()); headers.set("Id", id.toString()); return new ResponseEntity<>(headers, HttpStatus.CREATED); }
Source:
public void start(SocketAddress endpoint) throws IOException { if (isListening()) { throw new IllegalStateException("Cannot start when already listening for messages"); } bindToAddress(endpoint); new Thread(() -> { while (!configServerSocket.isClosed()) { acceptConnection(); } }, "configurationListener").start(); }

Target:
public void start(SocketAddress endpoint) throws IOException { if (isListening()) { throw new IllegalStateException("Cannot start when already listening for messages"); } bindToAddress(endpoint); new Thread(() -> { while (!configServerSocket.isClosed()) { acceptConnection(); } }, "messagesListener").start(); }
Source:
public void testLaunchJobTwiceWhereMakeUniqueIsFalse() { logger.info("Launch batch job (makeUnique=false) twice"); executeJobCreate(MY_JOB, JOB_WITH_PARAMETERS_DESCRIPTOR + " --makeUnique=false"); checkForJobInList(MY_JOB, JOB_WITH_PARAMETERS_DESCRIPTOR + " --makeUnique=false", true); executeJobLaunch(MY_JOB); CommandResult result = executeCommandExpectingFailure("job launch --name " + MY_JOB); System.out.println("*************************" + result.getException().getMessage()); assertThat( result.getException().getMessage(), containsString("A job instance already exists and is complete for parameters={}. If you want to run this job again, change the parameters.")); }

Target:
public void testLaunchJobTwiceWhereMakeUniqueIsFalse() { logger.info("Launch batch job (makeUnique=false) twice"); executeJobCreate(MY_JOB, JOB_WITH_PARAMETERS_DESCRIPTOR + " --makeUnique=false"); checkForJobInList(MY_JOB, JOB_WITH_PARAMETERS_DESCRIPTOR + " --makeUnique=false", true); executeJobLaunch(MY_JOB); CommandResult result = executeCommandExpectingFailure("job launch --name " + MY_JOB); assertThat( result.getException().getMessage(), containsString("A job instance already exists and is complete for parameters={}. If you want to run this job again, change the parameters.")); }
Source:
public List<GenericVertex> resolve(GraphService graphService, SearchCriteria searchCriteria) { GenericGraph graph = graphService.getGraph(searchCriteria.getNamespace()); return graph.getVertices() .stream() .map(ApplicationVertex::new) .filter(v -> filter(v, searchCriteria.getCriteria())) .map(ApplicationVertex::asGenericVertex) .collect(Collectors.toList()); }

Target:
public List<GenericVertex> resolve(GraphService graphService, SearchCriteria searchCriteria) { return getVerticesOfGraph(graphService, searchCriteria.getNamespace()) .stream() .map(ApplicationVertex::new) .filter(v -> filter(v, searchCriteria.getCriteria())) .map(ApplicationVertex::asGenericVertex) .collect(Collectors.toList()); }
Source:
protected Location manageRecursive(Location loc, final ManagementTransitionMode initialMode) { AccessController.Response access = managementContext.getAccessController().canManageLocation(loc); if (!access.isAllowed()) { throw new IllegalStateException("Access controller forbids management of "+loc+": "+access.getMsg()); } if (log.isDebugEnabled()) { String msg = "Managing location " + loc + " ("+initialMode+"), from " + Tasks.current()+" / "+Entitlements.getEntitlementContext(); long count = LOCATION_CNT.incrementAndGet(); if (count % 100 == 0) { log.debug(msg, new Exception("Informational stack trace of call to manage location "+loc+" ("+count+" calls; "+getLocations().size()+" currently managed)")); } else { log.debug(msg); } } recursively(loc, new Predicate<AbstractLocation>() { public boolean apply(AbstractLocation it) { ManagementTransitionMode mode = getLastManagementTransitionMode(it.getId()); if (mode==null) { setManagementTransitionMode(it, mode = initialMode); } if (it.isManaged()) { if (mode==ManagementTransitionMode.CREATING) { return false; } else { } } boolean result = manageNonRecursive(it, null); if (result) { it.setManagementContext(managementContext); if (!mode.isReadOnly()) { it.onManagementStarted(); recordLocationEvent(it, Lifecycle.CREATED); } managementContext.getRebindManager().getChangeListener().onManaged(it); } return result; } }); return loc; }

Target:
protected Location manageRecursive(Location loc, final ManagementTransitionMode initialMode) { AccessController.Response access = managementContext.getAccessController().canManageLocation(loc); if (!access.isAllowed()) { throw new IllegalStateException("Access controller forbids management of "+loc+": "+access.getMsg()); } long count = LOCATION_CNT.incrementAndGet(); if (log.isDebugEnabled()) { String msg = "Managing location " + loc + " ("+initialMode+"), from " + Tasks.current()+" / "+Entitlements.getEntitlementContext(); if (count % 100 == 0) { log.debug(msg, new Exception("Informational stack trace of call to manage location "+loc+" ("+count+" calls; "+getLocations().size()+" currently managed)")); } else { log.debug(msg); } } recursively(loc, new Predicate<AbstractLocation>() { public boolean apply(AbstractLocation it) { ManagementTransitionMode mode = getLastManagementTransitionMode(it.getId()); if (mode==null) { setManagementTransitionMode(it, mode = initialMode); } if (it.isManaged()) { if (mode==ManagementTransitionMode.CREATING) { return false; } else { } } boolean result = manageNonRecursive(it, null); if (result) { it.setManagementContext(managementContext); if (!mode.isReadOnly()) { it.onManagementStarted(); recordLocationEvent(it, Lifecycle.CREATED); } managementContext.getRebindManager().getChangeListener().onManaged(it); } return result; } }); return loc; }
Source:
void start(int slot) { mSlot = slot; int error = isValid(); if (error == SUCCESS) { Log.d(TAG, "Starting keepalive " + mSlot + " on " + mNai.name()); switch (mType) { case TYPE_NATT: mNai.asyncChannel .sendMessage(CMD_START_SOCKET_KEEPALIVE, slot, mInterval, mPacket); break; case TYPE_TCP: mTcpController.startSocketMonitor(mFd, this, mSlot); mNai.asyncChannel .sendMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER, slot, 0 , mPacket); mNai.asyncChannel .sendMessage(CMD_START_SOCKET_KEEPALIVE, slot, mInterval, mPacket); break; default: Log.wtf(TAG, "Starting keepalive with unknown type: " + mType); } mStartedState = STARTING; } else { handleStopKeepalive(mNai, mSlot, error); return; } }

Target:
void start(int slot) { mSlot = slot; int error = isValid(); if (error == SUCCESS) { Log.d(TAG, "Starting keepalive " + mSlot + " on " + mNai.name()); switch (mType) { case TYPE_NATT: mNai.asyncChannel .sendMessage(CMD_START_SOCKET_KEEPALIVE, slot, mInterval, mPacket); break; case TYPE_TCP: mTcpController.startSocketMonitor(mFd, this, mSlot); mNai.asyncChannel .sendMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER, slot, 0 , mPacket); mNai.asyncChannel .sendMessage(CMD_START_SOCKET_KEEPALIVE, slot, mInterval, mPacket); break; default: Log.wtf(TAG, "Starting keepalive with unknown type: " + mType); handleStopKeepalive(mNai, mSlot, error); return; } mStartedState = STARTING; } else { handleStopKeepalive(mNai, mSlot, error); return; } }
Source:
public NewTmfViewAction(TmfView view) { super(MessageFormat.format(Messages.TmfView_NewTmfViewNameText, view.getTitle().toLowerCase()), IAction.AS_PUSH_BUTTON); setToolTipText(MessageFormat.format(Messages.TmfView_NewTmfViewToolTipText, view.getTitle())); }

Target:
public NewTmfViewAction(TmfView view) { super(MessageFormat.format(Messages.TmfView_NewTmfViewNameText, view.getTitle()), IAction.AS_PUSH_BUTTON); setToolTipText(MessageFormat.format(Messages.TmfView_NewTmfViewToolTipText, view.getTitle())); fViewId = checkNotNull(view.getViewId()); }
Source:
public ChangeInfo apply(RevisionResource rsrc, Input input) throws BadRequestException, ResourceConflictException, EmailException, OrmException, ResourceNotFoundException, IOException { if (Strings.isNullOrEmpty(input.message)) { throw new BadRequestException("message must be non-empty"); } final Repository git; try { git = gitManager.openRepository(rsrc.getChange().getProject()); } catch (RepositoryNotFoundException e) { throw new ResourceNotFoundException(); } try { return json.format(ChangeUtil.editCommitMessage( rsrc.getPatchSet().getId(), rsrc.getControl().getRefControl(), (IdentifiedUser) rsrc.getControl().getCurrentUser(), input.message, dbProvider.get(), commitMessageEditedSenderFactory, git, myIdent, patchSetInserterFactory)); } catch (InvalidChangeOperationException e) { throw new BadRequestException(e.getMessage()); } catch (MissingObjectException e) { throw new ResourceConflictException(e.getMessage()); } catch (IncorrectObjectTypeException e) { throw new ResourceConflictException(e.getMessage()); } catch (PatchSetInfoNotAvailableException e) { throw new ResourceConflictException(e.getMessage()); } catch (NoSuchChangeException e) { throw new ResourceNotFoundException(); } finally { git.close(); } }

Target:
public ChangeInfo apply(RevisionResource rsrc, Input input) throws BadRequestException, ResourceConflictException, EmailException, OrmException, ResourceNotFoundException, IOException { if (Strings.isNullOrEmpty(input.message)) { throw new BadRequestException("message must be non-empty"); } final Repository git; try { git = gitManager.openRepository(rsrc.getChange().getProject()); } catch (RepositoryNotFoundException e) { throw new ResourceNotFoundException(e.getMessage()); } try { return json.format(ChangeUtil.editCommitMessage( rsrc.getPatchSet().getId(), rsrc.getControl().getRefControl(), (IdentifiedUser) rsrc.getControl().getCurrentUser(), input.message, dbProvider.get(), commitMessageEditedSenderFactory, git, myIdent, patchSetInserterFactory)); } catch (InvalidChangeOperationException e) { throw new BadRequestException(e.getMessage()); } catch (MissingObjectException e) { throw new ResourceConflictException(e.getMessage()); } catch (IncorrectObjectTypeException e) { throw new ResourceConflictException(e.getMessage()); } catch (PatchSetInfoNotAvailableException e) { throw new ResourceConflictException(e.getMessage()); } catch (NoSuchChangeException e) { throw new ResourceNotFoundException(); } finally { git.close(); } }