auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void importFromFileSystem(List<Process> processes) { if (isActionParameterInvalid("sourcefolder")) { return; } URI sourceFolder = new File(this.parameters.get("sourcefolder")).toURI(); try { if (!fileService.isDirectory(sourceFolder)) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Directory " + this.parameters.get("sourcefolder") + " does not exisist"); return; } for (Process process : processes) { Integer processId = process.getId(); String processTitle = process.getTitle(); URI imagesFolder = serviceManager.getProcessService().getImagesOrigDirectory(false, process); if (fileService.getSubUris(imagesFolder).size() > 0) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "", "The process " + processTitle + " [" + processId + "] has already data in image folder"); } else { URI sourceFolderProcess = fileService.createResource(sourceFolder, processTitle); if (!fileService.isDirectory(sourceFolder)) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "", "The directory for process " + processTitle + " [" + processId + "] is not existing"); } else { fileService.copyDirectory(sourceFolderProcess, imagesFolder); Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "The directory for process " + processTitle + " [" + processId + "] is copied"); } Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "The process " + processTitle + " [" + processId + "] is copied"); } } } catch (IOException e) { Helper.setFehlerMeldung(e); logger.error(e.getMessage(), e); } }

Target:
private void importFromFileSystem(List<Process> processes) { if (isActionParameterInvalid("sourcefolder")) { return; } URI sourceFolder = new File(this.parameters.get("sourcefolder")).toURI(); try { if (!fileService.isDirectory(sourceFolder)) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Directory " + this.parameters.get("sourcefolder") + " does not exisist"); return; } for (Process process : processes) { Integer processId = process.getId(); String processTitle = process.getTitle(); URI imagesFolder = serviceManager.getProcessService().getImagesOrigDirectory(false, process); if (fileService.getSubUris(imagesFolder).size() > 0) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "", "The process " + processTitle + " [" + processId + "] has already data in image folder"); } else { URI sourceFolderProcess = fileService.createResource(sourceFolder, processTitle); if (!fileService.isDirectory(sourceFolder)) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "", "The directory for process " + processTitle + " [" + processId + "] is not existing"); } else { fileService.copyDirectory(sourceFolderProcess, imagesFolder); Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "The directory for process " + processTitle + " [" + processId + "] is copied"); } Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "The process " + processTitle + " [" + processId + "] is copied"); } } } catch (IOException e) { Helper.setErrorMessage(e.toString(), logger, e); } }
Source:
public Class<?> getPicklistClass(){ String version = getApiVersion(); String pattern = "20\\d{2}.\\d+"; if(version != null && Pattern.matches(pattern, version)){ Class<?> valueClass; try { valueClass = Class.forName("com.netsuite.webservices.v"+version.replace('.', '_')+".platform.core.ListOrRecordRef"); } catch (ClassNotFoundException e) { return null; } return valueClass; } return null; }

Target:
public Class<?> getPicklistClass(){ String version = getApiVersion(); String pattern = "20\\d{2}\\.\\d+"; if(version != null && Pattern.matches(pattern, version)){ Class<?> valueClass; try { valueClass = Class.forName("com.netsuite.webservices.v"+version.replace('.', '_')+".platform.core.ListOrRecordRef"); } catch (ClassNotFoundException e) { return null; } return valueClass; } return null; }
Source:
private RpslObject getAbuseContactRoleInternal(final RpslObject object) { RpslObject abuseContact; try { abuseContact = getAbuseC(object); if (abuseContact == null) { if (object.containsAttribute(AttributeType.ORG)) { final RpslObject organisation = objectDao.getByKey(ObjectType.ORGANISATION, object.getValueForAttribute(AttributeType.ORG)); abuseContact = getAbuseC(organisation); } } } catch (EmptyResultDataAccessException ignored) { LOGGER.debug("Ignored invalid reference (object {})", object.getKey()); abuseContact = null; } return abuseContact; }

Target:
private RpslObject getAbuseContactRoleInternal(final RpslObject object) { try { RpslObject abuseContact = getAbuseC(object); if (abuseContact != null) { return abuseContact; } return getOrgAbuseC(object); } catch (EmptyResultDataAccessException ignored) { LOGGER.debug("Ignored invalid reference (object {})", object.getKey()); } return null; }
Source:
static void submitTasksAndWaitForResults(ExecutorService executor, Callable[] tasks) throws Exception { final List<Future> results = Lists.newArrayListWithCapacity(tasks.length); for (Callable task : tasks) { results.add(executor.submit(task)); } for (Future result : results) { result.get(); } executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); }

Target:
static void submitTasksAndWaitForResults(ExecutorService executor, Callable[] tasks) throws Exception { final List<Future> results = Lists.newArrayListWithCapacity(tasks.length); for (Callable task : tasks) { results.add(executor.submit(task)); } for (Future result : results) { result.get(); } }
Source:
protected void updateWorkingDirFromConfig(ILaunchConfiguration config) { if (workingDirText != null) { String workingDir = EMPTY_STRING; try { workingDir = config.getAttribute(ATTR_REMOTE_WORKING_DIRECTORY_NAME, EMPTY_STRING); } catch (CoreException ce) { ProfileLaunchPlugin.log(ce); } if (workingDir.equals(EMPTY_STRING)){ if(this.fProjText != null){ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(this.fProjText.getText()); if(project != null){ IRemoteFileProxy remoteFileProxy = null; try { remoteFileProxy = RemoteProxyManager.getInstance().getFileProxy(project); } catch (CoreException e) { e.printStackTrace(); } URI workingDirURI = remoteFileProxy.getWorkingDir(); workingDir = workingDirURI.toString(); } } } workingDirText.setText(workingDir); } }

Target:
protected void updateWorkingDirFromConfig(ILaunchConfiguration config) { if (workingDirText != null) { String projectDir = EMPTY_STRING; try { projectDir = config.getAttribute(ATTR_REMOTE_WORKING_DIRECTORY_NAME, EMPTY_STRING); } catch (CoreException ce) { ProfileLaunchPlugin.log(ce); } if (projectDir.equals(EMPTY_STRING)){ if(this.fProjText != null){ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(this.fProjText.getText()); try { projectDir = RemoteProxyManager.getInstance().getRemoteProjectLocation(project); } catch (CoreException e) { setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory); } } } workingDirText.setText(projectDir); } }
Source:
private static Symbol isSwitchAssigningVariable(SwitchStatementTree switchStatementTree) { Symbol switchAssigningVariable = null; for (CaseGroupTree caseGroupTree : switchStatementTree.cases()) { if (hasSingleStatement(caseGroupTree.body(), THROW_STATEMENT)) { continue; } Symbol variable = assigningVariable(caseGroupTree.body()); if (variable == null) { return null; } if (switchAssigningVariable == null) { switchAssigningVariable = variable; } else if (switchAssigningVariable != variable) { return null; } } return switchAssigningVariable; }

Target:
private static Symbol isSwitchAssigningVariable(SwitchStatementTree switchStatementTree) { Set<Symbol> assignedVariables = switchStatementTree.cases().stream() .filter(caseGroup -> !hasSingleStatement(caseGroup.body(), THROW_STATEMENT)) .map(UseSwitchExpressionCheck::assigningVariable) .collect(Collectors.toSet()); return assignedVariables.size() == 1 ? assignedVariables.iterator().next() : null; }
Source:
private static void enableJunit5ForTestTask(Test task) { if (!useJUnitPlatformEnabled(task)) { task.useJUnitPlatform(); } task.systemProperty("junit.platform.output.capture.stdout", "true"); task.systemProperty("junit.platform.output.capture.stderr", "true"); task.systemProperty("junit.jupiter.execution.parallel.enabled", "true"); task.systemProperty("junit.jupiter.execution.parallel.config.strategy", "dynamic"); task.getTestLogging().getEvents().add(TestLogEvent.FAILED); if ("true".equals(System.getenv("CI"))) { task.getTestLogging() .getEvents() .addAll(ImmutableSet.of(TestLogEvent.STARTED, TestLogEvent.PASSED, TestLogEvent.SKIPPED)); } }

Target:
private static void enableJunit5ForTestTask(Test task) { if (!useJUnitPlatformEnabled(task)) { task.useJUnitPlatform(); } task.systemProperty("junit.platform.output.capture.stdout", "true"); task.systemProperty("junit.platform.output.capture.stderr", "true"); task.systemProperty("junit.jupiter.execution.parallel.enabled", "true"); task.systemProperty("junit.jupiter.execution.parallel.config.strategy", "dynamic"); task.getTestLogging().getEvents().add(TestLogEvent.FAILED); if (!task.getName().equals("test") && "true".equals(System.getenv("CI"))) { task.getTestLogging() .getEvents() .addAll(ImmutableSet.of(TestLogEvent.STARTED, TestLogEvent.PASSED, TestLogEvent.SKIPPED)); } }
Source:
public void calculate_changelog() throws IOException, InterruptedException, SftpException, JSchException { final URL changesUrl; final String TEST_COMMIT_MESSAGE = "Second commit"; Build b; GitRepo repo = buildGitRepo(); repo.branch("testBranch"); repo.commit(TEST_COMMIT_MESSAGE); repo.transferToDockerContainer(host, port); job.useScm(GitScm.class) .url(repoUrl) .credentials(USERNAME) .calculateChangelog("origin", "testBranch"); job.save(); b = job.startBuild(); b.shouldSucceed(); changesUrl = b.url("changes"); assertThat( b.getConsole(), Matchers.containsRegexp("Using 'Changelog to branch' strategy.", Pattern.MULTILINE) ); assertThat( visit(changesUrl).getPageSource(), Matchers.containsRegexp(TEST_COMMIT_MESSAGE, Pattern.MULTILINE) ); }

Target:
public void calculate_changelog() { final URL changesUrl; final String TEST_COMMIT_MESSAGE = "Second commit"; Build b; GitRepo repo = buildGitRepo(); repo.createBranch("testBranch"); repo.changeAndCommitFoo(TEST_COMMIT_MESSAGE); repo.transferToDockerContainer(host, port); job.useScm(GitScm.class) .url(repoUrl) .credentials(USERNAME) .calculateChangelog("origin", "testBranch"); job.save(); b = job.startBuild(); b.shouldSucceed(); changesUrl = b.url("changes"); assertThat( b.getConsole(), Matchers.containsRegexp("Using 'Changelog to branch' strategy.", Pattern.MULTILINE) ); assertThat( visit(changesUrl).getPageSource(), Matchers.containsRegexp(TEST_COMMIT_MESSAGE, Pattern.MULTILINE) ); }
Source:
public CinderlibReturnValue runCommand(CinderlibCommand command, CinderlibCommandParameters params) throws Exception { File dir = Paths.get(config.getUsrDir().getAbsolutePath() + CINDERLIB_DIR).toFile(); ProcessBuilder cinderlibProcessBuilder = new ProcessBuilder() .directory(dir) .command(generateCommand(command, params)) .redirectErrorStream(true); Process process = cinderlibProcessBuilder.start(); String output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8); log.info("cinderlib output: {}", output); if (!process.waitFor(2, TimeUnit.MINUTES)) { throw new Exception("cinderlib call timed out"); } CinderlibReturnValue returnValue = new CinderlibReturnValue(process.exitValue(), output); return returnValue; }

Target:
public CinderlibReturnValue runCommand(CinderlibCommand command, CinderlibCommandParameters params) throws Exception { ProcessBuilder cinderlibProcessBuilder = new ProcessBuilder() .directory(cinderlibDir) .command(generateCommand(command, params)) .redirectErrorStream(true); Process process = cinderlibProcessBuilder.start(); String output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8); log.info("cinderlib output: {}", output); if (!process.waitFor(2, TimeUnit.MINUTES)) { throw new Exception("cinderlib call timed out"); } CinderlibReturnValue returnValue = new CinderlibReturnValue(process.exitValue(), output); return returnValue; }
Source:
public void triggerElection() throws IOException { if ( !refuseToBecomeLeader ) { handle( new RaftMessages.Timeout.Election( myself ) ); } else { log.info( format( "Election timeout occured triggered, but {%s} is configured to not tirgger an election. " + "See setting: %s", myself, CausalClusteringSettings.refuse_to_be_leader.name() ) ); } }

