auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean isRowSorted(List<String> row) { for(int i=1;i<row.size()-1;i++) { if(row.get(i).compareTo(row.get(i+1))>0) { return false; } } return true; }

Target:
public boolean isRowSorted(List<String> row) { return row.equals(row.stream().sorted().collect(Collectors.toList())); }
Source:
public synchronized NettyClientBase getTajoMasterConnection() throws ServiceException { if (client == null || !client.isConnected()) { try { RpcClientManager.cleanup(client); this.client = manager.newClient(getTajoMasterAddr(), TajoMasterClientProtocol.class, false, manager.getRetries(), manager.getTimeoutSeconds(), TimeUnit.SECONDS, false); } catch (Exception e) { throw new ServiceException(e); } } return client; }

Target:
public synchronized NettyClientBase getTajoMasterConnection() throws ServiceException { if (client != null && client.isConnected()) return client; else { try { RpcClientManager.cleanup(client); this.client = manager.newClient(getTajoMasterAddr(), TajoMasterClientProtocol.class, false, manager.getRetries(), 0, TimeUnit.SECONDS, false); } catch (Exception e) { throw new ServiceException(e); } return client; } }
Source:
private JsonObject toJsonObject(final UserProfile up) { final JsonObject object = new JsonObject(); object.addProperty("username", up.getUser().getUsername()); object.addProperty("givenNames", up.getGivenNames()); object.addProperty("familyNames", up.getFamilyNames()); object.addProperty("displayName", up.getDisplayName()); object.addProperty("email", up.getEmail()); object.addProperty("userAliasses", aliassesFor(up)); LocalDate expiration = up.getUser().getExpiration(); object.addProperty("expiration", expiration == null ? null : expiration.toString()); object.add("roles", LegacyRoleUtils.mainRoleKeys(up.getUser()).stream().map(JsonPrimitive::new).collect(toJsonArray())); return object; }

Target:
private JsonObject toJsonObject(final UserProfile up) { final JsonObject object = new JsonObject(); object.addProperty("username", up.getUser().getUsername()); object.addProperty("givenNames", up.getGivenNames()); object.addProperty("familyNames", up.getFamilyNames()); object.addProperty("displayName", up.getDisplayName()); object.addProperty("email", up.getEmail()); object.add("userAliases", aliasesFor(up)); LocalDate expiration = up.getUser().getExpiration(); object.addProperty("expiration", expiration == null ? null : expiration.toString()); object.add("roles", LegacyRoleUtils.mainRoleKeys(up.getUser()).stream().map(JsonPrimitive::new).collect(toJsonArray())); return object; }
Source:
public void testSetEditorDoesUpdateReturnToDRGTextWhenHasNameIsNotEmpty() { final String NAME = "NAME"; final Name name = new Name(NAME); final Optional<HasName> hasName = Optional.of(new HasName() { @Override public Name getName() { return name; } @Override public void setName(final Name name) { } }); final Optional<Expression> expression = Optional.empty(); view.setEditor(editorDefinition, hasExpression, hasName, expression); verify(returnToDRG).setTextContent(eq(NAME)); }

Target:
public void testSetEditorDoesUpdateReturnToDRGTextWhenHasNameIsNotEmpty() { final String NAME = "NAME"; final Name name = new Name(NAME); final HasName hasNameMock = mock(HasName.class); doReturn(name).when(hasNameMock).getName(); final Optional<HasName> hasName = Optional.of(hasNameMock); final Optional<Expression> expression = Optional.empty(); view.setEditor(editorDefinition, hasExpression, hasName, expression); verify(returnToDRG).setTextContent(eq(NAME)); }
Source:
public WorkspaceProject resolveProject(final Space space, final Path path) { final org.uberfire.java.nio.file.Path repositoryRoot = Paths.convert(path).getRoot(); final Repository repository = repositoryService.getRepository(space, Paths.convert(repositoryRoot)); if (repository == null) { return null; } final Branch branch = resolveBranch(repositoryRoot, repository); return new WorkspaceProject(organizationalUnitService.getOrganizationalUnit(repository.getSpace().getName()), repository, branch, moduleService.resolveModule(Paths.convert(Paths.convert(branch.getPath()).getRoot()))); }

Target:
public WorkspaceProject resolveProject(final Space space, final Path path) { final org.uberfire.java.nio.file.Path repositoryRoot = Paths.convert(path).getRoot(); final Repository repository = repositoryService.getRepository(space, Paths.convert(repositoryRoot)); if (repository == null) { throw new RuntimeException("Repository not found inside space " + space.getName() + " with path " + path.toURI() + " (root path " + repositoryRoot.toUri() + ")"); } final Branch branch = resolveBranch(repositoryRoot, repository); return new WorkspaceProject(organizationalUnitService.getOrganizationalUnit(repository.getSpace().getName()), repository, branch, moduleService.resolveModule(Paths.convert(Paths.convert(branch.getPath()).getRoot()))); }
Source:
@Bean PaArchivesUpdater paRecentArchivesUpdater() { PaProgDataUpdatesProcessor paProgDataUpdatesProcessor = new PaProgrammeProcessor(contentWriter, contentBuffer(), log, new PaTagMap(topicStore, new MongoSequentialIdGenerator(mongo, "topics"))); PaUpdatesProcessor updatesProcessor = new PaUpdatesProcessor(paProgDataUpdatesProcessor, contentWriter); PaArchivesUpdater updater = new PaRecentArchiveUpdater(paProgrammeDataStore(), fileUploadResultStore(), updatesProcessor); return updater; }

