auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void resetUserPassword(String username) { User user = userRepository.findUser(username); if (user == null) { throw new NoResultException(); } PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String newPassword = RandomStringUtils.randomAlphanumeric(16); user.setPassword(passwordEncoder.encode(newPassword)); user.setPasswordReset(true); userRepository.updateUser(user, true); try { MimeMailMessage message= bsisEmailSender.createMailMessage(user.getEmailId(), passwordResetSubject, String.format(passwordResetMessage, newPassword)); bsisEmailSender.sendEmail(message); } catch (MessagingException e) { throw new MailParseException(e); } }

Target:
public void resetUserPassword(String username) throws Exception { User user = userRepository.findUser(username); if (user == null) { throw new NoResultException(); } String newPassword = generateRandomPassword(); updateUserWithNewPassword(user, newPassword); sendNewPasswordEmailToUser(user, newPassword); }
Source:
public void toggleAutoStart() { autoStartStrategy.ifPresent(autoStart -> { boolean enableAutoStart = autoStartCheckbox.isSelected(); Task<Void> toggleTask = new ToggleAutoStartTask(autoStart, enableAutoStart); toggleTask.setOnFailed(event -> { autoStartCheckbox.setSelected(!enableAutoStart); LOG.error("Failed to toggle autostart.", event.getSource().getException()); errorComponent.cause(event.getSource().getException()).window(window).returnToScene(preferencesScene.get()).build().showErrorScene(); }); executor.execute(toggleTask); }); }

Target:
public void toggleAutoStart() { autoStartStrategy.ifPresent(autoStart -> { boolean enableAutoStart = autoStartCheckbox.isSelected(); Task<Void> toggleTask = new ToggleAutoStartTask(autoStart, enableAutoStart); toggleTask.setOnFailed(event -> { autoStartCheckbox.setSelected(!enableAutoStart); LOG.error("Failed to toggle autostart.", event.getSource().getException()); }); executor.execute(toggleTask); }); }
Source:
public Repository getSnapshotTo(byte[] root) { RepositoryRoot repo = new RepositoryRoot(stateDS, root); repo.config = this.config; return repo; }

Target:
public Repository getSnapshotTo(byte[] root) { return new RepositoryRoot(stateDS, root, config); }
Source:
public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { if (logging) { System.out.println("promptKeyboardInteractive:" + destination + ":" + name + ":" + instruction); for (String p : prompt) { System.out.println(" " + p); } } if (firstTry && !fAttributes.getAttribute(prompt[0], EMPTY_STRING, echo[0]).equals(EMPTY_STRING)) { firstTry = false; String[] result = new String[prompt.length]; for (int i=0; i<prompt.length; i++) { result[i] = fAttributes.getAttribute(prompt[i], EMPTY_STRING, echo[i]); } return result; } else if (fAuthenticator != null) { String[] result = fAuthenticator.prompt(destination, name, instruction, prompt, echo); if (result != null) { for (int i=0; i<prompt.length; i++) { fAttributes.setAttribute(prompt[i], result[i], echo[i]); } } return result; } return null; }

Target:
public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { if (logging) { System.out.println("promptKeyboardInteractive:" + destination + ":" + name + ":" + instruction); for (String p : prompt) { System.out.println(" " + p); } } if (prompt.length==0) { return new String[0]; } else if (firstTry) { firstTry = false; if (prompt.length==1 && prompt[0].trim().equalsIgnoreCase("password:")) { if (!getPassword().equals(EMPTY_STRING)) { return new String[]{getPassword()}; } } else if (!fAttributes.getAttribute(prompt[0], EMPTY_STRING, echo[0]).equals(EMPTY_STRING)) { String[] result = new String[prompt.length]; for (int i=0; i<prompt.length; i++) { result[i] = fAttributes.getAttribute(prompt[i], EMPTY_STRING, echo[i]); } return result; } } if (fAuthenticator != null) { String[] result = fAuthenticator.prompt(destination, name, instruction, prompt, echo); if (result != null) { if (prompt.length==1 && prompt[0].trim().equalsIgnoreCase("password:")) { fAttributes.setSecureAttribute(JSchConnectionAttributes.PASSWORD_ATTR, result[0]); } else { for (int i=0; i<prompt.length; i++) { fAttributes.setAttribute(prompt[i], result[i], echo[i]); } } } return result; } return null; }
Source:
public void delete(int cfIndex, byte[] keyBytes) throws RocksDBException { try { String tableName = tablesNames.get(cfIndex); Class keyType = getKeyType(tableName); Object key = codecRegistry.asObject(keyBytes, keyType); OMDBUpdateEvent.OMUpdateEventBuilder builder = new OMDBUpdateEvent.OMUpdateEventBuilder<>(); builder.setTable(tableName); builder.setKey(key); builder.setAction(OMDBUpdateEvent.OMDBUpdateAction.DELETE); OMDBUpdateEvent deleteEvent = builder.build(); LOG.info("Generated OM delete Event for table : " + deleteEvent.getTable() + ", Key = " + deleteEvent.getKey()); omdbUpdateEvents.add(deleteEvent); } catch (IOException ioEx) { LOG.error("Exception when reading key : " + ioEx); } }

Target:
public void delete(int cfIndex, byte[] keyBytes) throws RocksDBException { try { processEvent(cfIndex, keyBytes, null, OMDBUpdateEvent.OMDBUpdateAction.DELETE); } catch (IOException ioEx) { LOG.error("Exception when reading key : " + ioEx); } }
Source:
public List<Field> getFields() { try { if (notStrictFieldLayoutRowSyntaxValidator == null) { notStrictFieldLayoutRowSyntaxValidator = new NotStrictFieldLayoutRowSyntaxValidator(this.contentType, this.fields); notStrictFieldLayoutRowSyntaxValidator.validate(); } return notStrictFieldLayoutRowSyntaxValidator.getFields(); } catch (FieldLayoutValidationException e) { throw new DotRuntimeException(e); } }