Target:
public void triggerElection() throws IOException { if ( !refuseToBecomeLeader ) { handle( new RaftMessages.Timeout.Election( myself ) ); } else { log.info( format( "Election timeout occured, but {%s} is configured to not tirgger an election. " + "See setting: %s", myself, CausalClusteringSettings.refuse_to_be_leader.name() ) ); } }
Source:
public IId<?> fromExternalFormLenient(String externalForm) { if (externalForm == null) { return null; } String[] tmp = externalForm.split(":", 2); if (tmp.length != 2) { return null; } String typeName = tmp[0]; Class<? extends IId<?>> idClass = m_nameToClassMap.get(typeName); if (idClass == null) { return null; } return BEANS.get(IdFactory.class).createFromString(idClass, tmp[1]); }

Target:
public IId<?> fromExternalFormLenient(String externalForm) { if (externalForm == null) { return null; } String[] tmp = externalForm.split(":", 2); if (tmp.length != 2) { return null; } String typeName = tmp[0]; Class<? extends IId<?>> idClass = m_nameToClassMap.get(typeName); if (idClass == null) { return null; } return m_idFactory.get().createFromString(idClass, tmp[1]); }
Source:
public ApplicationListener<?> xdInitializer(ApplicationContext context) { XdConfigLoggingInitializer delegate = new XdConfigLoggingInitializer(true); delegate.setEnvironment(context.getEnvironment()); if (zooKeeperConnection != null) { delegate.setZkConnectString(zooKeeperConnection.getClient().getZookeeperClient().getCurrentConnectionString()); } return new SourceFilteringListener(context, delegate); }