Target:
@Bean PaArchivesUpdater paRecentArchivesUpdater() { PaProgDataUpdatesProcessor paProgDataUpdatesProcessor = new PaProgrammeProcessor(contentWriter, contentBuffer(), log, paTagMap); PaUpdatesProcessor updatesProcessor = new PaUpdatesProcessor(paProgDataUpdatesProcessor, contentWriter); PaArchivesUpdater updater = new PaRecentArchiveUpdater(paProgrammeDataStore(), fileUploadResultStore(), updatesProcessor); return updater; }
Source:
protected TmfCommonXAxisModel extractModelFromChart(final Chart chart, String... otherSeries) { String mainSeriesName = getMainSeriesName(); ISeries mainSeries = chart.getSeriesSet().getSeries(mainSeriesName); assertNotNull(mainSeries); double[] xMain = mainSeries.getXSeries(); double[] yMain = mainSeries.getYSeries(); Map<@NonNull String, @NonNull IYModel> yModels = new LinkedHashMap<>(); yModels.put(mainSeriesName, new YModel(mainSeriesName, Objects.requireNonNull(yMain))); for (String other : otherSeries) { if (other != null) { ISeries series = chart.getSeriesSet().getSeries(other); double[] xSeries = series.getXSeries(); double[] ySeries = series.getYSeries(); assertTrue("Series should have the same x axis values", Arrays.equals(xMain, xSeries)); yModels.put(other, new YModel(other, Objects.requireNonNull(ySeries))); } } long[] x = Longs.toArray(Doubles.asList(xMain)); assertNotNull(x); return new TmfCommonXAxisModel(getTitle(), x, yModels); }

Target:
protected TmfCommonXAxisModel extractModelFromChart(final Chart chart, String... otherSeries) { String analysisId = getAnalysisId(); if (analysisId != null) { ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); assertNotNull(trace); IAnalysisModule module = trace.getAnalysisModule(analysisId); assertNotNull(module); module.schedule(); assertTrue(module.waitForCompletion()); } String mainSeriesName = getMainSeriesName(); ISeries mainSeries = chart.getSeriesSet().getSeries(mainSeriesName); assertNotNull(mainSeries); double[] xMain = mainSeries.getXSeries(); double[] yMain = mainSeries.getYSeries(); Map<@NonNull String, @NonNull IYModel> yModels = new LinkedHashMap<>(); yModels.put(mainSeriesName, new YModel(mainSeriesName, Objects.requireNonNull(yMain))); for (String other : otherSeries) { if (other != null) { ISeries series = chart.getSeriesSet().getSeries(other); double[] xSeries = series.getXSeries(); double[] ySeries = series.getYSeries(); assertTrue("Series should have the same x axis values", Arrays.equals(xMain, xSeries)); yModels.put(other, new YModel(other, Objects.requireNonNull(ySeries))); } } long[] x = Longs.toArray(Doubles.asList(xMain)); assertNotNull(x); return new TmfCommonXAxisModel(getTitle(), x, yModels); }
Source:
public void onAttach(final Activity activity) { super.onAttach(activity); try { mListener = (Listener) activity; } catch (final ClassCastException e) { Lg.e(activity.getClass().getName(), " should implement ", Listener.class.getName()); } }

Target:
public void onAttach(final Activity activity) { super.onAttach(activity); if (activity instanceof Listener) { mListener = (Listener) activity; } else { Lg.e(activity.getClass().getName(), " should implement ", Listener.class.getName()); } }
Source:
private static Timestamp getTimestampValue(final PluginTask task, final Column column, final String value) { final List<ColumnConfig> columnConfigs = task.getColumns().getColumns(); String pattern = DEFAULT_TIMESTAMP_PATTERN; for (final ColumnConfig config : columnConfigs) { final ConfigSource columnConfig = config.getConfigSource(); if (config.getName().equals(column.getName()) && columnConfig != null && columnConfig.has("format")) { pattern = columnConfig.get(String.class, "format"); break; } } final TimestampParser parser = TimestampParser.of(pattern, "UTC"); Timestamp result = null; try { result = parser.parse(value); } catch (final Exception e) { } return result; }

Target:
private static Timestamp getTimestampValue(final PluginTask task, final Column column, final String value) { final List<ColumnConfig> columnConfigs = task.getColumns().getColumns(); String pattern = DEFAULT_TIMESTAMP_PATTERN; for (final ColumnConfig columnConfig : columnConfigs) { final ConfigSource columnConfigSource = columnConfig.getConfigSource(); if (columnConfig.getName().equals(column.getName()) && columnConfigSource != null && columnConfigSource.has("format")) { pattern = columnConfigSource.get(String.class, "format"); break; } } final TimestampParser parser = TimestampParser.of(pattern, "UTC"); Timestamp result = null; try { result = parser.parse(value); } catch (final Exception e) { } return result; }
Source:
public static String getResponseType(final ImmutableList<Ds3ResponseCode> responseCodes) { if (isEmpty(responseCodes)) return ""; String responseTypeName = ""; for (final Ds3ResponseCode responseCode : responseCodes) { final int rc = responseCode.getCode(); if (rc < 200 || rc >= 300) continue; for (final Ds3ResponseType responseType : responseCode.getDs3ResponseTypes()) { if (ConverterUtil.hasContent(responseType.getType()) && !responseType.getType().contentEquals("null")) { responseTypeName = responseType.getType(); } if (ConverterUtil.hasContent(responseType.getComponentType()) && !responseType.getComponentType().contentEquals("null")) { responseTypeName = responseType.getComponentType(); } } } if (responseTypeName.equalsIgnoreCase("java.lang.String")) { return "ds3_str"; } else if (!responseTypeName.isEmpty()) { return StructHelper.getResponseTypeName(responseTypeName); } return ""; }

Target:
public static String getResponseType(final ImmutableList<Ds3ResponseCode> responseCodes) { if (isEmpty(responseCodes)) return ""; String responseTypeName = ""; for (final Ds3ResponseCode responseCode : responseCodes) { final int rc = responseCode.getCode(); if (rc < 200 || rc >= 300) continue; for (final Ds3ResponseType responseType : responseCode.getDs3ResponseTypes()) { if (ConverterUtil.hasContent(responseType.getType()) && !responseType.getType().contentEquals("null")) { responseTypeName = responseType.getType(); } else if (ConverterUtil.hasContent(responseType.getComponentType()) && !responseType.getComponentType().contentEquals("null")) { responseTypeName = responseType.getComponentType(); } } } if (responseTypeName.equalsIgnoreCase("java.lang.String")) { return "ds3_str"; } else if (!responseTypeName.isEmpty()) { return StructHelper.getResponseTypeName(responseTypeName); } return ""; }
Source:
private void unlockAll() { if (undoLog != null && undoLog.size() > 0) { DbException.throwInternalError(); } if (!locks.isEmpty()) { Table[] array = locks.toArray(new Table[0]); for (Table t : array) { t.unlock(this); } locks.clear(); } database.unlockMetaDebug(this); savepoints = null; sessionStateChanged = true; }