Target:
public List<Field> getFields() { try { if (notStrictFieldLayoutRowSyntaxValidator == null) { notStrictFieldLayoutRowSyntaxValidator = new NotStrictFieldLayoutRowSyntaxValidator(this.contentType, this.fields); notStrictFieldLayoutRowSyntaxValidator.validate(); } return notStrictFieldLayoutRowSyntaxValidator.getFields(); } catch (FieldLayoutValidationException e) { Logger.error(FieldLayout.class, e.getMessage()); throw new DotRuntimeException(e); } }
Source:
protected void prepareHeaderWidgets(PatchScript script, PatchSetDetail detail) { initPatchSetListForTableHeader(); psListOfHeaderA.display(detail, script, patchKey, idSideA, idSideB); psListOfHeaderB.display(detail, script, patchKey, idSideA, idSideB); iconA = new Anchor(); iconA.setTitle(PatchUtil.C.addFileComment()); DOM.insertBefore(iconA.getElement(), new Image(Gerrit.RESOURCES.addFileComment()).getElement(), DOM.getFirstChild(iconA.getElement())); iconA.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { createFileCommentEditorOnSideA(); } }); iconB = new Anchor(); iconB.setTitle(PatchUtil.C.addFileComment()); DOM.insertBefore(iconB.getElement(), new Image(Gerrit.RESOURCES.addFileComment()).getElement(), DOM.getFirstChild(iconB.getElement())); iconB.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { createFileCommentEditorOnSideB(); } }); }

Target:
protected void prepareHeaderWidgets(PatchScript script, PatchSetDetail detail) { initPatchSetListForTableHeader(); psListOfHeaderA.display(detail, script, patchKey, idSideA, idSideB); psListOfHeaderB.display(detail, script, patchKey, idSideA, idSideB); iconA = new Image(Gerrit.RESOURCES.addFileComment()); iconA.setTitle(PatchUtil.C.addFileComment()); iconA.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { createFileCommentEditorOnSideA(); } }); iconB = new Image(Gerrit.RESOURCES.addFileComment()); iconB.setTitle(PatchUtil.C.addFileComment()); iconB.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { createFileCommentEditorOnSideB(); } }); }
Source:
public Schedule createSchedule(ReferenceData refData) { LocalDate unadjStart = calculatedUnadjustedStartDate(refData); LocalDate unadjEnd = calculatedUnadjustedEndDate(refData); LocalDate regularStart = calculatedFirstRegularStartDate(unadjStart, refData); LocalDate regularEnd = calculatedLastRegularEndDate(unadjEnd, refData); RollConvention rollConv = calculatedRollConvention(regularStart, regularEnd); List<LocalDate> unadj = generateUnadjustedDates(unadjStart, regularStart, regularEnd, unadjEnd, rollConv); List<LocalDate> adj = applyBusinessDayAdjustment(unadj, refData); List<SchedulePeriod> periods = new ArrayList<>(); try { if (combinePeriodsIfNecessary) { adj = new ArrayList<>(adj); unadj = new ArrayList<>(unadj); for (int i = 0; i < adj.size() - 1; i++) { if (adj.get(i).equals(adj.get(i + 1))) { adj.remove(i); unadj.remove(i); } } } for (int i = 0; i < unadj.size() - 1; i++) { periods.add(SchedulePeriod.of(adj.get(i), adj.get(i + 1), unadj.get(i), unadj.get(i + 1))); } } catch (IllegalArgumentException ex) { createUnadjustedDates(); createAdjustedDates(refData); ScheduleException se = new ScheduleException(this, "Schedule calculation resulted in invalid period"); se.initCause(ex); throw se; } return Schedule.builder() .periods(periods) .frequency(frequency) .rollConvention(rollConv) .build(); }

Target:
public Schedule createSchedule(ReferenceData refData) { return createSchedule(refData, false); }
Source:
public void visit( TypeCastExpressionNode n ) { n.expression().accept( this ); if ( n.type() == NativeType.INT ) { currExpression = new CastIntExpression( currExpression ); } else if ( n.type() == NativeType.DOUBLE ) { currExpression = new CastDoubleExpression( currExpression ); } else if ( n.type() == NativeType.STRING ) { currExpression = new CastStringExpression( currExpression ); } else if ( n.type() == NativeType.BOOL ) { currExpression = new CastBoolExpression( currExpression ); } else if ( n.type() == NativeType.LONG ) { currExpression = new CastLongExpression( currExpression ); } }

Target:
public void visit( TypeCastExpressionNode n ) { n.expression().accept( this ); switch( n.type() ) { case INT: currExpression = new CastIntExpression( currExpression ); break; case DOUBLE: currExpression = new CastDoubleExpression( currExpression ); break; case STRING: currExpression = new CastStringExpression( currExpression ); break; case BOOL: currExpression = new CastBoolExpression( currExpression ); break; case LONG: currExpression = new CastLongExpression( currExpression ); break; } }
Source:
public void start() { if (!running) { ChannelBindingServiceProperties channelBindingServiceProperties = null; try { ChannelBindingService channelBindingService = this.applicationContext .getBean(ChannelBindingService.class); channelBindingServiceProperties = channelBindingService.getChannelBindingServiceProperties(); Map<String, Bindable> bindables = this.applicationContext.getBeansOfType(Bindable.class); for (Bindable bindable : bindables.values()) { bindable.bindInputs(channelBindingService); } } catch (BeansException e) { throw new IllegalStateException( "Cannot perform binding, no proper implementation found", e); } if (channelBindingServiceProperties != null && channelBindingServiceProperties.isAutoStartup()) { this.running = true; } } }