Target:
public ApplicationListener<?> xdInitializer(ApplicationContext context) { XdConfigLoggingInitializer delegate = new XdConfigLoggingInitializer(true); delegate.setEnvironment(context.getEnvironment()); return new SourceFilteringListener(context, delegate); }
Source:
public E map(ResultSet rs, int columnNumber, StatementContext ctx) throws SQLException { String name = ctx.findColumnMapperFor(String.class) .orElseThrow(() -> new UnableToProduceResultException("a String column mapper is required to map Enums from names", ctx)) .map(rs, columnNumber, ctx); return name == null ? null : nameValueCache.computeIfAbsent(name.toLowerCase(), lowercased -> getValueByName(enumClass, name, ctx)); }

Target:
public E map(ResultSet rs, int columnNumber, StatementContext ctx) throws SQLException { String name = rs.getString(columnNumber); return name == null || name.isEmpty() ? null : nameValueCache.computeIfAbsent(name, n -> getValueByName(enumClass, name, ctx)); }
Source:
public void testPasswordResetWithNoExistingUser_shouldThrow() { String username= "anyUser"; when(userRepository.findUser(anyString())).thenReturn(null); passwordResetService.resetUserPassword(username); Assert.assertNotNull(userRepository.findUser(username)); verify(userRepository).findUser(username); verify(passwordResetService).resetUserPassword(username); }

Target:
public void testPasswordResetWithNoExistingUser_shouldThrow() { String username = "anyUser"; when(userRepository.findUser(anyString())).thenReturn(null); passwordResetService.resetUserPassword(username); }
Source:
private HBMessage encodeNettySerializable(ByteBufAllocator alloc, INettySerializable netty_message, HBServerMessageType mType) { HBMessageData message_data = new HBMessageData(); HBMessage m = new HBMessage(); ByteBuf messageBuffer = alloc.heapBuffer(netty_message.encodeLength()); try { netty_message.write(messageBuffer); message_data.set_message_blob(messageBuffer.array()); m.set_type(mType); m.set_data(message_data); return m; } finally { messageBuffer.release(); } }

Target:
private HBMessage encodeNettySerializable(ByteBufAllocator alloc, INettySerializable netty_message, HBServerMessageType mType) { HBMessageData message_data = new HBMessageData(); HBMessage m = new HBMessage(); byte[] messageBuffer = new byte[netty_message.encodeLength()]; ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(messageBuffer); try { netty_message.write(wrappedBuffer); message_data.set_message_blob(messageBuffer); m.set_type(mType); m.set_data(message_data); return m; } finally { wrappedBuffer.release(); } }
Source:
public static String normalizeBranchName(String name) { if (name == null || name.length() == 0) { return name; } String result = name.trim(); String fullName = result.startsWith(Constants.R_HEADS) ? result : Constants.R_HEADS + result; if (isValidRefName(fullName)) { return result; } return result.replaceAll("\\s+([_:-])*?\\s+", "$1") .replaceAll(":", "-") .replaceAll("\\s+", "_") .replaceAll("_{2,}", "_") .replaceAll("-{2,}", "-") .replaceAll("[^\\w-/]", "") .replaceAll("^_+", "") .replaceAll("^-+", ""); }