Target:
private void unlockAll() { if (undoLog != null && undoLog.size() > 0) { DbException.throwInternalError(); } if (!locks.isEmpty()) { Table[] array = locks.toArray(new Table[0]); for (Table t : array) { if (t != null) { t.unlock(this); } } locks.clear(); } database.unlockMetaDebug(this); savepoints = null; sessionStateChanged = true; }
Source:
public Filter adapt(FilterAdapterContext context, ColumnPrefixFilter filter) throws IOException { byte[] prefix = filter.getPrefix(); ByteString.Output outputStream = ByteString.newOutput(prefix.length * 2); ReaderExpressionHelper.writeQuotedExpression(outputStream, prefix); outputStream.write(ReaderExpressionHelper.ALL_QUALIFIERS_BYTES); return FILTERS.qualifier().regex(outputStream.toByteString()); }

Target:
public Filter adapt(FilterAdapterContext context, ColumnPrefixFilter filter) throws IOException { byte[] prefix = filter.getPrefix(); ByteString.Output outputStream = ByteString.newOutput(prefix.length * 2); ReaderExpressionHelper.writeQuotedExpression(outputStream, prefix); outputStream.write(ReaderExpressionHelper.ALL_QUALIFIERS_BYTES); Filter qualifierFilter = FILTERS.qualifier().regex(outputStream.toByteString()); return FILTERS.chain().filter(qualifierFilter); }
Source:
private Observable<List<MovedFile>> moveFiles(String folderName) { File file = getPublicFolder(folderName); List<MovedFile> movedFiles = new ArrayList<>(); if (file.exists()) { File[] files = file.listFiles(); movedFiles = copyFiles(files, folderName); if (files.length == movedFiles.size()) { file.delete(); } } return Observable.just(movedFiles); }

Target:
private Observable<List<MovedFile>> moveFiles(String folderName) { File publicFolder = getPublicFolder(folderName); List<MovedFile> movedFiles = new ArrayList<>(); if (publicFolder.exists()) { File[] files = publicFolder.listFiles(); movedFiles = copyFiles(files, folderName); if (files.length == movedFiles.size()) { publicFolder.delete(); } } return Observable.just(movedFiles); }
Source:
public void updateVirtioScsiController(VmBase vm, Boolean isVirtioScsiEnabled) { if (isVirtioScsiEnabled == null) { return; } if (isVirtioScsiEnabled) { if (!hasVirtioScsiController(vm.getId())) { addVirtioScsiController(vm); } } else { removeVirtioScsiControllers(vm.getId()); } }

Target:
public void updateVirtioScsiController(VmBase vm, Boolean isVirtioScsiEnabled) { if (isVirtioScsiEnabled == null) { return; } removeVirtioScsiControllers(vm.getId()); if (isVirtioScsiEnabled) { addVirtioScsiController(vm); } }
Source:
public static <T> T[] insert(T element, T[] array, Class<T> componentType) { boolean inserted = false; for (int i = 0; i < array.length; ++i) { if (array[i] == null) { array[i] = element; inserted = true; } } if (!inserted) { add(array, componentType, element); } return array; }

Target:
public static <T> T[] insert(T element, T[] array, Class<T> componentType) { T[] arrayToReturn = array; boolean inserted = false; for (int i = 0; i < array.length; ++i) { if (array[i] == null) { array[i] = element; inserted = true; break; } } if (!inserted) { arrayToReturn = add(array, componentType, element); } return arrayToReturn; }
Source:
public void go(AcceptsOneWidget container) { final ProjectWizardMode wizardMode = ProjectWizardMode.parse(context.get(WIZARD_MODE_KEY)); final String projectName = dataObject.getName(); if (CREATE == wizardMode && projectName != null) { if (getAttribute(ARTIFACT_ID).isEmpty()) { setAttribute(ARTIFACT_ID, projectName); } if (getAttribute(GROUP_ID).isEmpty()) { setAttribute(GROUP_ID, projectName); } updateDelegate.updateControls(); } projectService .getItem(Path.valueOf(dataObject.getPath()).parent().append("pom.xml")) .then( result -> { updateView(container, false); }) .catchError( arg -> { updateView(container, CREATE == wizardMode); }); }

Target:
public void go(AcceptsOneWidget container) { final ProjectWizardMode wizardMode = ProjectWizardMode.parse(context.get(WIZARD_MODE_KEY)); final String projectName = dataObject.getName(); if (CREATE == wizardMode && projectName != null) { if (getAttribute(ARTIFACT_ID).isEmpty()) { setAttribute(ARTIFACT_ID, projectName); } if (getAttribute(GROUP_ID).isEmpty()) { setAttribute(GROUP_ID, projectName); } updateDelegate.updateControls(); } if (CREATE == wizardMode) { projectService .getItem(Path.valueOf(dataObject.getPath()).parent().append("pom.xml")) .then( result -> { notificationManager.notify( localization.mavenPageArchetypeDisabledTitle(), localization.mavenPageArchetypeDisabledMessage(), WARNING, EMERGE_MODE); updateView(container, false); }) .catchError( error -> { updateView(container, true); }); } else { updateView(container, false); } }
Source:
private void handleTransferring(final StateContext context) { if (context.iterationTimestamp >= getParameters().getSessionExpiration() - getHostTicketRefreshAllowance()) { log.info("Renewing transfer ticket for {}", getTransferDescription()); boolean extendSucceeded = extendImageTransferSession(context.entity); if (!extendSucceeded) { log.warn("Failed to renew transfer ticket for {}", getTransferDescription()); if (!getParameters().isRetryExtendTicket()) { updateEntityPhase(ImageTransferPhase.PAUSED_SYSTEM); getParameters().setRetryExtendTicket(true); } else { getParameters().setRetryExtendTicket(false); } } } else { log.debug("Not yet renewing transfer ticket for {}", getTransferDescription()); } resetPeriodicPauseLogTime(0); }