Target:
public void start() { if (!running) { try { ChannelBindingService channelBindingService = this.applicationContext .getBean(ChannelBindingService.class); Map<String, Bindable> bindables = this.applicationContext.getBeansOfType(Bindable.class); for (Bindable bindable : bindables.values()) { bindable.bindInputs(channelBindingService); } } catch (BeansException e) { throw new IllegalStateException( "Cannot perform binding, no proper implementation found", e); } this.running = true; } }
Source:
public void pageFindByCandidateEntityShouldNotFindApplicationForCandidateWithoutApplications() { CandidateEntity candidateB = this.candidateRepository.findOne(CANDIDATE_B_ID); Page<ApplicationEntity> pageResult = this.repository.findByCandidateEntity(candidateB, DEFAULT_PAGE_REQUEST); List<ApplicationEntity> result = pageResult.getContent(); assertThat(result, notNullValue()); assertThat(result, empty()); }

Target:
public void pageFindByCandidateEntityShouldNotFindApplicationForCandidateWithoutApplications() { CandidateEntity candidateB = this.candidateRepository.findOne(CANDIDATE_B_ID); final Page<ApplicationEntity> pageResult = this.repository.findByCandidateEntity(candidateB, DEFAULT_PAGE_REQUEST); final List<ApplicationEntity> result = pageResult.getContent(); assertThat(result, notNullValue()); assertThat(result, empty()); }
Source:
private synchronized Status updateAndGetStatus() { if (this.status == Status.OPEN && Instant.now().isAfter(this.closeCircuitInstant)) { LOGGER.info("Timeout expired for OPEN circuit"); this.halfOpenCircuit(); } return this.status == Status.HALF_OPEN ? Status.CLOSED : this.status; }

Target:
private Status updateAndGetStatus() { this.lock.lock(); try { if (this.status == Status.OPEN && Instant.now().isAfter(this.closeCircuitInstant)) { LOGGER.info("Timeout expired for OPEN circuit"); this.halfOpenCircuit(); } return this.status; } finally { this.lock.unlock(); } }
Source:
public RestxSpecTestsRunner(Class<?> testClass) throws InitializationError, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException, IOException { super(testClass); FindSpecsIn findSpecsIn = getTestClass().getJavaClass().getAnnotation(FindSpecsIn.class); if (findSpecsIn != null) { Factory factory = Factory.newInstance(); WebServerSupplier supplier = factory.queryByClass(WebServerSupplier.class).findOne().get().getComponent(); RestxSpecRule rule = new RestxSpecRule(findSpecsIn.withRouterPath(), supplier, factory); tests = new RestxSpecTests(rule, RestxSpecTests.findSpecsIn(findSpecsIn.value())); } else { Object o = getTestClass().getOnlyConstructor().newInstance(); if (!(o instanceof RestxSpecTests)) { throw new IllegalArgumentException( format("Test class %s must either be annotated with FindSpecsIn" + " or extend RestxSpecTests " + "to be run with RestxSpecTestsRunner.", getTestClass().getJavaClass().getName())); } tests = (RestxSpecTests) o; } }

Target:
public RestxSpecTestsRunner(Class<?> testClass) throws InitializationError, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException, IOException { super(testClass); FindSpecsIn findSpecsIn = getTestClass().getJavaClass().getAnnotation(FindSpecsIn.class); if (findSpecsIn != null) { tests = new RestxSpecTests(new RestxSpecRule(findSpecsIn.withRouterPath()), RestxSpecTests.findSpecsIn(findSpecsIn.value())); } else { Object o = getTestClass().getOnlyConstructor().newInstance(); if (!(o instanceof RestxSpecTests)) { throw new IllegalArgumentException( format("Test class %s must either be annotated with FindSpecsIn" + " or extend RestxSpecTests " + "to be run with RestxSpecTestsRunner.", getTestClass().getJavaClass().getName())); } tests = (RestxSpecTests) o; } }
Source:
public static CertificateService getCertificateService() { if (certiticateService == null) { ServiceReference<?> guiVerifyReference = IrcActivator.getBundleContext().getServiceReference( CertificateService.class.getName()); if (guiVerifyReference != null) { certiticateService = (CertificateService) IrcActivator.getBundleContext().getService( guiVerifyReference); } } return certiticateService; }

Target:
public static CertificateService getCertificateService() { if (certificateService == null) { certificateService = ServiceUtils.getService(bundleContext, CertificateService.class); } return certificateService; }
Source:
protected Repository getRepository(boolean warn) { RepositoryMapping mapping = null; for (IResource resource : getSelectedResources()) { RepositoryMapping repositoryMapping = RepositoryMapping.getMapping(resource.getProject()); if (mapping == null) mapping = repositoryMapping; if (repositoryMapping == null) return null; if (mapping.getRepository() != repositoryMapping.getRepository()) { if (warn) MessageDialog.openError(getShell(), "Multiple Repositories Selection", "Cannot perform reset on multiple repositories simultaneously.\n\nPlease select items from only one repository."); return null; } } if (mapping == null) { if (warn) MessageDialog.openError(getShell(), "Cannot Find Repository", "Could not find a repository associated with this project"); return null; } final Repository repository = mapping.getRepository(); return repository; }

Target:
protected Repository getRepository(boolean warn) { RepositoryMapping mapping = null; for (IProject project : getSelectedProjects()) { RepositoryMapping repositoryMapping = RepositoryMapping.getMapping(project); if (mapping == null) mapping = repositoryMapping; if (repositoryMapping == null) return null; if (mapping.getRepository() != repositoryMapping.getRepository()) { if (warn) MessageDialog.openError(getShell(), "Multiple Repositories Selection", "Cannot perform reset on multiple repositories simultaneously.\n\nPlease select items from only one repository."); return null; } } if (mapping == null) { if (warn) MessageDialog.openError(getShell(), "Cannot Find Repository", "Could not find a repository associated with this project"); return null; } final Repository repository = mapping.getRepository(); return repository; }
Source:
public synchronized void removeFromDirQueue(String dir) { Object[] tempArray = dirQueue.toArray(); DirToCheck dirToCheck = null; for (int b = 0; b < tempArray.length; b++) { dirToCheck = (DirToCheck) tempArray[b]; String processWork = dirToCheck.getName(); if (processWork.equals(dir)) { if (dirQueue.remove(dirToCheck)) { totalDirsFound--; } else { LOG.error("Removed " + processWork + " from dir queue"); } } } }