Target:
public static String normalizeBranchName(String name) { if (name == null || name.isEmpty()) { return name; } String result = name.trim(); String fullName = result.startsWith(Constants.R_HEADS) ? result : Constants.R_HEADS + result; if (isValidRefName(fullName)) { return result; } result = result.replaceAll("(?:\\h|\\v)+", "_"); StringBuilder b = new StringBuilder(); char p = '/'; for (int i = 0, len = result.length(); i < len; i++) { char c = result.charAt(i); if (c < ' ' || c == 127) { continue; } switch (c) { case '\\': case '^': case '~': case ':': case '?': case '*': case '[': case '@': case '<': case '>': case '|': case '"': c = '-'; break; default: break; } switch (c) { case '/': if (p == '/') { continue; } p = '/'; break; case '.': case '_': case '-': if (p == '/' || p == '-') { continue; } p = '-'; break; default: p = c; break; } b.append(c); } result = b.toString().replaceFirst("[/_.-]+$", "") .replaceAll("\\.lock($|/)", "_lock$1"); return FORBIDDEN_BRANCH_NAME_COMPONENTS.matcher(result) .replaceAll("$1+$2$3"); }
Source:
public Response backupStart(@QueryParam("name") String name) { if (name == null || name.isEmpty()) { return JaxRsUtils.buildStreamingResponse(factory, new StreamingJsonResponse() { @Override public void write(final JsonGenerator json) throws IOException { json.writeBooleanField("started", false); json.writeStringField("error", "name required"); } }); } return ClusterJobUtils.startJob(cluster, factory, CassandraFrameworkProtos.ClusterJobType.BACKUP, name); }

Target:
public Response backupStart(@QueryParam("name") String name) { if (name == null) { name = "backup-" + System.currentTimeMillis(); } return ClusterJobUtils.startJob(cluster, factory, CassandraFrameworkProtos.ClusterJobType.BACKUP, name); }
Source:
public Void get() { nrtManager.waitForGeneration(gen); return null; }

Target:
public Void get() throws InterruptedException, ExecutionException { if (!isDone()) { nrtManager.waitForGeneration(gen); set(null); } return super.get(); }
Source:
protected MessageHandler createHandler() { MessageHandler handler; if (this.targetObject == null) { Assert.isTrue(!StringUtils.hasText(this.targetMethodName), "The target method is only allowed when a target object (ref or inner bean) is also provided."); } if (this.targetObject != null) { Assert.state(this.expression == null, "The 'targetObject' and 'expression' properties are mutually exclusive."); AbstractMessageProducingHandler actualHandler = this.extractTypeIfPossible(targetObject, AbstractMessageProducingHandler.class); boolean targetIsDirectReplyProducingHandler = actualHandler != null && this.canBeUsedDirect(actualHandler) && this.methodIsHandleMessageOrEmpty(this.targetMethodName); if (this.targetObject instanceof MessageProcessor<?>) { handler = this.createMessageProcessingHandler((MessageProcessor<?>) this.targetObject); } else if (targetIsDirectReplyProducingHandler) { if (logger.isDebugEnabled()) { logger.debug("Wiring handler (" + beanName + ") directly into endpoint"); } this.checkReuse(actualHandler); this.postProcessReplyProducer(actualHandler); handler = (MessageHandler) targetObject; } else { handler = this.createMethodInvokingHandler(this.targetObject, this.targetMethodName); } } else if (this.expression != null) { handler = this.createExpressionEvaluatingHandler(this.expression); } else { handler = this.createDefaultHandler(); } return handler; }

Target:
protected MessageHandler createHandler() { MessageHandler handler; if (this.targetObject == null) { Assert.isTrue(!StringUtils.hasText(this.targetMethodName), "The target method is only allowed when a target object (ref or inner bean) is also provided."); } if (this.targetObject != null) { Assert.state(this.expression == null, "The 'targetObject' and 'expression' properties are mutually exclusive."); AbstractMessageProducingHandler actualHandler = this.extractTypeIfPossible(targetObject, AbstractMessageProducingHandler.class); boolean targetIsDirectReplyProducingHandler = actualHandler != null && this.canBeUsedDirect(actualHandler) && this.methodIsHandleMessageOrEmpty(this.targetMethodName); if (this.targetObject instanceof MessageProcessor<?>) { handler = this.createMessageProcessingHandler((MessageProcessor<?>) this.targetObject); } else if (targetIsDirectReplyProducingHandler) { if (logger.isDebugEnabled()) { logger.debug("Wiring handler (" + this.targetObject + ") directly into endpoint"); } this.checkReuse(actualHandler); this.postProcessReplyProducer(actualHandler); handler = (MessageHandler) targetObject; } else { handler = this.createMethodInvokingHandler(this.targetObject, this.targetMethodName); } } else if (this.expression != null) { handler = this.createExpressionEvaluatingHandler(this.expression); } else { handler = this.createDefaultHandler(); } return handler; }
Source:
public Token appendCheckpoint() { long start = System.currentTimeMillis(); Token markerToken = rt.getSequencerView().next().getToken(); rt.getAddressSpaceView().write(markerToken, "marker".getBytes()); rt.getObjectsView().TXBuild() .type(TransactionType.SNAPSHOT) .snapshot(markerToken) .build() .begin(); try (Timer.Context context = MetricsUtils.getConditionalContext(appendCheckpointTimer)) { Token snapshot = TransactionalContext.getCurrentContext().getSnapshotTimestamp(); log.info("appendCheckpoint: Started checkpoint for at snapshot {}", streamId, snapshot); ICorfuSMR<T> corfuObject = (ICorfuSMR<T>) this.map; Set<Map.Entry> entries = this.map.entrySet(); long vloVersion = corfuObject.getCorfuSMRProxy().getVersion(); startCheckpoint(snapshot, vloVersion); appendObjectState(entries); finishCheckpoint(); log.info("appendCheckpoint: completed checkpoint for at snapshot in ms", streamId, snapshot, System.currentTimeMillis() - start); return snapshot; } finally { rt.getObjectsView().TXEnd(); } }