Target:
private void handleTransferring(final StateContext context) { if (context.iterationTimestamp >= getParameters().getSessionExpiration() - getHostTicketRefreshAllowance()) { log.info("Renewing transfer ticket for {}", getTransferDescription()); boolean extendSucceeded = extendImageTransferSession(context.entity); if (!extendSucceeded) { log.warn("Failed to renew transfer ticket for {}", getTransferDescription()); if (getParameters().isRetryExtendTicket()) { getParameters().setRetryExtendTicket(false); } else { updateEntityPhase(ImageTransferPhase.PAUSED_SYSTEM); getParameters().setRetryExtendTicket(true); } } } else { log.debug("Not yet renewing transfer ticket for {}", getTransferDescription()); } resetPeriodicPauseLogTime(0); if (getParameters().getTransferType() == TransferType.Download) { pollDownloadStatus(context); } }
Source:
public List<VDS> filter(SchedulingContext context, List<VDS> hosts, VM vm, PerHostMessages messages) { if (vm.getVmType() == VmType.HighPerformance) { VDS vmVds = vdsDao.get(vm.getRunOnVds()); if (vmVds == null || vmVds.getTscFrequency() == null) { return hosts; } return hosts.stream() .filter(vds -> vdsMatchesTscFrequency(messages, vmVds, vds)) .collect(Collectors.toList()); } return hosts; }

Target:
public List<VDS> filter(SchedulingContext context, List<VDS> hosts, VM vm, PerHostMessages messages) { if (vm.getRunOnVds() != null && vm.getVmType() == VmType.HighPerformance) { VDS vmVds = vdsDao.get(vm.getRunOnVds()); if (vmVds == null || vmVds.getTscFrequency() == null) { return hosts; } return hosts.stream() .filter(vds -> vdsMatchesTscFrequency(messages, vmVds, vds)) .collect(Collectors.toList()); } return hosts; }
Source:
public ResultSet getResultSet() throws SQLException { ResultSet resultSet = super.getResultSet(); return (resultSet == null) ? null : new LoggingPhoenixResultSet(super.getResultSet(), phoenixMetricsLog, sql); }

Target:
public ResultSet getResultSet() throws SQLException { ResultSet resultSet = super.getResultSet(); return (resultSet == null) ? null : new LoggingPhoenixResultSet(resultSet, phoenixMetricsLog, sql); }
Source:
public BackendClusterNetworkResource(String id, BackendClusterNetworksResource parent) { super(id, parent, ActionType.DetachNetworkToCluster); clusterId = ((BackendClusterNetworksResource)parent).clusterId; }

Target:
public BackendClusterNetworkResource(String id, BackendClusterNetworksResource parent) { super(id, parent, ActionType.DetachNetworkToCluster); clusterId = (parent).clusterId; }
Source:
public DbMetricsImpl(int maxTotalConnections, int minIdleConnections, long maxWaitMillis, long keepAliveMillis) { startTime = System.currentTimeMillis(); this.maxTotalConnections = maxTotalConnections; this.minIdleConnections = minIdleConnections; this.maxWaitMillis = maxWaitMillis; this.keepAliveMillis = keepAliveMillis; }

Target:
public DbMetricsImpl(int maxTotalConnections, int minIdleConnections, long maxWaitMillis, long keepAliveMillis) { this.startTime = System.currentTimeMillis(); this.maxTotalConnections = maxTotalConnections; this.minIdleConnections = minIdleConnections; this.maxWaitMillis = maxWaitMillis; this.keepAliveMillis = keepAliveMillis; }
Source:
public VcfLineMapper(VariantSource source) { this.source = source; factory = new VariantVcfFactory(); }

Target:
public VcfLineMapper(VariantSource source) { this.source = source; this.factory = new VariantVcfFactory(); }
Source:
private ResultSet findSchemaID(BinlogPosition targetPosition) throws SQLException { PreparedStatement s = connection .prepareStatement("SELECT * from `maxwell`.`schemas` where binlog_file <= ? and binlog_position <= ? " + "ORDER BY id desc limit 1"); s.setString(1, targetPosition.getFile()); s.setInt(2, targetPosition.getOffset()); ResultSet rs = s.executeQuery(); if (rs.next()) { return rs; } else return null; }

Target:
private ResultSet findSchemaID(BinlogPosition targetPosition) throws SQLException { PreparedStatement s = connection.prepareStatement( "SELECT * from `maxwell`.`schemas` " + "WHERE (binlog_file < ?) OR (binlog_file = ? and binlog_position <= ?) " + "ORDER BY id desc limit 1"); s.setString(1, targetPosition.getFile()); s.setString(2, targetPosition.getFile()); s.setInt(3, targetPosition.getOffset()); ResultSet rs = s.executeQuery(); if (rs.next()) { return rs; } else return null; }
Source:
public void onCreate() { super.onCreate(); mApp = this; mPrefs = PreferenceManager.getDefaultSharedPreferences(this); initOba(); initObaRegion(); NodeService.schedule(this); }

Target:
public void onCreate() { super.onCreate(); mApp = this; mPrefs = PreferenceManager.getDefaultSharedPreferences(this); initOba(); initObaRegion(); ObaAnalytics.initAnalytics(this); reportAnalytics(); }
Source:
public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof JobParserJobFactoryBean) { ((JobParserJobFactoryBean) bean).setJobExecutionListeners(this.jobExecutionListeners.toArray(new JobExecutionListener[this.jobExecutionListeners.size()])); } if (bean instanceof StepParserStepFactoryBean<?, ?>) { ((StepParserStepFactoryBean) bean).setListeners(this.stepListeners.toArray()); } if (bean instanceof FlowJob) { FlowJob job = (FlowJob) bean; job.setName(this.groupName); if (!jobRegistry.getJobNames().contains(groupName)) { jobLocator.addJob(groupName, (job.getJobParametersIncrementer() != null) ? true : false); jobLocator.addStepNames(groupName, job.getStepNames()); super.postProcessAfterInitialization(bean, beanName); } else { throw new BatchJobAlreadyExistsException(groupName); } } return bean; }