Target:
public synchronized void removeFromDirQueue(String dir) { Object[] tempArray = dirQueue.toArray(); DirToCheck dirToCheck = null; for (int b = 0; b < tempArray.length; b++) { dirToCheck = (DirToCheck) tempArray[b]; String processWork = dirToCheck.getName(); if (processWork.equals(dir)) { if (dirQueue.remove(dirToCheck)) { totalDirsFound--; } else { LOG.warn("Failed to remove " + processWork + " from dir queue"); } } } }
Source:
public void testPairedIntervalFilter(final String intervalFilename, final int expectNumber) throws Exception { final File inputSam = File.createTempFile("testSam", ".sam", TEST_DIR); inputSam.deleteOnExit(); final File sortedSamIdx = new File(TEST_DIR, inputSam.getName() + ".bai"); sortedSamIdx.deleteOnExit(); final SAMFileWriter writer = new SAMFileWriterFactory() .setCreateIndex(true).makeBAMWriter(builder.getHeader(), false, inputSam); for (final SAMRecord record : builder) { writer.addAlignment(record); } writer.close(); final File intervalFile = new File(intervalFilename); FilterSamReads filterTest = setupProgram(intervalFile, inputSam, FilterSamReads.Filter.includePairedIntervals); Assert.assertEquals(filterTest.doWork(),0); long count = getReadCount(filterTest); Assert.assertEquals(count, expectNumber); }

Target:
public void testPairedIntervalFilter(final String intervalFilename, final int expectNumber) throws Exception { final File inputSam = File.createTempFile("testSam", ".sam", TEST_DIR); inputSam.deleteOnExit(); final File sortedSamIdx = new File(TEST_DIR, inputSam.getName() + ".idx"); sortedSamIdx.deleteOnExit(); final SAMFileWriter writer = new SAMFileWriterFactory() .setCreateIndex(true).makeSAMWriter(builder.getHeader(), false, inputSam); for (final SAMRecord record : builder) { writer.addAlignment(record); } writer.close(); final File intervalFile = new File(intervalFilename); FilterSamReads filterTest = setupProgram(intervalFile, inputSam, FilterSamReads.Filter.includePairedIntervals); Assert.assertEquals(filterTest.doWork(),0); long count = getReadCount(filterTest); Assert.assertEquals(count, expectNumber); }
Source:
public String getSwiftContainerName(){ String swiftContainerName; try { DataFileIO dataFileIO = getFile().getDataFileIO(); try { SwiftAccessIO swiftIO = (SwiftAccessIO)dataFileIO; swiftIO.open(); swiftContainerName = swiftIO.getSwiftContainerName(); logger.info("Swift container name: " + swiftContainerName); return swiftContainerName; } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } return ""; }

Target:
public String getSwiftContainerName(){ SwiftAccessIO swiftObject = getSwiftObject(); try { swiftObject.open(); return swiftObject.getSwiftContainerName(); } catch (IOException e){ logger.info("FilePage: Failed to open swift object"); } return ""; }
Source:
public static Cube syncCubeLoad(ICubicWorld world, CubeIO loader, ServerCubeCache cache, int cubeX, int cubeY, int cubeZ) { Column column = cache.loadChunk(cubeX, cubeZ); QueuedCube key = new QueuedCube(cubeX, cubeY, cubeZ, world); AsyncCubeIOProvider task = cubeTasks.remove(key); if (task != null) { runTask(task); } else { task = new AsyncCubeIOProvider(key, loader); task.setColumn(column); task.run(); task.runSynchronousPart(); } task.runCallbacks(); return task.get(); }

Target:
public static Cube syncCubeLoad(ICubicWorld world, CubeIO loader, ServerCubeCache cache, int cubeX, int cubeY, int cubeZ) { Column column = cache.loadChunk(cubeX, cubeZ); QueuedCube key = new QueuedCube(cubeX, cubeY, cubeZ, world); AsyncCubeIOProvider task = cubeTasks.remove(key); if (task != null) { runTask(task); } else { task = new AsyncCubeIOProvider(key, loader); task.setColumn(column); task.run(); } task.runSynchronousPart(); return task.get(); }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (getParameters() == null || getParameters().getConfigParams() == null || getParameters().getConfigParams().size() == 0) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAMS_IS_EMPTY); return false; } for (GlusterVolumeSnapshotConfig param : getParameters().getConfigParams()) { if (param.getParamValue() == null || param.getParamValue().equals("")) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (getParameters().getConfigParams() == null || getParameters().getConfigParams().size() == 0) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAMS_IS_EMPTY); return false; } for (GlusterVolumeSnapshotConfig param : getParameters().getConfigParams()) { if (param.getParamValue() == null || param.getParamValue().equals("")) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }
Source:
static RoomAppDatabase obtainInstance(Context context) { RoomAppDatabase database = singleInstance; if (database == null) { synchronized (LOCK) { database = singleInstance; if (database == null) { singleInstance = newInstance(context); database = singleInstance; } } } return database; }

Target:
static RoomAppDatabase obtainInstance(Context context) { if (singleInstance == null) { synchronized (RoomAppDatabase.class) { if (singleInstance == null) { singleInstance = newInstance(context); } } } return singleInstance; }
Source:
private boolean createTable() { try { ControllerTest.sendPostRequest( ControllerRequestURLBuilder.baseUrl(CONTROLLER_URL).forSchemaCreate(), FileUtils.readFileToString(new File(_schemaFileName))); return true; } catch (IOException e) { System.out.println(e.getMessage()); return false; } }