Target:
public Token appendCheckpoint() { long start = System.currentTimeMillis(); Token markerToken = rt.getSequencerView().query().getToken(); if (Address.nonAddress(markerToken.getSequence())) { return markerToken; } rt.getAddressSpaceView().read(markerToken.getSequence()); rt.getObjectsView().TXBuild() .type(TransactionType.SNAPSHOT) .snapshot(markerToken) .build() .begin(); try (Timer.Context context = MetricsUtils.getConditionalContext(appendCheckpointTimer)) { Token snapshot = TransactionalContext.getCurrentContext().getSnapshotTimestamp(); log.info("appendCheckpoint: Started checkpoint for at snapshot {}", streamId, snapshot); ICorfuSMR<T> corfuObject = (ICorfuSMR<T>) this.map; Set<Map.Entry> entries = this.map.entrySet(); long vloVersion = corfuObject.getCorfuSMRProxy().getVersion(); startCheckpoint(snapshot, vloVersion); appendObjectState(entries); finishCheckpoint(); log.info("appendCheckpoint: completed checkpoint for {}, num of entries at snapshot in ms", streamId, entries.size(), snapshot, System.currentTimeMillis() - start); return snapshot; } finally { rt.getObjectsView().TXEnd(); } }
Source:
void validate() { if (!containsMacro("path")) { Preconditions.checkArgument(!Strings.isNullOrEmpty(path), "Path cannot be empty."); } if (!containsMacro("nodePath")) { Preconditions.checkArgument(!Strings.isNullOrEmpty(nodePath), "Node path cannot be empty."); } if (!containsMacro("temporaryFolder")) { Preconditions.checkArgument(!Strings.isNullOrEmpty(temporaryFolder), "Temporary folder cannot be empty."); } boolean onlyOneActionRequired = !actionAfterProcess.equalsIgnoreCase("NONE") && isReprocessingRequired(); Preconditions.checkArgument(!onlyOneActionRequired, "Please select either 'After Processing Action' or " + "'Reprocessing Required'; both cannot be applied at the same time."); boolean targetFolderEmpty = (actionAfterProcess.equalsIgnoreCase("ARCHIVE") || actionAfterProcess.equalsIgnoreCase("MOVE")) && Strings.isNullOrEmpty(targetFolder); Preconditions.checkArgument(!targetFolderEmpty, "Target folder cannot be empty for Action = '" + actionAfterProcess + "'."); }

Target:
void validate() { if (!containsMacro("path")) { Preconditions.checkArgument(!Strings.isNullOrEmpty(path), "Path cannot be empty."); } if (!containsMacro("nodePath")) { Preconditions.checkArgument(!Strings.isNullOrEmpty(nodePath), "Node path cannot be empty."); } if (!containsMacro("tableExpiryPeriod") && tableExpiryPeriod != null && tableExpiryPeriod < 0) { throw new IllegalArgumentException("Value for Table expiry period should either be empty or greater than 0."); } if (!containsMacro("temporaryFolder")) { Preconditions.checkArgument(!Strings.isNullOrEmpty(temporaryFolder), "Temporary folder cannot be empty."); } boolean onlyOneActionRequired = !actionAfterProcess.equalsIgnoreCase("NONE") && isReprocessingRequired(); Preconditions.checkArgument(!onlyOneActionRequired, "Please select either 'After Processing Action' or " + "'Reprocessing Required'; both cannot be applied at the same time."); boolean targetFolderEmpty = (actionAfterProcess.equalsIgnoreCase("ARCHIVE") || actionAfterProcess.equalsIgnoreCase("MOVE")) && Strings.isNullOrEmpty(targetFolder); Preconditions.checkArgument(!targetFolderEmpty, "Target folder cannot be empty for Action = '" + actionAfterProcess + "'."); }
Source:
public Optional<String> getItemData(ItemStack item) { if (item.getItemMeta() == null) { return Optional.empty(); } return getItemData(item.getItemMeta()); }

Target:
public Optional<String> getItemData(ItemStack item) { if (item == null || !item.hasItemMeta()) { return Optional.empty(); } return getItemData(item.getItemMeta()); }
Source:
protected boolean shouldWrapLines() { return !(FileUtils.isMarkdown(mPath) && !mViewRawText) && super.shouldWrapLines(); }

Target:
protected boolean shouldWrapLines() { boolean displayingMarkdown = FileUtils.isMarkdown(mPath) && !mViewRawText; return !displayingMarkdown && super.shouldWrapLines(); }
Source:
void handleResponse(ResponseInfo responseInfo) { GetRequest getRequest = (GetRequest) responseInfo.getRequest(); GetOperation getOperation = correlationIdToGetOperation.remove(getRequest.getCorrelationId()); if (getOperations.contains(getOperation)) { getOperation.handleResponse(responseInfo); if (getOperation.isOperationComplete()) { getOperations.remove(getOperation); routerMetrics.operationDequeuingRate.mark(); } } }

Target:
void handleResponse(ResponseInfo responseInfo) { GetRequest getRequest = (GetRequest) responseInfo.getRequest(); GetOperation getOperation = correlationIdToGetOperation.remove(getRequest.getCorrelationId()); if (getOperations.contains(getOperation)) { getOperation.handleResponse(responseInfo); if (getOperation.isOperationComplete()) { remove(getOperation); } } }
Source:
public Iterator<E> iterator(){ return new ArrayList<E>(backingList).iterator(); }

Target:
public Iterator<E> iterator(){ return list.iterator(); }
Source:
protected void initBaseTestConfig( CoreServerFixture fixture ) throws IOException { writeConfigFile( "conf.d/storage.conf", "[storage-default]\nstorage.dir=" + fixture.getBootOptions().getHomeDir() + "/var/lib/indy/storage" ); if ( isSchedulerEnabled() ) { writeConfigFile( "conf.d/scheduler.conf", readTestResource( "default-test-scheduler.conf" ) ); writeConfigFile( "conf.d/threadpools.conf", "[threadpools]\nenabled=false" ); writeConfigFile( "conf.d/ssl_validation.conf", "[ssl_validation]\n_internal.store.validation.enabled=false" ); } else { writeConfigFile( "conf.d/scheduler.conf", "[scheduler]\nenabled=false" ); } }