Target:
public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof JobParserJobFactoryBean) { addJobExecutionListener(); if (!this.jobExecutionListeners.isEmpty()) { ((JobParserJobFactoryBean) bean).setJobExecutionListeners(this.jobExecutionListeners.toArray(new JobExecutionListener[this.jobExecutionListeners.size()])); } } else if (bean instanceof StepParserStepFactoryBean<?, ?>) { addStepListeners(); if (!stepListeners.isEmpty()) { ((StepParserStepFactoryBean) bean).setListeners(this.stepListeners.toArray(new StepListener[this.stepListeners.size()])); } } else if (bean instanceof FlowJob) { FlowJob job = (FlowJob) bean; job.setName(this.groupName); if (!jobRegistry.getJobNames().contains(groupName)) { jobLocator.addJob(groupName, (job.getJobParametersIncrementer() != null) ? true : false); jobLocator.addStepNames(groupName, job.getStepNames()); super.postProcessAfterInitialization(bean, beanName); } else { throw new BatchJobAlreadyExistsException(groupName); } } return bean; }
Source:
public List<String> getStatusLineMessages() { return UIThreadRunnable.syncExec(new ListResult<String>() { @Override public List<String> run() { Control statusLine = null; IStatusLineManager s = null; int messageCount = 0; final List<String> l = new ArrayList<String>(); IWorkbenchPartSite site = bot.activeEditor().getReference().getPart(false).getSite(); if (site instanceof IViewSite) { s = ((IViewSite) site).getActionBars().getStatusLineManager(); } else if (site instanceof IEditorSite) { s = ((IEditorSite) site).getActionBars().getStatusLineManager(); } if (s instanceof SubStatusLineManager) { s = (IStatusLineManager) ((SubStatusLineManager) s).getParent(); } if (s instanceof StatusLineManager) { statusLine = ((StatusLineManager) s).getControl(); } if (statusLine == null) return l; SWTBot statusbot = new SWTBot(statusLine); try { @SuppressWarnings("unchecked") List<? extends Widget> separators = bot.widgets( allOf(widgetOfType(Label.class), withStyle(SWT.SEPARATOR, "Separator")), statusLine); messageCount = separators.size() + 1; } catch (Exception e) { messageCount = 1; } for (int i = 0; i < messageCount; i++) { try { l.add(statusbot.clabel(i).getText()); } catch (Exception e) { log.warn("Failed to get Status line message at index " + Integer.toString(i), e); } } return l; } }); }

Target:
public List<String> getStatusLineMessages() { return UIThreadRunnable.syncExec(new ListResult<String>() { @Override public List<String> run() { Control statusLine = null; IStatusLineManager s = null; int messageCount = 0; final List<String> l = new ArrayList<String>(); IWorkbenchPartSite site = partReference.getPart(false).getSite(); if (site instanceof IViewSite) { s = ((IViewSite) site).getActionBars().getStatusLineManager(); } else if (site instanceof IEditorSite) { s = ((IEditorSite) site).getActionBars().getStatusLineManager(); } while (s instanceof SubStatusLineManager) { s = (IStatusLineManager) ((SubStatusLineManager) s).getParent(); } if (s instanceof StatusLineManager) { statusLine = ((StatusLineManager) s).getControl(); } if (statusLine == null) return l; SWTBot statusbot = new SWTBot(statusLine); try { @SuppressWarnings("unchecked") List<? extends Widget> clabels = bot.widgets(allOf(widgetOfType(CLabel.class)), statusLine); messageCount = clabels.size(); } catch (Exception e) { log.warn("Failed to get CLable controls on Status line", e); } for (int i = 0; i < messageCount; i++) { try { l.add(statusbot.clabel(i).getText()); } catch (Exception e) { log.warn("Failed to get Status line message at index " + Integer.toString(i), e); } } return l; } }); }
Source:
public PGPSecretKey findSecretKey() throws IOException, PGPException { if (exists(USER_KEYBOX_PATH)) { PGPPublicKey publicKey = findPublicKeyInKeyBox(USER_KEYBOX_PATH); if (publicKey == null) { throw new PGPException( "no public-key with key or user id: " + signingKey); } PGPSecretKey secretKey = findSecretKeyForKeyBoxPublicKey(publicKey); if (secretKey != null) { return secretKey; } throw new PGPException( "unable to find associated secret key for public key: " + Long.toHexString(publicKey.getKeyID())); } else if (exists(USER_PGP_LEGACY_SECRING_FILE)) { PGPSecretKey secretKey = findSecretKeyInLegacySecring(signingKey, USER_PGP_LEGACY_SECRING_FILE); if (secretKey != null) { return secretKey; } throw new PGPException( "no matching secret key found in legacy secring.gpg for key or user id: " + signingKey); } throw new PGPException( "neither pubring.kbx nor secring.gpg files found"); }

Target:
public PGPSecretKey findSecretKey() throws IOException, PGPException { if (exists(USER_KEYBOX_PATH)) { PGPPublicKey publicKey = findPublicKeyInKeyBox(USER_KEYBOX_PATH); if (publicKey == null) { throw new PGPException(MessageFormat.format( JGitText.get().gpgNoPublicKeyFound, signingKey)); } PGPSecretKey secretKey = findSecretKeyForKeyBoxPublicKey(publicKey); if (secretKey != null) { return secretKey; } throw new PGPException(MessageFormat.format( JGitText.get().gpgNoSecretKeyForPublicKey, Long.toHexString(publicKey.getKeyID()))); } else if (exists(USER_PGP_LEGACY_SECRING_FILE)) { PGPSecretKey secretKey = findSecretKeyInLegacySecring(signingKey, USER_PGP_LEGACY_SECRING_FILE); if (secretKey != null) { return secretKey; } throw new PGPException(MessageFormat.format( JGitText.get().gpgNoKeyInLegacySecring, signingKey)); } throw new PGPException(JGitText.get().gpgNoKeyring); }
Source:
public void handleAction(ActionParameters params) throws ActionException { final int layerId = ConversionHelper.getInt(params.getRequiredParam(PARAM_LAYER_ID), -1); final OskariLayer layer = getLayer(layerId); final JSONObject response = getLayerFields(layer); ResponseHelper.writeResponse(params, response); }