Target:
private boolean createTable() { try { ControllerTest.sendPostRequest( ControllerRequestURLBuilder.baseUrl(ClusterDescriptor.CONTROLLER_URL).forTableCreate(), FileUtils.readFileToString(new File(_tableConfigFileName))); return true; } catch (IOException e) { LOGGER.error("Failed to create table with file: {}", _tableConfigFileName, e); return false; } }
Source:
protected void onReadRequestStart(Channel channel) { if (readsSemaphore != null) { if (!readsSemaphore.tryAcquire()) { final long throttlingStartTimeNanos = MathUtils.nowInNano(); channel.config().setAutoRead(false); readsBlocked.incrementAndGet(); readsSemaphore.acquireUninterruptibly(); channel.config().setAutoRead(true); readEntryBlockedStats.registerSuccessfulEvent(MathUtils.elapsedNanos(throttlingStartTimeNanos), TimeUnit.NANOSECONDS); readsBlocked.decrementAndGet(); } } final int curr = readsInProgress.incrementAndGet(); maxReadsInProgress.accumulateAndGet(curr, Integer::max); }

Target:
protected void onReadRequestStart(Channel channel) { if (readsSemaphore != null) { if (!readsSemaphore.tryAcquire()) { final long throttlingStartTimeNanos = MathUtils.nowInNano(); channel.config().setAutoRead(false); LOG.info("Too many read requests in progress, disabling autoread on channel {}", channel); readsBlocked.incrementAndGet(); readsSemaphore.acquireUninterruptibly(); channel.config().setAutoRead(true); final long delayNanos = MathUtils.elapsedNanos(throttlingStartTimeNanos); LOG.info("Re-enabled autoread on channel after ReadRequest delay of nanos", channel, delayNanos); readEntryBlockedStats.registerSuccessfulEvent(delayNanos, TimeUnit.NANOSECONDS); readsBlocked.decrementAndGet(); } } final int curr = readsInProgress.incrementAndGet(); maxReadsInProgress.accumulateAndGet(curr, Integer::max); }
Source:
private boolean filterFlushLines() throws IOException { boolean flushed = false; if (buf.position() > 0) { buf.flip(); Matcher matcher = EOL.matcher(buf); int start = 0; while (matcher.find()) { int end = matcher.end(); String line = buf.subSequence(start, end).toString(); String filtered = contentFilter.filter(line); out.write(filtered.getBytes(charset)); start = end; flushed = true; } buf.position(start); if (buf.capacity() - buf.remaining() > DEFAULT_DECODER_CAPACITY) { buf = CharBuffer.allocate(DEFAULT_DECODER_CAPACITY).put(buf); } else { buf.compact(); } } return flushed; }

Target:
private boolean filterFlushLines() throws IOException { ensureOpen(); boolean flushed = false; if (decodedBuf.position() > 0) { decodedBuf.flip(); Matcher matcher = EOL.matcher(decodedBuf); int start = 0; while (matcher.find()) { int end = matcher.end(); String line = decodedBuf.subSequence(start, end).toString(); String filtered = contentFilter.filter(line); out.write(filtered.getBytes(charset)); start = end; flushed = true; } decodedBuf.position(start); decodedBuf.compact(); } return flushed; }
Source:
public static long dateToLong(Object datelike) { if (datelike instanceof Date) { Date date = (Date) datelike; return date.getTime(); } else if (datelike instanceof Instant) { Instant instant = (Instant) datelike; return instant.toEpochMilli(); } else if (datelike instanceof LocalDateTime) { LocalDateTime date = (LocalDateTime) datelike; return date.atZone(ZoneId.of("UTC")).toInstant().toEpochMilli(); } else if (datelike instanceof LocalDate) { LocalDate date = (LocalDate) datelike; return date.atStartOfDay(ZoneId.of("UTC")).toInstant().toEpochMilli(); } else { throw new IllegalArgumentException("Illegal argument " + datelike + ". Expected a Number, Date, Instant, LocalDateTime, or LocalDate"); } }

Target:
public static long dateToLong(Object datelike) { if (datelike instanceof Date) { Date date = (Date) datelike; return date.getTime(); } else if (datelike instanceof Calendar) { Calendar calendar = (Calendar) datelike; return calendar.getTimeInMillis(); } else if (datelike instanceof Instant) { Instant instant = (Instant) datelike; return instant.toEpochMilli(); } else if (datelike instanceof LocalDateTime) { LocalDateTime date = (LocalDateTime) datelike; return date.atZone(ZoneId.of("UTC")).toInstant().toEpochMilli(); } else if (datelike instanceof LocalDate) { LocalDate date = (LocalDate) datelike; return date.atStartOfDay(ZoneId.of("UTC")).toInstant().toEpochMilli(); } else { throw new IllegalArgumentException("Illegal argument " + datelike + ". Expected a Number, Date, Instant, LocalDateTime, or LocalDate"); } }
Source:
public void createSimpleSaml2AuthenticatedPrincipal() { Map<String, Object> attributes = TestSamlResponseAttributes.getAttributes(); SimpleSaml2AuthenticatedPrincipal principal = new SimpleSaml2AuthenticatedPrincipal("user", attributes); Assert.assertEquals("user", principal.getName()); Assert.assertTrue("attributes", attributes.equals(principal.getAttributes())); }

Target:
public void createSimpleSaml2AuthenticatedPrincipal() { Map<String, List<Object>> attributes = new LinkedHashMap<>(); attributes.put("email", Arrays.asList("john.doe@example.com", "doe.john@example.com")); SimpleSaml2AuthenticatedPrincipal principal = new SimpleSaml2AuthenticatedPrincipal("user", attributes); assertThat(principal.getName()).isEqualTo("user"); assertThat(principal.getAttributes()).isEqualTo(attributes); }
Source:
private boolean areAllReferencingExprsCoveredByIndex(IndexDescriptor id) throws StandardException { if (referencingExpressions == null || referencingExpressions.isEmpty()) { return false; } return getRefExprIndexPositions(id).size() == referencingExpressions.size(); }

Target:
private boolean areAllReferencingExprsCoveredByIndex(IndexDescriptor id) throws StandardException { if (referencingExpressions == null || referencingExpressions.isEmpty()) { return true; } return getRefExprIndexPositions(id).size() == referencingExpressions.size(); }
Source:
protected void tearDown() throws Exception { target = null; commandStack = null; session.close(new NullProgressMonitor()); session = null; super.tearDown(); }