Target:
protected void initBaseTestConfig( CoreServerFixture fixture ) throws IOException { writeConfigFile( "conf.d/storage.conf", "[storage-default]\nstorage.dir=" + fixture.getBootOptions().getHomeDir() + "/var/lib/indy/storage" ); if ( isSchedulerEnabled() ) { writeConfigFile( "conf.d/scheduler.conf", readTestResource( "default-test-scheduler.conf" ) ); writeConfigFile( "conf.d/threadpools.conf", "[threadpools]\nenabled=false" ); writeConfigFile( "conf.d/internal_validation.conf", "[internal]\n_internal.store.validation.enabled=false" ); } else { writeConfigFile( "conf.d/scheduler.conf", "[scheduler]\nenabled=false" ); } }
Source:
public void ensureValid(String name, Object value) { String strValue = (String) value; if (strValue.isEmpty()) { return; } String[] configs = StringUtil.csvSplit(strValue); Arrays.stream(configs).forEach(config -> validateHttpResponseHeaderConfig(config)); }

Target:
public void ensureValid(String name, Object value) { String strValue = (String) value; if (strValue == null || strValue.trim().isEmpty()) { return; } String[] configs = StringUtil.csvSplit(strValue); Arrays.stream(configs).forEach(WorkerConfig::validateHttpResponseHeaderConfig); }
Source:
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServletResponse) servletResponse; if (isRequestUrlExcluded(request)) { logger.debug("Request is ignored."); filterChain.doFilter(request, response); return; } if (!preFilter(servletRequest, servletResponse, filterChain)) { return; } final String ticket = retrieveTicketFromRequest(request); if (CommonUtils.isNotBlank(ticket)) { logger.debug("Attempting to validate ticket: {}", ticket); try { final Assertion assertion = this.ticketValidator.validate(ticket, constructServiceUrl(request, response)); logger.debug("Successfully authenticated user: {}", assertion.getPrincipal().getName()); request.setAttribute(CONST_CAS_ASSERTION, assertion); if (this.useSession) { request.getSession().setAttribute(CONST_CAS_ASSERTION, assertion); } onSuccessfulValidation(request, response, assertion); if (this.redirectAfterValidation) { logger.debug("Redirecting after successful ticket validation."); response.sendRedirect(constructServiceUrl(request, response)); return; } } catch (final TicketValidationException e) { logger.debug(e.getMessage(), e); onFailedValidation(request, response); if (this.exceptionOnValidationFailure) { throw new ServletException(e); } response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } } filterChain.doFilter(request, response); }

Target:
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { if (!preFilter(servletRequest, servletResponse, filterChain)) { return; } final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServletResponse) servletResponse; final String ticket = retrieveTicketFromRequest(request); if (CommonUtils.isNotBlank(ticket)) { logger.debug("Attempting to validate ticket: {}", ticket); try { final Assertion assertion = this.ticketValidator.validate(ticket, constructServiceUrl(request, response)); logger.debug("Successfully authenticated user: {}", assertion.getPrincipal().getName()); request.setAttribute(CONST_CAS_ASSERTION, assertion); if (this.useSession) { request.getSession().setAttribute(CONST_CAS_ASSERTION, assertion); } onSuccessfulValidation(request, response, assertion); if (this.redirectAfterValidation) { logger.debug("Redirecting after successful ticket validation."); response.sendRedirect(constructServiceUrl(request, response)); return; } } catch (final TicketValidationException e) { logger.debug(e.getMessage(), e); onFailedValidation(request, response); if (this.exceptionOnValidationFailure) { throw new ServletException(e); } response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } } filterChain.doFilter(request, response); }
Source:
public SqlInputSource( @JsonProperty("sqls") List<String> sqls, @JsonProperty("foldCase") boolean foldCase, @JsonProperty("database") SQLFirehoseDatabaseConnector sqlFirehoseDatabaseConnector, @JacksonInject @Smile ObjectMapper objectMapper ) { Preconditions.checkArgument(sqls.size() > 0, "No SQL queries provided"); this.sqls = sqls; this.foldCase = foldCase; this.sqlFirehoseDatabaseConnector = sqlFirehoseDatabaseConnector; this.objectMapper = objectMapper; }

Target:
public SqlInputSource( @JsonProperty("sqls") List<String> sqls, @JsonProperty("foldCase") boolean foldCase, @JsonProperty("database") SQLFirehoseDatabaseConnector sqlFirehoseDatabaseConnector, @JacksonInject @Smile ObjectMapper objectMapper ) { Preconditions.checkArgument(sqls.size() > 0, "No SQL queries provided"); this.sqls = sqls; this.foldCase = foldCase; this.sqlFirehoseDatabaseConnector = Preconditions.checkNotNull( sqlFirehoseDatabaseConnector, "SQL Metadata Connector not configured!" ); this.objectMapper = objectMapper; }
Source:
public void process(EquivalenceAssertionMessage message) throws RecoverableException { LOG.debug( "Processing message on id {}, asserted adjacents: {}, message: {}", message.getSubject().getId(), message.getAssertedAdjacents().stream() .map(ResourceRef::getId) .collect(ImmutableCollectors.toList()), message ); try { if (messageTimer != null) { Timer.Context timer = messageTimer.time(); graphStore.updateEquivalences(message.getSubject(), message.getAssertedAdjacents(), message.getPublishers()); equivMigrator.migrateEquivalence(message.getSubject()); timer.stop(); } else { graphStore.updateEquivalences(message.getSubject(), message.getAssertedAdjacents(), message.getPublishers()); equivMigrator.migrateEquivalence(message.getSubject()); } LOG.debug("Successfully processed message {}", message.toString()); } catch (WriteException e) { LOG.warn( "Failed to process message on id {}, asserted adjacents: {}, message: {}. " + "Retrying...", message.getSubject().getId(), message.getAssertedAdjacents().stream() .map(ResourceRef::getId) .collect(ImmutableCollectors.toList()), message ); throw new RecoverableException("update failed for " + message.toString(), e); } catch (Exception e) { LOG.warn( "Failed to process message on id {}, asserted adjacents: {}, message: {}", message.getSubject().getId(), message.getAssertedAdjacents().stream() .map(ResourceRef::getId) .collect(ImmutableCollectors.toList()), message ); if (meter != null) { meter.mark(); } } }