Target:
public void handleAction(ActionParameters params) throws ActionException { final int layerId = params.getRequiredParamInt(PARAM_LAYER_ID); final User user = params.getUser(); final OskariLayer layer = getLayer(layerId, user); final JSONObject response = getLayerFields(layer); ResponseHelper.writeResponse(params, response); }
Source:
public void testInitializeWithConfiguration() throws IOException { final String tableName = getTestTableName("testInitializeWithConfiguration"); final Configuration conf = getTableCreationConfig(); conf.unset(S3GUARD_DDB_TABLE_NAME_KEY); String savedRegion = conf.get(S3GUARD_DDB_REGION_KEY, getFileSystem().getBucketLocation()); conf.unset(S3GUARD_DDB_REGION_KEY); try (DynamoDBMetadataStore ddbms = new DynamoDBMetadataStore()) { ddbms.initialize(conf, new S3Guard.TtlTimeProvider(conf)); fail("Should have failed because the table name is not set!"); } catch (IllegalArgumentException ignored) { } conf.set(S3GUARD_DDB_TABLE_NAME_KEY, tableName); try (DynamoDBMetadataStore ddbms = new DynamoDBMetadataStore()) { ddbms.initialize(conf, new S3Guard.TtlTimeProvider(conf)); fail("Should have failed because as the region is not set!"); } catch (IllegalArgumentException ignored) { } conf.set(S3GUARD_DDB_REGION_KEY, savedRegion); DynamoDBMetadataStore ddbms = new DynamoDBMetadataStore(); try { ddbms.initialize(conf, new S3Guard.TtlTimeProvider(conf)); Table table = verifyTableInitialized(tableName, ddbms.getDynamoDB()); verifyTableSse(conf, table.getDescription()); assertNotNull(ddbms.getTable()); assertEquals(tableName, ddbms.getTable().getTableName()); assertEquals("Unexpected key schema found!", keySchema(), ddbms.getTable().describe().getKeySchema()); } finally { destroy(ddbms); } }

Target:
public void testInitializeWithConfiguration() throws IOException { final String tableName = getTestTableName("testInitializeWithConfiguration"); final Configuration conf = getTableCreationConfig(); conf.unset(S3GUARD_DDB_TABLE_NAME_KEY); String savedRegion = conf.get(S3GUARD_DDB_REGION_KEY, getFileSystem().getBucketLocation()); conf.unset(S3GUARD_DDB_REGION_KEY); try (DynamoDBMetadataStore ddbms = new DynamoDBMetadataStore()) { ddbms.initialize(conf, new S3Guard.TtlTimeProvider(conf)); fail("Should have failed because the table name is not set!"); } catch (IllegalArgumentException ignored) { } conf.set(S3GUARD_DDB_TABLE_NAME_KEY, tableName); try (DynamoDBMetadataStore ddbms = new DynamoDBMetadataStore()) { ddbms.initialize(conf, new S3Guard.TtlTimeProvider(conf)); fail("Should have failed because as the region is not set!"); } catch (IllegalArgumentException ignored) { } conf.set(S3GUARD_DDB_REGION_KEY, savedRegion); doTestInitializeWithConfiguration(conf, tableName); conf.setBoolean(S3GUARD_DDB_TABLE_SSE_ENABLED, true); doTestInitializeWithConfiguration(conf, tableName); }
Source:
protected ClientConfiguration getClientConfiguration() { boolean proxyDisabled = Boolean.parseBoolean(Framework.getProperty(DISABLE_PROXY_PROPERTY)); String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST); String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT); String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN); String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD); int maxConnections = getIntProperty(CONNECTION_MAX_PROPERTY); int maxErrorRetry = getIntProperty(CONNECTION_RETRY_PROPERTY); int connectionTimeout = getIntProperty(CONNECTION_TIMEOUT_PROPERTY); int socketTimeout = getIntProperty(SOCKET_TIMEOUT_PROPERTY); ClientConfiguration clientConfiguration = new ClientConfiguration(); if (!proxyDisabled) { if (isNotBlank(proxyHost)) { clientConfiguration.setProxyHost(proxyHost); } if (isNotBlank(proxyPort)) { clientConfiguration.setProxyPort(Integer.parseInt(proxyPort)); } if (isNotBlank(proxyLogin)) { clientConfiguration.setProxyUsername(proxyLogin); } if (proxyPassword != null) { clientConfiguration.setProxyPassword(proxyPassword); } } if (maxConnections > 0) { clientConfiguration.setMaxConnections(maxConnections); } if (maxErrorRetry >= 0) { clientConfiguration.setMaxErrorRetry(maxErrorRetry); } if (connectionTimeout >= 0) { clientConfiguration.setConnectionTimeout(connectionTimeout); } if (socketTimeout >= 0) { clientConfiguration.setSocketTimeout(socketTimeout); } return clientConfiguration; }

Target:
protected ClientConfiguration getClientConfiguration() { boolean proxyDisabled = Framework.isBooleanPropertyTrue(DISABLE_PROXY_PROPERTY); String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST); String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT); String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN); String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD); int maxConnections = getIntProperty(CONNECTION_MAX_PROPERTY); int maxErrorRetry = getIntProperty(CONNECTION_RETRY_PROPERTY); int connectionTimeout = getIntProperty(CONNECTION_TIMEOUT_PROPERTY); int socketTimeout = getIntProperty(SOCKET_TIMEOUT_PROPERTY); ClientConfiguration clientConfiguration = new ClientConfiguration(); if (!proxyDisabled) { if (isNotBlank(proxyHost)) { clientConfiguration.setProxyHost(proxyHost); } if (isNotBlank(proxyPort)) { clientConfiguration.setProxyPort(Integer.parseInt(proxyPort)); } if (isNotBlank(proxyLogin)) { clientConfiguration.setProxyUsername(proxyLogin); } if (proxyPassword != null) { clientConfiguration.setProxyPassword(proxyPassword); } } if (maxConnections > 0) { clientConfiguration.setMaxConnections(maxConnections); } if (maxErrorRetry >= 0) { clientConfiguration.setMaxErrorRetry(maxErrorRetry); } if (connectionTimeout >= 0) { clientConfiguration.setConnectionTimeout(connectionTimeout); } if (socketTimeout >= 0) { clientConfiguration.setSocketTimeout(socketTimeout); } return clientConfiguration; }
Source:
private void printDebugMessage( String message ) { System.out.println( String.format( "%s %s %s", GdbPlugin.getDebugTime(), TIMEOUT_TRACE_IDENTIFIER, message ) ); if(GdbDebugOptions.DEBUG_COMMAND_TIMEOUTS) { if(!message.endsWith("\n")) { message = message + "\n"; } GdbDebugOptions.trace(message); } }