Target:
protected void tearDown() throws Exception { domain = null; target = null; commandStack = null; session.close(new NullProgressMonitor()); session = null; super.tearDown(); }
Source:
public void authorizeStreamRead(final EventType eventType) throws AccessDeniedException { if (eventType.getAuthorization() == null) { return; } final Resource resource = new EventTypeResource(eventType.getName(), eventType.getAuthorization()); try { if (!authorizationService.isAuthorized(AuthorizationService.Operation.READ, resource)) { if (!adminService.hasAllDataAccess(AuthorizationService.Operation.READ)) { throw new AccessDeniedException(AuthorizationService.Operation.READ, resource); } } } catch (final PluginException e) { throw new ServiceTemporarilyUnavailableException("Error calling authorization plugin", e); } }

Target:
public void authorizeStreamRead(final EventType eventType) throws AccessDeniedException { if (eventType.getAuthorization() == null) { return; } final Resource resource = new EventTypeResource(eventType.getName(), eventType.getAuthorization()); try { if (!authorizationService.isAuthorized(AuthorizationService.Operation.READ, resource) && !adminService.hasAllDataAccess(AuthorizationService.Operation.READ)) { throw new AccessDeniedException(AuthorizationService.Operation.READ, resource); } } catch (final PluginException e) { throw new ServiceTemporarilyUnavailableException("Error calling authorization plugin", e); } }
Source:
private void processSoftwareRequirement(ArtifactReadable softwareRequirement, String criticality) throws IOException { writer.writeCell(softwareRequirement.getName(), SafetyReportGenerator.SOFTWARE_REQUIREMENT_INDEX); String softwareRequirementDAL = writeCriticalityWithDesignCheck(softwareRequirement, criticality, CoreRelationTypes.Requirement_Trace__Higher_Level, CoreAttributeTypes.DevelopmentAssuranceLevel); writer.writeCell(calculateBoeingEquivalentSWQualLevel(softwareRequirementDAL, softwareRequirement.getAttributeCount(CoreAttributeTypes.Partition))); writer.writeCell(functionalCategory); writer.writeCell(Collections.toString(",", getAttributesToStringList(softwareRequirement, CoreAttributeTypes.Partition))); writer.writeCell(safetyReport.getComponentUtil().getQualifiedComponentNames(softwareRequirement)); Collection<String> codeUnits = safetyReport.getRequirementToCodeUnitsValues(softwareRequirement); if (codeUnits == null || codeUnits.isEmpty()) { writer.endRow(); } else { for (String codeUnit : codeUnits) { writer.writeCell(codeUnit, SafetyReportGenerator.CODE_UNIT_INDEX); writer.endRow(); } } }

Target:
private void processSoftwareRequirement(ArtifactReadable softwareRequirement, String criticality) throws IOException { writer.writeCell(softwareRequirement.getName(), SafetyReportGenerator.SOFTWARE_REQUIREMENT_INDEX); String softwareRequirementDAL = writeCriticalityWithDesignCheck(softwareRequirement, criticality, CoreRelationTypes.Requirement_Trace__Higher_Level, CoreAttributeTypes.DevelopmentAssuranceLevel); writer.writeCell(calculateBoeingEquivalentSWQualLevel(softwareRequirementDAL, softwareRequirement.getAttributeCount(CoreAttributeTypes.Partition))); writer.writeCell(functionalCategory); writer.writeCell(Collections.toString(",", getAttributesToStringList(softwareRequirement, CoreAttributeTypes.Partition))); writer.writeCell(safetyReport.getComponentUtil().getQualifiedComponentNames(softwareRequirement)); Collection<String> codeUnits = safetyReport.getRequirementToCodeUnitsValues(softwareRequirement); if (Conditions.hasValues(codeUnits)) { for (String codeUnit : codeUnits) { writer.writeCell(codeUnit, SafetyReportGenerator.CODE_UNIT_INDEX); writer.endRow(); } } else { writer.endRow(); } }
Source:
public static <T> TraversalControl changeNode(TraverserContext<T> context, T changedNode) { NodeZipper<T> zipperWithChangedNode = context.getVar(NodeZipper.class).withNewNode(changedNode); boolean changed = context.isChanged(); if (context.isParallel()) { Queue<NodeZipper<T>> zippers = context.getSharedContextData(); if (changed) { throw new RuntimeException("multiple changes per node not supported for parallel"); } else { zippers.add(zipperWithChangedNode); context.changeNode(changedNode); } return TraversalControl.CONTINUE; } else { List<NodeZipper<T>> zippers = context.getSharedContextData(); if (changed) { replaceZipperForNode(zippers, context.thisNode(), changedNode); context.changeNode(changedNode); } else { zippers.add(zipperWithChangedNode); context.changeNode(changedNode); } return TraversalControl.CONTINUE; } }

Target:
public static <T> TraversalControl changeNode(TraverserContext<T> context, T changedNode) { NodeZipper<T> zipperWithChangedNode = context.getVar(NodeZipper.class).withNewNode(changedNode); boolean changed = context.isChanged(); if (context.isParallel()) { Queue<NodeZipper<T>> zippers = context.getSharedContextData(); if (changed) { replaceZipperForNodeParallel(zippers, context.thisNode(), changedNode); context.changeNode(changedNode); } else { zippers.add(zipperWithChangedNode); context.changeNode(changedNode); } return TraversalControl.CONTINUE; } else { List<NodeZipper<T>> zippers = context.getSharedContextData(); if (changed) { replaceZipperForNode(zippers, context.thisNode(), changedNode); context.changeNode(changedNode); } else { zippers.add(zipperWithChangedNode); context.changeNode(changedNode); } return TraversalControl.CONTINUE; } }
Source:
void threadSafeStringParametersTest() throws Exception { String[] iatas = { "JFK", "IAD", "SFO", "SJC", "SEA", "LAX", "PHX" }; Future[] future = new Future[iatas.length]; ExecutorService executorService = Executors.newFixedThreadPool(iatas.length); try { for (int i = 0; i < iatas.length; i++) { Airport airport = new Airport("airports::" + iatas[i], iatas[i] , iatas[i].toLowerCase() ); airportRepository.save(airport); } try { Thread.sleep(1000); } catch (InterruptedException ie) { ; } for (int k = 0; k < 100; k++) { Callable<Boolean>[] suppliers = new Callable[iatas.length]; for (int i = 0; i < iatas.length; i++) { final int idx = i; suppliers[i] = () -> { try { Thread.sleep(iatas.length - idx); } catch (InterruptedException ie) { ; } String foundName = airportRepository.getAllByIata(iatas[idx]).get(0).getIata(); assertEquals(iatas[idx], foundName); return iatas[idx].equals(foundName); }; } for (int i = 0; i < iatas.length; i++) { future[i] = executorService.submit(suppliers[i]); } for (int i = 0; i < iatas.length; i++) { future[i].get(); } } } finally { executorService.shutdown(); for (int i = 0; i < iatas.length; i++) { Airport airport = new Airport("airports::" + iatas[i], iatas[i] , iatas[i] ); airportRepository.delete(airport); } } }