Target:
public void process(EquivalenceAssertionMessage message) throws RecoverableException { if (LOG.isDebugEnabled()) { LOG.debug( "Processing message on id {}, asserted adjacents: {}, message: {}", message.getSubject().getId(), message.getAssertedAdjacents().stream() .map(ResourceRef::getId) .collect(ImmutableCollectors.toList()), message ); } try { if (messageTimer != null) { Timer.Context timer = messageTimer.time(); graphStore.updateEquivalences(message.getSubject(), message.getAssertedAdjacents(), message.getPublishers()); equivMigrator.migrateEquivalence(message.getSubject()); timer.stop(); } else { graphStore.updateEquivalences(message.getSubject(), message.getAssertedAdjacents(), message.getPublishers()); equivMigrator.migrateEquivalence(message.getSubject()); } LOG.debug("Successfully processed message {}", message.toString()); } catch (WriteException e) { LOG.warn( "Failed to process message on id {}, asserted adjacents: {}, message: {}. " + "Retrying...", message.getSubject().getId(), message.getAssertedAdjacents().stream() .map(ResourceRef::getId) .collect(ImmutableCollectors.toList()), message ); throw new RecoverableException("update failed for " + message.toString(), e); } catch (Exception e) { LOG.warn( "Failed to process message on id {}, asserted adjacents: {}, message: {}", message.getSubject().getId(), message.getAssertedAdjacents().stream() .map(ResourceRef::getId) .collect(ImmutableCollectors.toList()), message ); if (meter != null) { meter.mark(); } } }
Source:
public List<BuildTimeOutStrategyDescriptor> getStrategies() { return Jenkins.getInstance().getDescriptorList(BuildTimeOutStrategy.class); }

Target:
public List<BuildTimeOutStrategyDescriptor> getStrategies() { List<BuildTimeOutStrategyDescriptor> descriptors = Jenkins.getInstance().getDescriptorList(BuildTimeOutStrategy.class); List<BuildTimeOutStrategyDescriptor> supportedStrategies = new ArrayList<BuildTimeOutStrategyDescriptor>(descriptors.size()); for(BuildTimeOutStrategyDescriptor descriptor : descriptors) { if (descriptor.isApplicableAsBuildStep()) { supportedStrategies.add(descriptor); } } return supportedStrategies; }
Source:
public Host getCurrentHost() throws DotDataException, DotSecurityException { final HttpServletRequest request = HttpServletRequestThreadLocal.INSTANCE.getRequest(); return this.getCurrentHost(request); }

Target:
public Host getCurrentHost() throws DotDataException, DotSecurityException { final HttpServletRequest request = HttpServletRequestThreadLocal.INSTANCE.getRequest(); if (request == null) { return APILocator.getHostAPI().findDefaultHost(APILocator.systemUser(), true); } return this.getCurrentHost(request); }
Source:
protected Cluster postPopulate(Cluster model) { ErrorHandling errorHandling = new ErrorHandling(); errorHandling.setOnError(MappingTestHelper.shuffle(MigrateOnError.class).value()); model.setErrorHandling(errorHandling); SchedulingPolicy policy = new SchedulingPolicy(); policy.setPolicy(NONE); FencingPolicy fencingPolicy = new FencingPolicy(); SkipIfSDActive skipIfSDActive = new SkipIfSDActive(); SkipIfConnectivityBroken skipIfConnectivityBroken = new SkipIfConnectivityBroken(); skipIfSDActive.setEnabled(false); skipIfConnectivityBroken.setEnabled(false); skipIfConnectivityBroken.setThreshold(50); fencingPolicy.setEnabled(true); fencingPolicy.setSkipIfSdActive(skipIfSDActive); fencingPolicy.setSkipIfConnectivityBroken(skipIfConnectivityBroken); model.setSchedulingPolicy(policy); model.getSerialNumber().setPolicy(SerialNumberPolicy.CUSTOM.value()); model.getRequiredRngSources().getRngSources().clear(); model.getRequiredRngSources().getRngSources().add(RngSource.RANDOM.name()); model.getSchedulingPolicy().setPolicy(NONE); model.getSchedulingPolicy().setName(NONE); model.setFencingPolicy(fencingPolicy); return model; }

Target:
protected Cluster postPopulate(Cluster model) { ErrorHandling errorHandling = new ErrorHandling(); errorHandling.setOnError(MappingTestHelper.shuffle(MigrateOnError.class).value()); model.setErrorHandling(errorHandling); SchedulingPolicy policy = new SchedulingPolicy(); policy.setPolicy(NONE); model.setSchedulingPolicy(policy); model.getSerialNumber().setPolicy(SerialNumberPolicy.CUSTOM.value()); model.getRequiredRngSources().getRngSources().clear(); model.getRequiredRngSources().getRngSources().add(RngSource.RANDOM.name()); model.getSchedulingPolicy().setPolicy(NONE); model.getSchedulingPolicy().setName(NONE); return model; }
Source:
public void nextPreviewStyle() { for (Tab tab : this.entryEditorTabs) { if (tab instanceof FieldsEditorTab) { ((FieldsEditorTab) tab).previewPanel.nextPreviewStyle(); } } }

Target:
public void nextPreviewStyle() { this.entryEditorTabs.forEach(EntryEditorTab::nextPreviewStyle); }
Source:
public Set<Type> getImportTypes() { Set<Type> imported = new HashSet<Type>( super.getImportTypes() ); if ( isDirectAssignment() ) { if ( targetType.getImplementationType() != null ) { imported.addAll( targetType.getImplementationType().getImportTypes() ); } else { imported.addAll( targetType.getImportTypes() ); } if ( isEnumSet() ) { imported.add( typeFactory.getType( EnumSet.class ) ); } } if (isDirectAssignment() || getSourcePresenceCheckerReference() == null ) { imported.addAll( getNullCheckLocalVarType().getImportTypes() ); } if ( isMapNullToDefault() ) { imported.add( targetType.getImplementationType() ); } return imported; }