Target:
private void printDebugMessage( String message ) { if(GdbDebugOptions.DEBUG_COMMAND_TIMEOUTS) { if(!message.endsWith("\n")) { message = message + "\n"; } GdbDebugOptions.trace(String.format( "%s %s %s", GdbPlugin.getDebugTime(), TIMEOUT_TRACE_IDENTIFIER, message)); } }
Source:
public Long getPopulation(DateTime when) { Long pop = 0l; for(Planet planet : planets.values()) { if(null != planet.getPopulation(when)) { pop += planet.getPopulation(when); } } return pop; }

Target:
public long getPopulation(DateTime when) { long pop = 0l; for(Planet planet : planets.values()) { if(null != planet.getPopulation(when)) { pop += planet.getPopulation(when); } } return pop; }
Source:
public synchronized boolean addShardingKey(String realm, String shardingKey) { if (_leaderElection.isLeader()) { if (_zkClient.isClosed()) { throw new IllegalStateException("ZkClient is closed!"); } if (!_zkClient.exists(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + realm)) { if (!createZkRealm(realm)) { LOG.error( "Failed to add sharding key because ZkRealm creation failed! Namespace: {}, Realm: {}, Sharding key: {}", _namespace, realm, shardingKey); return false; } } ZNRecord znRecord; try { znRecord = _zkClient.readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + realm); } catch (Exception e) { LOG.error( "Failed to read the realm ZNRecord in addShardingKey()! Namespace: {}, Realm: {}, ShardingKey: {}", _namespace, realm, shardingKey, e); return false; } znRecord.setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, Collections.singletonList(shardingKey)); try { _zkClient .writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + realm, znRecord); } catch (Exception e) { LOG.error( "Failed to write the realm ZNRecord in addShardingKey()! Namespace: {}, Realm: {}, ShardingKey: {}", _namespace, realm, shardingKey, e); return false; } return true; } return true; }

Target:
public synchronized boolean addShardingKey(String realm, String shardingKey) { if (_leaderElection.isLeader()) { if (_zkClient.isClosed()) { throw new IllegalStateException("ZkClient is closed!"); } String realmPath = MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + realm; if (!_zkClient.exists(realmPath)) { if (!createZkRealm(realm)) { LOG.error( "Failed to add sharding key because ZkRealm creation failed! Namespace: {}, Realm: {}, Sharding key: {}", _namespace, realm, shardingKey); return false; } } ZNRecord znRecord; try { znRecord = _zkClient.readData(realmPath); } catch (Exception e) { LOG.error( "Failed to read the realm ZNRecord in addShardingKey()! Namespace: {}, Realm: {}, ShardingKey: {}", _namespace, realm, shardingKey, e); return false; } znRecord.setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, Collections.singletonList(shardingKey)); try { _zkClient.writeData(realmPath, znRecord); } catch (Exception e) { LOG.error( "Failed to write the realm ZNRecord in addShardingKey()! Namespace: {}, Realm: {}, ShardingKey: {}", _namespace, realm, shardingKey, e); return false; } return true; } return true; }
Source:
default TableStatisticsMetadata getInsertIntoTableStatisticsMetadata(ConnectorSession session, ConnectorTableHandle tableHandle) { return EMPTY_STATISTICS_METADATA; }

Target:
default TableStatisticsMetadata getInsertIntoTableStatisticsMetadata(ConnectorSession session, ConnectorTableHandle tableHandle) { return TableStatisticsMetadata.empty(); }
Source:
private TargetedSweepMetrics(long millis) { metricsManager = new MetricsManager(); metricsForStrategyMap = ImmutableMap.of( TableMetadataPersistence.SweepStrategy.CONSERVATIVE, new MetricsForStrategy(metricsManager, AtlasDbMetricNames.PREFIX_CONSERVATIVE, millis), TableMetadataPersistence.SweepStrategy.THOROUGH, new MetricsForStrategy(metricsManager, AtlasDbMetricNames.PREFIX_THOROUGH, millis)); }

Target:
private TargetedSweepMetrics(long millis) { MetricsManager metricsManager = new MetricsManager(); metricsForStrategyMap = ImmutableMap.of( TableMetadataPersistence.SweepStrategy.CONSERVATIVE, new MetricsForStrategy(metricsManager, AtlasDbMetricNames.TAG_CONSERVATIVE, millis), TableMetadataPersistence.SweepStrategy.THOROUGH, new MetricsForStrategy(metricsManager, AtlasDbMetricNames.TAG_THOROUGH, millis)); }
Source:
public void testPreferenceChangeCastedParameterPassed() { Preference preference = activity.findPreference(activity.getString(R.string.checkBoxWithCastPrefKey)); Boolean newValue = new Boolean(true); preference.getOnPreferenceChangeListener().onPreferenceChange(preference, newValue); assertThat(activity.preference).isSameAs(preference); assertThat(activity.newValue).isSameAs(newValue); }

Target:
public void testPreferenceChangeCastedParameterPassed() { Preference preference = activity.findPreference(activity.getString(R.string.checkBoxWithCastPrefKey)); preference.getOnPreferenceChangeListener().onPreferenceChange(preference, true); assertThat(activity.preference).isSameAs(preference); }
Source:
protected void logActivityFailure(HttpServletRequest req, Throwable e) { String url = HttpRequestHelper.getRequestedURL(req); StringBuilder message = new StringBuilder(100); message.append("<span class=\"color_red\">Servlet Action failure in ").append(actionName).append("<br>") .append(e.getMessage()).append("</span>"); ActivityLogEntry activityLogEntry = new ActivityLogEntry(actionName, actionDescription, null, message.toString(), url); log.log(Level.INFO, activityLogEntry.generateLogMessage()); log.severe(e.getMessage()); }