Target:
void threadSafeStringParametersTest() throws Exception { String[] iatas = { "JFK", "IAD", "SFO", "SJC", "SEA", "LAX", "PHX" }; Future[] future = new Future[iatas.length]; ExecutorService executorService = Executors.newFixedThreadPool(iatas.length); try { for (int i = 0; i < iatas.length; i++) { Airport airport = new Airport("airports::" + iatas[i], iatas[i] , iatas[i].toLowerCase() ); airportRepository.save(airport); } sleep(1000); for (int k = 0; k < 100; k++) { Callable<Boolean>[] suppliers = new Callable[iatas.length]; for (int i = 0; i < iatas.length; i++) { final int idx = i; suppliers[i] = () -> { sleep(iatas.length - idx); String foundName = airportRepository.getAllByIata(iatas[idx]).get(0).getIata(); assertEquals(iatas[idx], foundName); return iatas[idx].equals(foundName); }; } for (int i = 0; i < iatas.length; i++) { future[i] = executorService.submit(suppliers[i]); } for (int i = 0; i < iatas.length; i++) { future[i].get(); } } } finally { executorService.shutdown(); for (int i = 0; i < iatas.length; i++) { Airport airport = new Airport("airports::" + iatas[i], iatas[i] , iatas[i] ); airportRepository.delete(airport); } } }
Source:
public void getGlobalPropertyValue_shouldFailIfDefaultValueIsNull() { exception.expect(IllegalArgumentException.class); exception.expectMessage("The defaultValue argument cannot be null"); adminService.getGlobalPropertyValue("valid.double", null); }

Target:
public void getGlobalPropertyValue_shouldFailIfDefaultValueIsNull() { adminService.getGlobalPropertyValue("valid.double", null); }
Source:
private static ImmutableList<Arguments> getRequiredArgs(final Ds3Request ds3Request) { final ImmutableList.Builder<Arguments> requiredArgsBuilder = ImmutableList.builder(); LOG.debug("Getting required args..."); if (ds3Request.getBucketRequirement() == Requirement.REQUIRED) { LOG.debug("bucket name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "bucketName")); if (ds3Request.getObjectRequirement() == Requirement.REQUIRED) { LOG.debug("object name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "objectName")); } } LOG.debug("Getting required query params..."); if (ds3Request.getRequiredQueryParams() == null) { return requiredArgsBuilder.build(); } for (final Ds3Param ds3Param : ds3Request.getRequiredQueryParams()) { if (ds3Param == null) break; LOG.debug("query param " + ds3Param.getType()); final String paramType = ds3Param.getType().substring(ds3Param.getType().lastIndexOf(".") + 1); LOG.debug("param " + paramType + " is required."); requiredArgsBuilder.add(new Arguments(paramType, ds3Param.getName())); } return requiredArgsBuilder.build(); }

Target:
private static ImmutableList<Arguments> getRequiredArgs(final Ds3Request ds3Request) { final ImmutableList.Builder<Arguments> requiredArgsBuilder = ImmutableList.builder(); LOG.debug("Getting required args..."); if (ds3Request.getBucketRequirement() == Requirement.REQUIRED) { LOG.debug("bucket name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "bucketName")); if (ds3Request.getObjectRequirement() == Requirement.REQUIRED) { LOG.debug("object name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "objectName")); } } LOG.debug("Getting required query params..."); if (ConverterUtil.isEmpty(ds3Request.getRequiredQueryParams())) { return requiredArgsBuilder.build(); } for (final Ds3Param ds3Param : ds3Request.getRequiredQueryParams()) { if (ds3Param == null) break; LOG.debug("query param " + ds3Param.getType()); final String paramType = ds3Param.getType().substring(ds3Param.getType().lastIndexOf(".") + 1); LOG.debug("param " + paramType + " is required."); requiredArgsBuilder.add(new Arguments(paramType, ds3Param.getName())); } return requiredArgsBuilder.build(); }
Source:
public int hashCode() { int result = delegate != null ? delegate.hashCode() : 0; result = 31 * result + typeParameter.hashCode(); result = 31 * result + typeForValidatorResolution.hashCode(); return result; }

Target:
public int hashCode() { return hashCode; }
Source:
public ClientConnection connect() throws TechnicalException { if (this.device == null) { throw new IllegalStateException("Can not connect because no device is set."); } this.checkIpAddress(); try { final ClientConnection connection = this.createConnection(); this.discardInvalidKeys(); return connection; } catch (final UnknownHostException e) { LOGGER.warn("The IP address is not found: {}", this.device.getIpAddress(), e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "The IP address is not found: " + this.device.getIpAddress()); } catch (final IOException e) { if (this.device.hasNewSecurityKey()) { this.recoverKeyProcessInitiator.initiate(this.device.getDeviceIdentification(), this.device.getIpAddress()); } throw new ConnectionException(e); } catch (final RsaEncrypterException e) { LOGGER.error("RSA decryption on security keys went wrong for device with ip: {}", this.device.getIpAddress(), e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "RSA decryption on security keys went wrong for device with ip: " + this.device.getIpAddress()); } }