Target:
public Set<Type> getImportTypes() { Set<Type> imported = new HashSet<Type>( super.getImportTypes() ); if ( isDirectAssignment() ) { if ( targetType.getImplementationType() != null ) { imported.addAll( targetType.getImplementationType().getImportTypes() ); } else { imported.addAll( targetType.getImportTypes() ); } if ( isEnumSet() ) { imported.add( typeFactory.getType( EnumSet.class ) ); } } if (isDirectAssignment() || getSourcePresenceCheckerReference() == null ) { imported.addAll( getNullCheckLocalVarType().getImportTypes() ); } if ( isMapNullToDefault() && ( targetType.getImplementationType() != null ) ) { imported.add( targetType.getImplementationType() ); } return imported; }
Source:
public ArrayList<Sprite> getSprites(double steps) { SpriteStore store = SpriteStore.getInstance(); String id = "fruit"; ArrayList<Sprite> result = new ArrayList<Sprite>(); result.add(store.getAnimated(id).getFrame(posX())); return result; }

Target:
public ArrayList<Sprite> getSprites(double steps) { SpriteStore store = SpriteStore.getInstance(); ArrayList<Sprite> result = new ArrayList<Sprite>(); result.add(store.getAnimated("fruit").getFrame(posX())); return result; }
Source:
public void patchPasswordMissingValue() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .build(); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/password", null); ops.add(replaceOperation); String patchBody = getPatchContent(ops); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isBadRequest()); }

Target:
public void patchPasswordMissingValue() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withPassword("testpass79bC") .build(); String token = getAuthToken(admin.getEmail(), password); String newPassword = "newpass"; List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/password", newPassword); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()); List<Operation> ops2 = new ArrayList<Operation>(); ReplaceOperation replaceOperation2 = new ReplaceOperation("/password", null); ops2.add(replaceOperation2); patchBody = getPatchContent(ops2); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isBadRequest()); token = getAuthToken(ePerson.getEmail(), newPassword); getClient(token).perform(get("/api/")) .andExpect(status().isOk()); }
Source:
public int getSourceAnchorVerticalPosition() { IdentityAnchor srcAnchor = null; Anchor sourceAnchor = edge.getSourceAnchor(); if (sourceAnchor instanceof IdentityAnchor) { srcAnchor = (IdentityAnchor) sourceAnchor; } else if (sourceAnchor.eIsProxy()) { SequenceDiagramPlugin.INSTANCE.log(MessageFormat.format(Messages.ProxyAnchor_Source, ((DEdge) edge.getElement()).getName())); } View source = edge.getSource(); Range sourceRange = new Range(0, 0); if (source instanceof Node) { sourceRange = new SequenceNodeQuery((Node) source).getVerticalRange(); } return getAnchorAbsolutePosition(srcAnchor, sourceRange); }

Target:
public int getSourceAnchorVerticalPosition() { IdentityAnchor srcAnchor = null; Anchor sourceAnchor = edge.getSourceAnchor(); if (sourceAnchor instanceof IdentityAnchor) { srcAnchor = (IdentityAnchor) sourceAnchor; } View source = edge.getSource(); Range sourceRange = new Range(0, 0); if (source instanceof Node) { sourceRange = new SequenceNodeQuery((Node) source).getVerticalRange(); } return getAnchorAbsolutePosition(srcAnchor, sourceRange); }
Source:
PendingIntent createContentIntent(Context context, Account account, boolean incoming) { Intent editServerSettingsIntent = incoming ? IncomingView.intentActionEditIncomingSettings(context, account) : OutgoingView.intentActionEditOutgoingSettings(context, account); return PendingIntent.getActivity(context, account.getAccountNumber(), editServerSettingsIntent, PendingIntent.FLAG_UPDATE_CURRENT); }

Target:
PendingIntent createContentIntent(Context context, Account account, boolean incoming) { Intent editServerSettingsIntent = incoming ? AccountSetupActivity.intentActionEditIncomingSettings(context, account) : AccountSetupActivity.intentActionEditOutgoingSettings(context, account); return PendingIntent.getActivity(context, account.getAccountNumber(), editServerSettingsIntent, PendingIntent.FLAG_UPDATE_CURRENT); }
Source:
public void testLockingLocks() throws Exception { Lock lock = new ReentrantLock(); int threads = 10; CyclicBarrier barrier = new CyclicBarrier(threads); AtomicInteger underLock = new AtomicInteger(0); AtomicInteger maxUnderLock = new AtomicInteger(0); List<Future<?>> futures = IntStream.range(0, threads) .mapToObj(i -> executor.submit(() -> { barrier.await(); locking(lock, () -> { maxUnderLock.accumulateAndGet(underLock.incrementAndGet(), Integer::max); Thread.sleep(30); underLock.decrementAndGet(); }); return null; })) .collect(toImmutableList()); futures.forEach(MoreFutures::getFutureValue); }

Target:
public void testLockingLocks() throws Exception { Lock lock = new ReentrantLock(); int threads = 10; CyclicBarrier barrier = new CyclicBarrier(threads); AtomicInteger underLock = new AtomicInteger(0); AtomicInteger maxUnderLock = new AtomicInteger(0); List<Future<?>> futures = IntStream.range(0, threads) .mapToObj(i -> executor.submit(() -> { barrier.await(); locking(lock, () -> { maxUnderLock.accumulateAndGet(underLock.incrementAndGet(), Integer::max); Thread.sleep(30); underLock.decrementAndGet(); }); return null; })) .collect(toImmutableList()); futures.forEach(MoreFutures::getFutureValue); assertEquals(maxUnderLock.get(), 1, "More than one thread acquired the lock at the same time"); }