Target:
protected void logActivityFailure(HttpServletRequest req, Throwable e) { String url = HttpRequestHelper.getRequestedURL(req); String message = "<span class=\"color_red\">Servlet Action failure in " + actionName + "<br>" + e.getMessage() + "</span>"; ActivityLogEntry activityLogEntry = new ActivityLogEntry(actionName, actionDescription, null, message, url); log.log(Level.INFO, activityLogEntry.generateLogMessage()); log.severe(e.getMessage()); }
Source:
Offer createAndPlaceOffer(String currencyCode, String directionAsString, String priceAsString, boolean useMarketBasedPrice, double marketPriceMargin, long amountAsLong, long minAmountAsLong, double buyerSecurityDeposit, String paymentAccountId, Consumer<Offer> resultHandler) { String upperCaseCurrencyCode = currencyCode.toUpperCase(); String offerId = createOfferService.getRandomOfferId(); Direction direction = Direction.valueOf(directionAsString.toUpperCase()); Price price = Price.valueOf(upperCaseCurrencyCode, priceStringToLong(priceAsString, upperCaseCurrencyCode)); Coin amount = Coin.valueOf(amountAsLong); Coin minAmount = Coin.valueOf(minAmountAsLong); PaymentAccount paymentAccount = user.getPaymentAccount(paymentAccountId); Coin useDefaultTxFee = Coin.ZERO; Offer offer = createOfferService.createAndGetOffer(offerId, direction, upperCaseCurrencyCode, amount, minAmount, price, useDefaultTxFee, useMarketBasedPrice, exactMultiply(marketPriceMargin, 0.01), buyerSecurityDeposit, paymentAccount); boolean useSavingsWallet = true; placeOffer(offer, buyerSecurityDeposit, useSavingsWallet, transaction -> resultHandler.accept(offer)); return offer; }

Target:
void createAndPlaceOffer(String currencyCode, String directionAsString, String priceAsString, boolean useMarketBasedPrice, double marketPriceMargin, long amountAsLong, long minAmountAsLong, double buyerSecurityDeposit, String paymentAccountId, Consumer<Offer> resultHandler) { String upperCaseCurrencyCode = currencyCode.toUpperCase(); String offerId = createOfferService.getRandomOfferId(); Direction direction = Direction.valueOf(directionAsString.toUpperCase()); Price price = Price.valueOf(upperCaseCurrencyCode, priceStringToLong(priceAsString, upperCaseCurrencyCode)); Coin amount = Coin.valueOf(amountAsLong); Coin minAmount = Coin.valueOf(minAmountAsLong); PaymentAccount paymentAccount = user.getPaymentAccount(paymentAccountId); Coin useDefaultTxFee = Coin.ZERO; Offer offer = createOfferService.createAndGetOffer(offerId, direction, upperCaseCurrencyCode, amount, minAmount, price, useDefaultTxFee, useMarketBasedPrice, exactMultiply(marketPriceMargin, 0.01), buyerSecurityDeposit, paymentAccount); boolean useSavingsWallet = true; placeOffer(offer, buyerSecurityDeposit, useSavingsWallet, transaction -> resultHandler.accept(offer)); }
Source:
private void buildAssignedActiveTaskAndPartitionsList(final String consumer, final ClientState clientState, final List<TaskId> activeTasksForConsumer, final Map<TaskId, Set<TopicPartition>> partitionsForTask, final Set<TopicPartition> allOwnedPartitions, final List<TopicPartition> activePartitionsList, final List<TaskId> assignedActiveList) { final List<AssignedPartition> assignedPartitions = new ArrayList<>(); for (final TaskId taskId : activeTasksForConsumer) { for (final TopicPartition partition : partitionsForTask.get(taskId)) { final String oldOwner = clientState.ownedPartitions().get(partition); final boolean newPartitionForConsumer = oldOwner == null || !oldOwner.equals(consumer); if (newPartitionForConsumer && allOwnedPartitions.contains(partition)) { log.debug("Removing task from assignment until it is safely revoked", taskId); clientState.removeFromAssignment(taskId); break; } else { assignedPartitions.add(new AssignedPartition(taskId, partition)); } } } Collections.sort(assignedPartitions); for (final AssignedPartition partition : assignedPartitions) { assignedActiveList.add(partition.taskId); activePartitionsList.add(partition.partition); } }

Target:
private void buildAssignedActiveTaskAndPartitionsList(final String consumer, final ClientState clientState, final List<TaskId> activeTasksForConsumer, final Map<TaskId, Set<TopicPartition>> partitionsForTask, final Set<TopicPartition> allOwnedPartitions, final List<TopicPartition> activePartitionsList, final List<TaskId> assignedActiveList) { final List<AssignedPartition> assignedPartitions = new ArrayList<>(); for (final TaskId taskId : activeTasksForConsumer) { final List<AssignedPartition> assignedPartitionsForTask = new ArrayList<>(); for (final TopicPartition partition : partitionsForTask.get(taskId)) { final String oldOwner = clientState.ownedPartitions().get(partition); final boolean newPartitionForConsumer = oldOwner == null || !oldOwner.equals(consumer); if (newPartitionForConsumer && allOwnedPartitions.contains(partition)) { log.debug("Removing task from assignment until it is safely revoked", taskId); clientState.removeFromAssignment(taskId); assignedPartitionsForTask.clear(); break; } else { assignedPartitionsForTask.add(new AssignedPartition(taskId, partition)); } } assignedPartitions.addAll(assignedPartitionsForTask); } Collections.sort(assignedPartitions); for (final AssignedPartition partition : assignedPartitions) { assignedActiveList.add(partition.taskId); activePartitionsList.add(partition.partition); } }
Source:
public String getOnboardingSectionIdentifier() { if (onboardingType == OnboardingSectionType.CUSTUM) { return customOnboardingType; } return super.getOnboardingSectionIdentifier(); }

Target:
public String getOnboardingSectionIdentifier() { if (onboardingType == OnboardingSectionType.CUSTOM) { return customOnboardingType; } return super.getOnboardingSectionIdentifier(); }