Target:
public ClientConnection connect() throws TechnicalException { if (this.device == null) { throw new IllegalStateException("Can not connect because no device is set."); } this.checkIpAddress(); try { final ClientConnection connection = this.createConnection(); this.discardInvalidKeys(); return connection; } catch (final UnknownHostException e) { LOGGER.warn("The IP address is not found: {}", this.device.getIpAddress(), e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "The IP address is not found: " + this.device.getIpAddress()); } catch (final IOException e) { if (this.device.hasNewSecurityKey()) { this.recoverKeyProcessInitiator.initiate(this.device.getDeviceIdentification(), this.device.getIpAddress()); } throw new ConnectionException(e); } catch (final RsaEncrypterException e) { LOGGER.error("RSA decryption on security keys went wrong for device: {}", this.device.getDeviceIdentification(), e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "RSA decryption on security keys went wrong for device: " + this.device.getDeviceIdentification()); } }
Source:
protected void configure() { if (clusterPassword.length() < REQUIRED_DEFAULT_PASSWORD_LENGTH) { logger().warn("The provided cluster admin password length is less then the default password policy length. " + "Cluster start will fail if configured password policy is offended."); } }

Target:
protected void configure() { if (clusterPassword.length() < REQUIRED_DEFAULT_PASSWORD_LENGTH) { logger().warn("The provided cluster admin password length is less then the default password policy length. " + "Cluster start will fail if configured password requirements are not met."); } }
Source:
public void setVmtGuid(Guid value) { vmtGuid = value; }

Target:
public void setVmtGuid(Guid value) { this.vmtGuid = value; }
Source:
PluginWrapper createPluginWrapper(File archive) throws IOException; @Nonnull String getShortName(File archive) throws IOException; void load(PluginWrapper wrapper) throws IOException; void initializeComponents(PluginWrapper plugin); <T> List<ExtensionComponent<T>> findComponents(Class<T> type, Hudson hudson); default void updateDependency(PluginWrapper depender, PluginWrapper dependee)

Target:
PluginWrapper createPluginWrapper(File archive) throws IOException; @Nonnull String getShortName(File archive) throws IOException; void load(PluginWrapper wrapper) throws IOException; void initializeComponents(PluginWrapper plugin); <T> List<ExtensionComponent<T>> findComponents(Class<T> type, Hudson hudson); default void updateDependency(PluginWrapper depender, PluginWrapper dependee) { Logger.getLogger(PluginStrategy.class.getName()).log(Level.WARNING, "{0} does not yet implement updateDependency", getClass()); }
Source:
public Map<String, MapSession> findByIndexNameAndIndexValue(String indexName, String indexValue) { if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Collections.emptyMap(); } return cache.getNativeCache().values().stream() .map(cacheValue -> (MapSession) cacheValue) .filter(session -> indexValue.equals(principalNameResolver.resolvePrincipal(session))) .collect(Collectors.toMap(session -> session.getId(), session -> session)); }

Target:
public Map<String, MapSession> findByIndexNameAndIndexValue(String indexName, String indexValue) { if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Collections.emptyMap(); } return cache.getNativeCache().values().stream() .map(cacheValue -> (MapSession) cacheValue) .filter(session -> indexValue.equals(principalNameResolver.resolvePrincipal(session))) .collect(Collectors.toMap(MapSession::getId, Function.identity())); }
Source:
public Map<String, List<WriteRequest>> toWriteRequestItems(final List<DeviceData> deviceDataList) { final Map<String, Map<String, WriteRequest>> writeRequestMap = Maps.newHashMap(); for (final DeviceData data: deviceDataList) { final String tableName = getTableName(data.dateTimeUTC); final Map<String, AttributeValue> item = deviceDataToAttributeMap(data); final String hashAndRangeKey = item.get(Attribute.ACCOUNT_ID.name).getN() + item.get(Attribute.RANGE_KEY.name).getS(); final WriteRequest request = new WriteRequest().withPutRequest(new PutRequest().withItem(item)); if (writeRequestMap.containsKey(tableName)) { writeRequestMap.get(tableName).put(hashAndRangeKey, request); } else { final Map<String, WriteRequest> newMap = Maps.newHashMap(); newMap.put(hashAndRangeKey, request); writeRequestMap.put(tableName, newMap); } } Map<String, List<WriteRequest>> requestItems = Maps.newHashMapWithExpectedSize(writeRequestMap.size()); for (final Map.Entry<String, Map<String, WriteRequest>> entry : writeRequestMap.entrySet()) { requestItems.put(entry.getKey(), Lists.newArrayList(entry.getValue().values())); } return requestItems; }

Target:
public Map<String, List<WriteRequest>> toWriteRequestItems(final List<DeviceData> deviceDataList) { final Map<String, Map<String, WriteRequest>> writeRequestMap = Maps.newHashMap(); for (final DeviceData data: deviceDataList) { final String tableName = getTableName(data.dateTimeUTC); final Map<String, AttributeValue> item = deviceDataToAttributeMap(data); final String hashAndRangeKey = item.get(Attribute.ACCOUNT_ID.name).getN() + item.get(Attribute.RANGE_KEY.name).getS(); final WriteRequest request = new WriteRequest().withPutRequest(new PutRequest().withItem(item)); if (writeRequestMap.containsKey(tableName)) { writeRequestMap.get(tableName).put(hashAndRangeKey, request); } else { final Map<String, WriteRequest> newMap = Maps.newHashMap(); newMap.put(hashAndRangeKey, request); writeRequestMap.put(tableName, newMap); } } final Map<String, List<WriteRequest>> requestItems = Maps.newHashMapWithExpectedSize(writeRequestMap.size()); for (final Map.Entry<String, Map<String, WriteRequest>> entry : writeRequestMap.entrySet()) { requestItems.put(entry.getKey(), Lists.newArrayList(entry.getValue().values())); } return requestItems; }