auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void install(TierInstance tierInstance, ClaudiaData claudiaData, String envName,String vdc, ProductRelease productRelease, Set<Attribute> attributes, Task task, String callback) throws EntityNotFoundException { EnvironmentInstance environmentInstance = environmentInstanceManager.load(vdc,envName); try { ProductInstance productInstance = productInstanceManager.install(tierInstance, claudiaData, environmentInstance, productRelease, attributes); log.info("Product " + productRelease.getProduct() + '-' + productRelease.getVersion() + " installed successfully"); } catch (InvalidProductInstanceRequestException e) { String errorMsg = e.getMessage(); ProductInstance instance = getInstalledProduct(productRelease, tierInstance.getVM()); if (instance != null) { updateErrorTask(instance, task, errorMsg, e); } else { updateErrorTask(task, errorMsg, e); } } catch (Exception e) { String errorMsg = "The product " + productRelease.getProduct() + "-" + productRelease.getVersion() + " can not be installed in" + tierInstance.getVM(); ProductInstance instance = getInstalledProduct(productRelease, tierInstance.getVM()); if (instance != null) { updateErrorTask(instance, task, errorMsg, e); } else { updateErrorTask(task, errorMsg, e); } } finally { notifyTask(callback, task); } }

Target:
public void install(TierInstance tierInstance, ClaudiaData claudiaData, String envName, String vdc, ProductRelease productRelease, Set<Attribute> attributes, Task task, String callback) throws EntityNotFoundException { EnvironmentInstance environmentInstance = environmentInstanceManager.load(vdc, envName); try { ProductInstance productInstance = productInstanceManager.install(tierInstance, claudiaData, environmentInstance, productRelease); log.info("Product " + productRelease.getProduct() + '-' + productRelease.getVersion() + " installed successfully"); } catch (InvalidProductInstanceRequestException e) { String errorMsg = e.getMessage(); ProductInstance instance = getInstalledProduct(productRelease, tierInstance.getVM()); if (instance != null) { updateErrorTask(instance, task, errorMsg, e); } else { updateErrorTask(task, errorMsg, e); } } catch (Exception e) { String errorMsg = "The product " + productRelease.getProduct() + "-" + productRelease.getVersion() + " can not be installed in" + tierInstance.getVM(); ProductInstance instance = getInstalledProduct(productRelease, tierInstance.getVM()); if (instance != null) { updateErrorTask(instance, task, errorMsg, e); } else { updateErrorTask(task, errorMsg, e); } } finally { notifyTask(callback, task); } }
Source:
public DefaultInterpretedExpressionTargetSwitch(EStructuralFeature feature, IInterpretedExpressionTargetSwitch globalSwitch) { IInterpretedExpressionTargetSwitch theGlobalSwitch = Objects.firstNonNull(globalSwitch, this); this.firstRelevantContainerFinder = new FirstRelevantContainerDefaultFunction(); this.descriptionSwitch = new DescriptionInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.styleSwitch = new StyleInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.toolSwitch = new ToolInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.validationSwitch = new ValidationInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); }

Target:
public DefaultInterpretedExpressionTargetSwitch(EStructuralFeature feature, IInterpretedExpressionTargetSwitch globalSwitch) { IInterpretedExpressionTargetSwitch theGlobalSwitch = Objects.firstNonNull(globalSwitch, this); this.descriptionSwitch = new DescriptionInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.styleSwitch = new StyleInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.toolSwitch = new ToolInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.validationSwitch = new ValidationInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); }
Source:
public static String getStringFromBundleNoMissingCheck(String key, List<String> arguments, ResourceBundle bundle) throws MissingResourceException { if (key == null || key.isEmpty()) { return null; } String stringFromBundle = null; stringFromBundle = bundle.getString(key); logger.fine("string found: " + stringFromBundle); if (arguments != null) { Object[] argArray = new String[arguments.size()]; argArray = arguments.toArray(argArray); return MessageFormat.format(stringFromBundle, argArray); } else { return stringFromBundle; } }

Target:
private static String getStringFromBundleNoMissingCheck(String key, List<String> arguments, ResourceBundle bundle) throws MissingResourceException { if (key == null || key.isEmpty()) { return null; } String stringFromBundle = null; stringFromBundle = bundle.getString(key); logger.fine("string found: " + stringFromBundle); if (arguments != null) { Object[] argArray = new String[arguments.size()]; argArray = arguments.toArray(argArray); return MessageFormat.format(stringFromBundle, argArray); } else { return stringFromBundle; } }
Source:
OpenSslKeyMaterial chooseKeyMaterial(ByteBufAllocator allocator, String alias) throws Exception { OpenSslKeyMaterial material = cache.get(alias); if (material == null) { material = super.chooseKeyMaterial(allocator, alias); if (material == null) { return null; } if (cache.size() > maxCachedEntries) { return material; } OpenSslKeyMaterial old = cache.putIfAbsent(alias, material); if (old != null) { material.release(); material = old; } } return material.retain(); }

Target:
OpenSslKeyMaterial chooseKeyMaterial(ByteBufAllocator allocator, String alias) throws Exception { OpenSslKeyMaterial material = cache.get(alias); if (material == null) { material = super.chooseKeyMaterial(allocator, alias); if (material == null) { return null; } if (full) { return material; } if (cache.size() > maxCachedEntries) { full = true; return material; } OpenSslKeyMaterial old = cache.putIfAbsent(alias, material); if (old != null) { material.release(); material = old; } } return material.retain(); }
Source:
public ColumnSortList reloadColumnSortList() { ColumnSortList columnSortList = getListGrid().getColumnSortList(); GridPreferencesStore gridPreferencesStore = listTable.getGridPreferencesStore(); GridSortedColumnPreference gridSortedColumnPreference = gridPreferencesStore.getGridSortedColumnPreference(); if (gridPreferencesStore != null && gridSortedColumnPreference != null && columnSortList.size() <= 1) { Column<T, String> col = new Column<T, String>(new TextCell()) { @Override public String getValue(T domain) { return null; } }; col.setDataStoreName(gridSortedColumnPreference.getDataStoreName()); columnSortList.push(new ColumnSortList.ColumnSortInfo(col, gridSortedColumnPreference.isAscending())); } return columnSortList; }

Target:
public ColumnSortList reloadColumnSortList() { ColumnSortList columnSortList = getListGrid().getColumnSortList(); GridPreferencesStore gridPreferencesStore = getListGrid().getGridPreferencesStore(); if (gridPreferencesStore != null) { GridSortedColumnPreference gridSortedColumnPreference = gridPreferencesStore.getGridSortedColumnPreference(); if (gridSortedColumnPreference != null && columnSortList.size() <= 1) { Optional<ColumnMeta<T>> optional = getListGrid().getColumnMetaList().stream().filter( tColumnMeta -> tColumnMeta.getColumn().getDataStoreName().equals(gridSortedColumnPreference.getDataStoreName())) .findFirst(); if (optional.isPresent()) { Column col = optional.get().getColumn(); col.setDataStoreName(gridSortedColumnPreference.getDataStoreName()); columnSortList.push(new ColumnSortList.ColumnSortInfo(col, gridSortedColumnPreference.isAscending())); } } } return columnSortList; }
Source:
private JFreeChart createDebugEventGanttChart() { eventStatistics = new EventStatistics( InitializationManager.getInstance(WatchDogUtils.getProject()).getDebugEventManager(), selectedDebugInterval); final GanttCategoryDataset dataset = eventStatistics.createDebugEventGanttChartDataset(); final JFreeChart chart = ChartFactory.createGanttChart( "Debug Events During Selected Debug Interval", "Event", "Time", dataset, false, true, false); CategoryPlot plot = chart.getCategoryPlot(); ValueAxis axis = plot.getRangeAxis(); axis.setRangeWithMargins(selectedDebugInterval.getStart().getTime(), selectedDebugInterval.getEnd().getTime()); plot.setRenderer(new WatchDogGanttRenderer()); return chart; }

Target:
private JFreeChart createDebugEventGanttChart() { eventStatistics = new EventStatistics( InitializationManager.getInstance(WatchDogUtils.getProject()).getDebugEventManager(), selectedDebugInterval); GanttCategoryDataset dataset = eventStatistics.createDebugEventGanttChartDataset(); JFreeChart chart = ChartFactory.createGanttChart( "Debug Events During Selected Debug Interval", "Event", "Time", dataset, false, true, false); CategoryPlot plot = chart.getCategoryPlot(); ValueAxis axis = plot.getRangeAxis(); axis.setRangeWithMargins(selectedDebugInterval.getStart().getTime(), selectedDebugInterval.getEnd().getTime()); plot.setRenderer(new WatchDogGanttRenderer()); return chart; }
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ChunkImpl)) { return false; } ChunkImpl that = (ChunkImpl) obj; return Objects.equal(this.chunkPos, that.chunkPos); }

Target:
public boolean equals(Object obj) { return super.equals(obj); }
Source:
private static PackIndex writePack(FileRepository repo, Set<? extends ObjectId> want, Set<ObjectIdSet> excludeObjects) throws IOException { try (PackWriter pw = new PackWriter(repo)) { pw.setDeltaBaseAsOffset(true); pw.setReuseDeltaCommits(false); for (ObjectIdSet idx : excludeObjects) pw.excludeObjects(idx); pw.preparePack(NullProgressMonitor.INSTANCE, want, PackWriter.NONE); String id = pw.computeName().getName(); File packdir = new File(repo.getObjectsDirectory(), "pack"); File packFile = new File(packdir, "pack-" + id + ".pack"); FileOutputStream packOS = new FileOutputStream(packFile); pw.writePack(NullProgressMonitor.INSTANCE, NullProgressMonitor.INSTANCE, packOS); packOS.close(); File idxFile = new File(packdir, "pack-" + id + ".idx"); FileOutputStream idxOS = new FileOutputStream(idxFile); pw.writeIndex(idxOS); idxOS.close(); return PackIndex.open(idxFile); } }

Target:
private static PackIndex writePack(FileRepository repo, Set<? extends ObjectId> want, Set<ObjectIdSet> excludeObjects) throws IOException { try (PackWriter pw = new PackWriter(repo)) { pw.setDeltaBaseAsOffset(true); pw.setReuseDeltaCommits(false); for (ObjectIdSet idx : excludeObjects) pw.excludeObjects(idx); pw.preparePack(NullProgressMonitor.INSTANCE, want, NONE); String id = pw.computeName().getName(); File packdir = new File(repo.getObjectsDirectory(), "pack"); File packFile = new File(packdir, "pack-" + id + ".pack"); FileOutputStream packOS = new FileOutputStream(packFile); pw.writePack(NullProgressMonitor.INSTANCE, NullProgressMonitor.INSTANCE, packOS); packOS.close(); File idxFile = new File(packdir, "pack-" + id + ".idx"); FileOutputStream idxOS = new FileOutputStream(idxFile); pw.writeIndex(idxOS); idxOS.close(); return PackIndex.open(idxFile); } }
Source:
String getPaymentMethod(OpenOfferListItem item) { String result = ""; if (item != null) { Offer offer = item.getOffer(); checkNotNull(offer); checkNotNull(offer.getPaymentMethod()); String method = Res.get(offer.getPaymentMethod().getId() + "_SHORT"); String methodCountryCode = offer.getCountryCode(); if (methodCountryCode != null) result = method + " (" + methodCountryCode + ")"; else result = method; } return result; }

Target:
String getPaymentMethod(OpenOfferListItem item) { String result = ""; if (item != null) { Offer offer = item.getOffer(); checkNotNull(offer); checkNotNull(offer.getPaymentMethod()); result = offer.getPaymentMethodNameWithCountryCode(); } return result; }
Source:
public KeyValueScanner preStoreScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c, final Store store, final Scan scan, final NavigableSet<byte[]> targetCols, final KeyValueScanner s) throws IOException { if (storeFileScanDoesntNeedAlteration(store, scan)) { return s; } if (s!=null) { s.close(); } ScanInfo scanInfo = ScanInfoUtil.cloneScanInfoWithKeepDeletedCells(store, store.getScanInfo()); return ScanInfoUtil.createStoreScanner(store, scanInfo, scan, targetCols, c.getEnvironment().getRegion().getReadpoint(scan.getIsolationLevel())); }

Target:
public KeyValueScanner preStoreScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c, final Store store, final Scan scan, final NavigableSet<byte[]> targetCols, final KeyValueScanner s) throws IOException { if (storeFileScanDoesntNeedAlteration(store, scan)) { return s; } if (s != null) { s.close(); } ScanInfo scanInfo = ScanInfoUtil.cloneScanInfoWithKeepDeletedCells(store.getScanInfo()); return ScanInfoUtil.createStoreScanner(store, scanInfo, scan, targetCols, c.getEnvironment().getRegion().getReadpoint(scan.getIsolationLevel())); }
Source:
private static String getNextOffset(String currentOffset) { return currentOffset.equals(EventHubSystemConsumer.END_OF_STREAM) ? currentOffset : String.valueOf(Long.parseLong(currentOffset) + 1); }

Target:
private String getNextOffset(String currentOffset) { return currentOffset.equals(EventHubSystemConsumer.END_OF_STREAM) ? currentOffset : String.valueOf(Long.parseLong(currentOffset) + 1); }
Source:
void shouldFailSelectOneAuthorUsingMapperClassWithTwoResultHandlers() { Configuration configuration = new Configuration(sqlMapper.getConfiguration().getEnvironment()); configuration.addMapper(AuthorMapperWithMultipleHandlers.class); SqlSessionFactory sqlMapperWithMultipleHandlers = new DefaultSqlSessionFactory(configuration); try (SqlSession sqlSession = sqlMapperWithMultipleHandlers.openSession()) { DefaultResultHandler handler1 = new DefaultResultHandler(); DefaultResultHandler handler2 = new DefaultResultHandler(); AuthorMapperWithMultipleHandlers mapper = sqlSession.getMapper(AuthorMapperWithMultipleHandlers.class); Assertions.assertThrows(BindingException.class, () -> mapper.selectAuthor(101, handler1, handler2)); } }

Target:
void shouldFailSelectOneAuthorUsingMapperClassWithTwoResultHandlers() { Configuration configuration = new Configuration(sqlMapper.getConfiguration().getEnvironment()); configuration.addMapper(AuthorMapperWithMultipleHandlers.class); SqlSessionFactory sqlMapperWithMultipleHandlers = new DefaultSqlSessionFactory(configuration); try (SqlSession sqlSession = sqlMapperWithMultipleHandlers.openSession();) { DefaultResultHandler handler1 = new DefaultResultHandler(); DefaultResultHandler handler2 = new DefaultResultHandler(); AuthorMapperWithMultipleHandlers mapper = sqlSession.getMapper(AuthorMapperWithMultipleHandlers.class); Assertions.assertThrows(BindingException.class, () -> mapper.selectAuthor(101, handler1, handler2)); } }
Source:
static IQueryable<IInstallableUnit> getQueryableMetadata(URI[] repos, IProgressMonitor monitor) throws CoreException { IMetadataRepositoryManager manager = getRepoManager(); if (repos == null) { repos = manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); } int repoCount = repos.length; SubMonitor subMonitor = SubMonitor.convert(monitor, repoCount * 10); List<IMetadataRepository> result = new ArrayList<IMetadataRepository>(repoCount); MultiStatus repoStatus = new MultiStatus(PDECore.PLUGIN_ID, 0, Messages.IUBundleContainer_ProblemsLoadingRepositories, null); for (int i = 0; i < repoCount; ++i) { try { result.add(manager.loadRepository(repos[i], subMonitor.newChild(10))); } catch (ProvisionException e) { repoStatus.add(e.getStatus()); } } if (result.size() != repos.length) { throw new CoreException(repoStatus); } if (result.size() == 1) { return result.get(0); } return QueryUtil.compoundQueryable(result); }

Target:
static IQueryable<IInstallableUnit> getQueryableMetadata(URI[] repos, IProgressMonitor monitor) throws CoreException { IMetadataRepositoryManager manager = getRepoManager(); if (repos == null) { repos = manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL); } int repoCount = repos.length; SubMonitor subMonitor = SubMonitor.convert(monitor, repoCount); List<IMetadataRepository> result = new ArrayList<IMetadataRepository>(repoCount); MultiStatus repoStatus = new MultiStatus(PDECore.PLUGIN_ID, 0, Messages.IUBundleContainer_ProblemsLoadingRepositories, null); for (int i = 0; i < repoCount; ++i) { try { result.add(manager.loadRepository(repos[i], subMonitor.newChild(1))); } catch (ProvisionException e) { repoStatus.add(e.getStatus()); } } if (result.size() != repos.length) { throw new CoreException(repoStatus); } if (result.size() == 1) { return result.get(0); } return QueryUtil.compoundQueryable(result); }
Source:
protected void closeOutputStreams() throws IOException { if (outputHolder != null) { outputHolder.getStream().close(); if (outputHolder.getWrappedStream() != null) { outputHolder.getWrappedStream().close(); } outputHolder = null; } }

Target:
protected void closeOutputStreams() throws IOException { if (outputHolder != null) { outputHolder.close(); outputHolder = null; } }
Source:
protected Map<Event, Position> analyzePosition(Position position) { if (Context.getIdentityManager().getById(position.getDeviceId()) == null || !Context.getIdentityManager().isLatestPosition(position)) { return null; } Position lastPosition = Context.getIdentityManager().getLastPosition(position.getDeviceId()); if (lastPosition == null) { return null; } Map<Event, Position> events = new HashMap<>(); for (long maintenanceId : Context.getMaintenancesManager().getAllDeviceItems(position.getDeviceId())) { Maintenance maintenance = Context.getMaintenancesManager().getById(maintenanceId); if (maintenance.getLapse() != 0) { double oldValue = lastPosition.getDouble(maintenance.getType()); double newValue = position.getDouble(maintenance.getType()); if (oldValue != 0.0 && newValue != 0.0 && (long) ((oldValue - maintenance.getStart()) / maintenance.getLapse()) < (long) ((newValue - maintenance.getStart()) / maintenance.getLapse())) { Event event = new Event(Event.TYPE_MAINTENANCE, position.getDeviceId(), position.getId()); event.setMaintenanceId(maintenanceId); event.set(maintenance.getType(), newValue); events.put(event, position); } } } return events; }

Target:
protected Map<Event, Position> analyzePosition(Position position) { if (Context.getIdentityManager().getById(position.getDeviceId()) == null || !Context.getIdentityManager().isLatestPosition(position)) { return null; } Position lastPosition = Context.getIdentityManager().getLastPosition(position.getDeviceId()); if (lastPosition == null) { return null; } Map<Event, Position> events = new HashMap<>(); for (long maintenanceId : Context.getMaintenancesManager().getAllDeviceItems(position.getDeviceId())) { Maintenance maintenance = Context.getMaintenancesManager().getById(maintenanceId); if (maintenance.getPeriod() != 0) { double oldValue = lastPosition.getDouble(maintenance.getType()); double newValue = position.getDouble(maintenance.getType()); if (oldValue != 0.0 && newValue != 0.0 && (long) ((oldValue - maintenance.getStart()) / maintenance.getPeriod()) < (long) ((newValue - maintenance.getStart()) / maintenance.getPeriod())) { Event event = new Event(Event.TYPE_MAINTENANCE, position.getDeviceId(), position.getId()); event.setMaintenanceId(maintenanceId); event.set(maintenance.getType(), newValue); events.put(event, position); } } } return events; }
Source:
public LocalDocument insertLocalDocument(final String docId, final DocumentBody body) throws DocumentException { Preconditions.checkState(this.isOpen(), "Database is closed"); CouchUtils.validateDocumentId(docId); Preconditions.checkNotNull(body, "Input document body can not be null"); try { return queue.submitTransaction(new SQLQueueCallable<LocalDocument>() { @Override public LocalDocument call(SQLDatabase db) throws Exception { ContentValues values = new ContentValues(); values.put("docid", docId); values.put("json", body.asBytes()); long rowId = db.insertWithOnConflict("localdocs", values, SQLDatabase .CONFLICT_REPLACE); if (rowId < 0) { throw new DocumentException("Failed to insert local document"); } else { logger.finer(String.format("Local doc inserted: %d , %s", rowId, docId)); } return doGetLocalDocument(db, docId); } }).get(); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Failed to create local document", e); } catch (ExecutionException e) { logger.log(Level.SEVERE,"Failed to create local document",e); throw new DocumentException("Cannot insert new local document",e); } return null; }

Target:
public LocalDocument insertLocalDocument(final String docId, final DocumentBody body) throws DocumentException { Preconditions.checkState(this.isOpen(), "Database is closed"); CouchUtils.validateDocumentId(docId); Preconditions.checkNotNull(body, "Input document body can not be null"); try { return queue.submitTransaction(new SQLQueueCallable<LocalDocument>() { @Override public LocalDocument call(SQLDatabase db) throws Exception { ContentValues values = new ContentValues(); values.put("docid", docId); values.put("json", body.asBytes()); long rowId = db.insertWithOnConflict("localdocs", values, SQLDatabase .CONFLICT_REPLACE); if (rowId < 0) { throw new DocumentException("Failed to insert local document"); } else { logger.finer(String.format("Local doc inserted: %d , %s", rowId, docId)); } return doGetLocalDocument(db, docId); } }).get(); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Failed to insert local document", e); } catch (ExecutionException e) { logger.log(Level.SEVERE,"Failed to insert local document",e); throw new DocumentException("Cannot insert local document",e); } return null; }
Source:
protected SmppSplitter createSplitter(Message message) { SmppSplitter splitter; if (message.getHeaders().containsKey(SmppConstants.DATA_SPLITTER)){ splitter = message.getHeader(SmppConstants.DATA_SPLITTER, SmppSplitter.class); if (null != splitter){ return splitter; } logger.warn("Invalid splitter given. Must be instance of SmppSplitter"); } Alphabet alphabet = determineAlphabet(message); String body = message.getBody(String.class); if (SmppUtils.is8Bit(alphabet)) { splitter = new Smpp8BitSplitter(body.length()); } else if (alphabet == Alphabet.ALPHA_UCS2) { splitter = new SmppUcs2Splitter(body.length()); } else { splitter = new SmppDefaultSplitter(body.length()); } return splitter; }

Target:
protected SmppSplitter createSplitter(Message message) throws SmppException { SmppSplitter splitter; if (message.getHeaders().containsKey(SmppConstants.DATA_SPLITTER)) { splitter = message.getHeader(SmppConstants.DATA_SPLITTER, SmppSplitter.class); if (null != splitter) { return splitter; } throw new SmppException("Invalid splitter given. Must be instance of SmppSplitter"); } Alphabet alphabet = determineAlphabet(message); String body = message.getBody(String.class); if (SmppUtils.is8Bit(alphabet)) { splitter = new Smpp8BitSplitter(body.length()); } else if (alphabet == Alphabet.ALPHA_UCS2) { splitter = new SmppUcs2Splitter(body.length()); } else { splitter = new SmppDefaultSplitter(body.length()); } return splitter; }
Source:
protected boolean isFinished() { return false; }

Target:
protected boolean isFinished() { return true; }
Source:
public static TimelineFeedback create( @JsonProperty("date_of_night") final String dateOfNight, @JsonProperty("old_time_of_event") final String oldTimeOfEvent, @JsonProperty("new_time_of_event") final String newTimeOfEvent, @JsonProperty("event_type") final String eventTypeString) { final DateTime date = DateTime.parse(dateOfNight); final DateTime realDate = new DateTime(date.getMillis(), DateTimeZone.UTC).withTimeAtStartOfDay(); final Event.Type eventType = Event.Type.fromString(eventTypeString); return new TimelineFeedback(0L, realDate, oldTimeOfEvent, newTimeOfEvent, eventType, Optional.<Long>absent(),Optional.<Long>absent()); }

Target:
public static TimelineFeedback create( @JsonProperty("date_of_night") final String dateOfNight, @JsonProperty("old_time_of_event") final String oldTimeOfEvent, @JsonProperty("new_time_of_event") final String newTimeOfEvent, @JsonProperty("event_type") final String eventTypeString) { final DateTime date = DateTime.parse(dateOfNight); final DateTime realDate = new DateTime(date.getMillis(), DateTimeZone.UTC).withTimeAtStartOfDay(); final Event.Type eventType = Event.Type.fromString(eventTypeString); return new TimelineFeedback(realDate, oldTimeOfEvent, newTimeOfEvent, eventType, Optional.<Long>absent(),Optional.<Long>absent(), null); }
Source:
private static void updateStepMessage(CommandBase<?> cmd, Guid vdsForExecution) { StepEnum stepEnum = null; try { stepEnum = StepEnum.valueOf(getStepWithHostname(cmd)); } catch (IllegalArgumentException e) { log.debug("No StepEnum found for " + getStepWithHostname(cmd)); return; } Step step = cmd.getExecutionContext().getStep(); Map<String, String> jobProperties = cmd.getJobMessageProperties(); jobProperties.put(VdcObjectType.VDS.name().toLowerCase(), getVdsDao().get(vdsForExecution).getName()); step.setDescription(ExecutionMessageDirector.resolveStepMessage(stepEnum, jobProperties)); getStepDao().update(step); cmd.addCustomValues(jobProperties); new AuditLogDirector().log(cmd, AuditLogType.USER_MERGE_SNAPSHOT_ON_HOST); }

Target:
private static void updateStepMessage(CommandBase<?> cmd, Guid vdsForExecution) { StepEnum stepEnum = null; try { stepEnum = StepEnum.valueOf(getStepWithHostname(cmd)); } catch (IllegalArgumentException e) { log.debug("No StepEnum found for " + getStepWithHostname(cmd)); return; } Step step = cmd.getExecutionContext().getStep(); Map<String, String> jobProperties = cmd.getJobMessageProperties(); jobProperties.put(VdcObjectType.VDS.name().toLowerCase(), getVdsDao().get(vdsForExecution).getName()); step.setDescription(ExecutionMessageDirector.resolveStepMessage(stepEnum, jobProperties)); getStepDao().update(step); AuditLogType logType = null; try { logType = AuditLogType.valueOf(getAuditLogType(cmd)); } catch (IllegalArgumentException e) { log.debug("No AuditLogType found for " + getAuditLogType(cmd)); return; } jobProperties.entrySet().stream().forEach(entry -> cmd.addCustomValue(entry.getKey(), entry.getValue())); Injector.get(AuditLogDirector.class).log(cmd, logType); }
Source:
private boolean progressGraph() throws IOException { finishedNodes.swap(); HashSet<ExecutableNode> nodesToCheck = new HashSet<ExecutableNode>(); for (ExecutableNode node : finishedNodes) { Set<String> outNodeIds = node.getOutNodes(); ExecutableFlowBase parentFlow = node.getParentFlow(); if (node.getStatus() == Status.FAILED || (node.getStatus() == Status.KILLED && node.isKilledBySLA())) { if (!retryJobIfPossible(node)) { propagateStatus(node.getParentFlow(), Status.FAILED_FINISHING); if (failureAction == FailureAction.CANCEL_ALL) { this.kill(); } this.flowFailed = true; } else { nodesToCheck.add(node); continue; } } if (outNodeIds.isEmpty()) { finalizeFlow(parentFlow); finishExecutableNode(parentFlow); if (!(parentFlow instanceof ExecutableFlow)) { outNodeIds = parentFlow.getOutNodes(); parentFlow = parentFlow.getParentFlow(); } } for (String nodeId : outNodeIds) { ExecutableNode outNode = parentFlow.getExecutableNode(nodeId); nodesToCheck.add(outNode); } } boolean jobsRun = false; for (ExecutableNode node : nodesToCheck) { if (Status.isStatusFinished(node.getStatus()) || Status.isStatusRunning(node.getStatus())) { continue; } jobsRun |= runReadyJob(node); } if (jobsRun || finishedNodes.getSize() > 0) { updateFlow(); return true; } return false; }

Target:
private boolean progressGraph() throws IOException { this.finishedNodes.swap(); final HashSet<ExecutableNode> nodesToCheck = new HashSet<>(); for (final ExecutableNode node : this.finishedNodes) { Set<String> outNodeIds = node.getOutNodes(); ExecutableFlowBase parentFlow = node.getParentFlow(); if (node.getStatus() == Status.FAILED || (node.getStatus() == Status.KILLED && node.isKilledBySLA())) { if (!retryJobIfPossible(node)) { propagateStatus(node.getParentFlow(), Status.FAILED_FINISHING); if (this.failureAction == FailureAction.CANCEL_ALL) { this.kill(); } this.flowFailed = true; } else { nodesToCheck.add(node); continue; } } if (outNodeIds.isEmpty()) { finalizeFlow(parentFlow); finishExecutableNode(parentFlow); if (!(parentFlow instanceof ExecutableFlow)) { outNodeIds = parentFlow.getOutNodes(); parentFlow = parentFlow.getParentFlow(); } } for (final String nodeId : outNodeIds) { final ExecutableNode outNode = parentFlow.getExecutableNode(nodeId); nodesToCheck.add(outNode); } } boolean jobsRun = false; for (final ExecutableNode node : nodesToCheck) { if (notReadyToRun(node.getStatus())) { continue; } jobsRun |= runReadyJob(node); } if (jobsRun || this.finishedNodes.getSize() > 0) { updateFlow(); return true; } return false; }
Source:
private void performPrimaryAction() { switch (getPrimaryAction()) { case PUBLISH_NOW: case UPDATE: case SCHEDULE: showPrepublishingNudgeBottomSheet(); return; case SUBMIT_FOR_REVIEW: case SAVE: uploadPost(false); break; } }

Target:
private void performPrimaryAction() { switch (getPrimaryAction()) { case PUBLISH_NOW: case UPDATE: case SCHEDULE: mAnalyticsTrackerWrapper.track(Stat.EDITOR_POST_PUBLISH_TAPPED); showPrepublishingNudgeBottomSheet(); return; case SUBMIT_FOR_REVIEW: case SAVE: uploadPost(false); break; } }
Source:
protected io.gravitee.definition.model.endpoint.HttpEndpoint resolve(io.gravitee.definition.model.endpoint.HttpEndpoint endpoint) { endpoint.setTarget(convert(endpoint.getTarget())); if (endpoint.getHttpProxy() != null) { endpoint.getHttpProxy().setHost(convert(endpoint.getHttpProxy().getHost())); endpoint.getHttpProxy().setUsername(convert(endpoint.getHttpProxy().getUsername())); endpoint.getHttpProxy().setPassword(convert(endpoint.getHttpProxy().getPassword())); } if (endpoint.getHeaders() != null && endpoint.getHeaders().isEmpty()) { endpoint.getHeaders().replaceAll((key, value) -> convert(value)); } return endpoint; }

Target:
protected io.gravitee.definition.model.endpoint.HttpEndpoint resolve(io.gravitee.definition.model.endpoint.HttpEndpoint endpoint) { endpoint.setTarget(convert(endpoint.getTarget())); if (endpoint.getHttpProxy() != null) { endpoint.getHttpProxy().setHost(convert(endpoint.getHttpProxy().getHost())); endpoint.getHttpProxy().setUsername(convert(endpoint.getHttpProxy().getUsername())); endpoint.getHttpProxy().setPassword(convert(endpoint.getHttpProxy().getPassword())); } if (endpoint.getHeaders() != null && !endpoint.getHeaders().isEmpty()) { endpoint.getHeaders().replaceAll((key, value) -> convert(value)); } return endpoint; }
Source:
public void writeObject(ObjectOutput output, GroupAddedEvent obj) throws IOException { output.writeByte(VERSION_1); MarshallUtil.marshallString(obj.groupId, output); MarshallUtil.marshallString(obj.realmId, output); MarshallUtil.marshallString(obj.parentId, output); }

Target:
public void writeObject(ObjectOutput output, GroupAddedEvent obj) throws IOException { output.writeByte(VERSION_2); MarshallUtil.marshallString(obj.groupId, output); MarshallUtil.marshallString(obj.realmId, output); MarshallUtil.marshallString(obj.parentId, output); }
Source:
public void testSinkTaskPut() throws Exception { setUp(); HdfsSinkTask task = new HdfsSinkTask(); String key = "key"; Schema schema = createSchema(); Struct record = createRecord(schema); Collection<SinkRecord> sinkRecords = new ArrayList<>(); for (TopicPartition tp : context.assignment()) { for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(tp.topic(), tp.partition(), Schema.STRING_SCHEMA, key, schema, record, offset); sinkRecords.add(sinkRecord); } } properties.remove(StorageCommonConfig.STORE_URL_CONFIG); task.initialize(context); task.start(properties); task.put(sinkRecords); task.stop(); AvroData avroData = task.getAvroData(); long[] validOffsets = {-1, 2, 5}; for (TopicPartition tp : context.assignment()) { String directory = tp.topic() + "/" + "partition=" + String.valueOf(tp.partition()); for (int j = 1; j < validOffsets.length; ++j) { long startOffset = validOffsets[j - 1] + 1; long endOffset = validOffsets[j]; Path path = new Path(FileUtils.committedFileName(url, topicsDir, directory, tp, startOffset, endOffset, extension, ZERO_PAD_FMT)); Collection<Object> records = schemaFileReader.readData(connectorConfig.getHadoopConfiguration(), path); long size = endOffset - startOffset + 1; assertEquals(records.size(), size); for (Object avroRecord : records) { assertEquals(avroRecord, avroData.fromConnectData(schema, record)); } } } }

Target:
public void testSinkTaskPut() throws Exception { setUp(); HdfsSinkTask task = new HdfsSinkTask(); String key = "key"; Schema schema = createSchema(); Struct record = createRecord(schema); Collection<SinkRecord> sinkRecords = new ArrayList<>(); for (TopicPartition tp : context.assignment()) { for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(tp.topic(), tp.partition(), Schema.STRING_SCHEMA, key, schema, record, offset); sinkRecords.add(sinkRecord); } } task.initialize(context); task.start(properties); task.put(sinkRecords); task.stop(); AvroData avroData = task.getAvroData(); long[] validOffsets = {-1, 2, 5}; for (TopicPartition tp : context.assignment()) { String directory = tp.topic() + "/" + "partition=" + String.valueOf(tp.partition()); for (int j = 1; j < validOffsets.length; ++j) { long startOffset = validOffsets[j - 1] + 1; long endOffset = validOffsets[j]; Path path = new Path(FileUtils.committedFileName(url, topicsDir, directory, tp, startOffset, endOffset, extension, ZERO_PAD_FMT)); Collection<Object> records = schemaFileReader.readData(connectorConfig.getHadoopConfiguration(), path); long size = endOffset - startOffset + 1; assertEquals(records.size(), size); for (Object avroRecord : records) { assertEquals(avroRecord, avroData.fromConnectData(schema, record)); } } } }
Source:
private void refreshIndex( WritableFulltext index ) { try { index.maybeRefreshBlocking(); } catch ( IOException e ) { e.printStackTrace(); } }

Target:
private void refreshIndex( WritableFulltext index ) { try { index.maybeRefreshBlocking(); } catch ( IOException e ) { log.error( "Failed to refresh fulltext after updates", e ); } }
Source:
protected List<File> showFileDialog() { int style = SWT.NONE; if (getScoutFileChooser().isTypeLoad()) { style |= SWT.OPEN; } else { style |= SWT.SAVE; } if (getScoutFileChooser().isMultiSelect()) { style |= SWT.MULTI; } String[] extensions = new String[]{"*.*"}; if (getScoutFileChooser().getFileExtensions() != null) { List<String> extensionList = new ArrayList<String>(); for (String ext : getScoutFileChooser().getFileExtensions()) { extensionList.add("*." + ext); } String allExtensions = StringUtility.join(";", extensionList.toArray(new String[extensionList.size()])); extensionList.add(0, allExtensions); extensions = extensionList.toArray(new String[extensionList.size()]); } FileDialog dialog = new FileDialog(getParentShell(), style); dialog.setFilterExtensions(extensions); if (getScoutFileChooser().getDirectory() != null) { dialog.setFilterPath(getScoutFileChooser().getDirectory().getAbsolutePath()); } if (getScoutFileChooser().getFileName() != null) { dialog.setFileName(getScoutFileChooser().getFileName()); } dialog.open(); String filterPath = dialog.getFilterPath(); String[] fileNames = dialog.getFileNames(); List<File> result = new ArrayList<File>(); for (String fileName : fileNames) { result.add(new Path(filterPath).append(fileName).toFile()); } return result; }

Target:
protected List<File> showFileDialog() { int style = SWT.NONE; if (getScoutFileChooser().isTypeLoad()) { style |= SWT.OPEN; } else { style |= SWT.SAVE; } if (getScoutFileChooser().isMultiSelect()) { style |= SWT.MULTI; } String[] extensions = new String[]{"*.*"}; if (getScoutFileChooser().getFileExtensions() != null) { List<String> extensionList = new ArrayList<String>(); for (String ext : getScoutFileChooser().getFileExtensions()) { extensionList.add("*." + ext); } String allExtensions = StringUtility.join(";", extensionList); extensionList.add(0, allExtensions); extensions = extensionList.toArray(new String[extensionList.size()]); } FileDialog dialog = new FileDialog(getParentShell(), style); dialog.setFilterExtensions(extensions); if (getScoutFileChooser().getDirectory() != null) { dialog.setFilterPath(getScoutFileChooser().getDirectory().getAbsolutePath()); } if (getScoutFileChooser().getFileName() != null) { dialog.setFileName(getScoutFileChooser().getFileName()); } dialog.open(); String filterPath = dialog.getFilterPath(); String[] fileNames = dialog.getFileNames(); List<File> result = new ArrayList<File>(); for (String fileName : fileNames) { result.add(new Path(filterPath).append(fileName).toFile()); } return result; }
Source:
public static NewSessionPayload create(Capabilities caps) throws IOException { boolean forceMobileJSONWP = ofNullable(caps.getCapability(FORCE_MJSONWP)) .map(o -> { if (Boolean.class.isAssignableFrom(o.getClass())) { return Boolean.class.cast(o); } return false; }).orElse(false); HashMap<String, ?> capabilityMap = new HashMap<>(caps.asMap()); capabilityMap.remove(FORCE_MJSONWP); return create(ImmutableMap.of("desiredCapabilities", capabilityMap), forceMobileJSONWP); }

Target:
public static NewSessionPayload create(Capabilities caps) throws IOException { boolean forceMobileJSONWP = ofNullable(caps.getCapability(FORCE_MJSONWP)) .map(o -> Boolean.class.isAssignableFrom(o.getClass()) && Boolean.class.cast(o)) .orElse(false); HashMap<String, ?> capabilityMap = new HashMap<>(caps.asMap()); capabilityMap.remove(FORCE_MJSONWP); Map<String, ?> source = of(DESIRED_CAPABILITIES, capabilityMap); String json = new Json().toJson(source); return new NewSessionPayload(new StringReader(json), forceMobileJSONWP); }
Source:
public void testDiagnosticRedrawingCalls() throws CoreException { IFile file = TestUtils.createUniqueTestFile(project, "Diagnostic Other Text\nDiagnostic Other Text"); IWorkspace workspace = ResourcesPlugin.getWorkspace(); IResourceChangeListener listener = new IResourceChangeListener() { @Override public void resourceChanged(IResourceChangeEvent event) { IResourceDelta delta = event.getDelta(); if (delta == null) return; IResourceDelta[] childDeltas = delta.getAffectedChildren(); if (childDeltas.length == 0) return; childDeltas = childDeltas[0].getAffectedChildren(); if (childDeltas.length == 0 || childDeltas[0].getMarkerDeltas().length == 0) return; resourceChanges++; } }; workspace.addResourceChangeListener(listener); final Range range1 = new Range(new Position(0, 0), new Position(0, 10)); final Range range2 = new Range(new Position(1, 0), new Position(1, 10)); final Diagnostic pos1Info1 = createDiagnostic("1", "message1", range1, DiagnosticSeverity.Error, "source1"); final Diagnostic pos1Info2 = createDiagnostic("2", "message2", range1, DiagnosticSeverity.Error, "source2"); final Diagnostic pos2Info2 = createDiagnostic("2", "message2", range2, DiagnosticSeverity.Error, "source2"); try { confirmResourceChanges(file, pos1Info1, 2); confirmResourceChanges(file, pos1Info2, 1); confirmResourceChanges(file, pos2Info2, 1); confirmResourceChanges(file, pos1Info1, 1); confirmResourceChanges(file, pos1Info1, 0); } finally { workspace.removeResourceChangeListener(listener); } }

Target:
public void testDiagnosticRedrawingCalls() throws CoreException { IFile file = TestUtils.createUniqueTestFile(project, "Diagnostic Other Text\nDiagnostic Other Text"); final Range range1 = new Range(new Position(0, 0), new Position(0, 10)); final Range range2 = new Range(new Position(1, 0), new Position(1, 10)); final Diagnostic pos1Info1 = createDiagnostic("1", "message1", range1, DiagnosticSeverity.Error, "source1"); final Diagnostic pos1Info2 = createDiagnostic("2", "message2", range1, DiagnosticSeverity.Error, "source2"); final Diagnostic pos2Info2 = createDiagnostic("2", "message2", range2, DiagnosticSeverity.Error, "source2"); confirmResourceChanges(file, pos1Info1, 2); confirmResourceChanges(file, pos1Info2, 1); confirmResourceChanges(file, pos2Info2, 1); confirmResourceChanges(file, pos1Info1, 1); confirmResourceChanges(file, pos1Info1, 0); }
Source:
protected void onPostExecute(Boolean result) { String message; String title = "Nominating for Deletion"; if (result){ title += ": Success"; message = "Successfully nominated " + media.getDisplayTitle() + " deletion."; } else { title += ": Failed"; message = "Could not request deletion."; } notificationBuilder.setDefaults(DEFAULT_ALL) .setContentTitle(title) .setStyle(new NotificationCompat.BigTextStyle() .bigText(message)) .setSmallIcon(R.drawable.ic_launcher) .setProgress(0,0,false) .setOngoing(false) .setPriority(PRIORITY_HIGH); String urlForDelete=baseUrl+media.getFilename(); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlForDelete)); PendingIntent pendingIntent = PendingIntent.getActivity(context , 1 , browserIntent , PendingIntent.FLAG_UPDATE_CURRENT); notificationBuilder.setContentIntent(pendingIntent); notificationManager.notify(NOTIFICATION_DELETE, notificationBuilder.build()); }

Target:
protected void onPostExecute(Boolean result) { String message; String title = "Nominating for Deletion"; if (result){ title += ": Success"; message = "Successfully nominated " + media.getDisplayTitle() + " deletion."; } else { title += ": Failed"; message = "Could not request deletion."; } notificationBuilder.setDefaults(DEFAULT_ALL) .setContentTitle(title) .setStyle(new NotificationCompat.BigTextStyle() .bigText(message)) .setSmallIcon(R.drawable.ic_launcher) .setProgress(0,0,false) .setOngoing(false) .setPriority(PRIORITY_HIGH); String urlForDelete = BuildConfig.COMMONS_URL + "/wiki/Commons:Deletion_requests/File:" + media.getFilename(); Intent browserIntent = new Intent(Intent.ACTION_VIEW , Uri.parse(urlForDelete)); PendingIntent pendingIntent = PendingIntent.getActivity(context , 1 , browserIntent , PendingIntent.FLAG_UPDATE_CURRENT); notificationBuilder.setContentIntent(pendingIntent); notificationManager.notify(NOTIFICATION_DELETE, notificationBuilder.build()); }
Source:
public void processBody(final ParserContext context) { String documentBody = context.getBody(); try (InputStream stream = new ByteArrayInputStream(documentBody.getBytes(StandardCharsets.UTF_8))){ TexyRestService texyService = new TexyRestService(new URL("http://localhost:8022/TexyService.rest.php")); try (InputStream xhtmlIS = texyService.convertTexyToXhtml(stream)){ java.util.Scanner s = new java.util.Scanner(xhtmlIS, StandardCharsets.UTF_8.name()).useDelimiter("\\A"); String xhtmlString = s.hasNext() ? s.next() : ""; context.setBody(xhtmlString); } catch (IOException ex) { throw new RuntimeException("Couldn't convert:'" + context.getContentPath() + "': " + ex.getMessage(), ex); } } catch (IOException ex) { throw new RuntimeException("Failed opening String stream: " + ex.getMessage(), ex); } }

Target:
public void processBody(final ParserContext context) { String documentBody = context.getBody(); try (InputStream stream = new ByteArrayInputStream(documentBody.getBytes(StandardCharsets.UTF_8))){ TexyRestService texyService = new TexyRestService(new URL("http://localhost:8022/TexyService.rest.php")); String xhtmlString = null; try (InputStream xhtmlIS = texyService.convertTexyToXhtml(stream)){ java.util.Scanner s = new java.util.Scanner(xhtmlIS, StandardCharsets.UTF_8.name()).useDelimiter("\\A"); xhtmlString = s.hasNext() ? s.next() : ""; context.setBody(xhtmlString); if (!context.getDocumentModel().containsKey(Crawler.Attributes.TITLE)) { try { new TitleExtractor().tryExtractHighestHeader(context); } catch (Exception ex){ LOG.warn("Could not extract title from '{}': {}\nConverted XHTML: \n{}", context.getFile().getName(), ex.getMessage(), xhtmlString); } if (StringUtils.isBlank((String) context.getDocumentModel().get(Crawler.Attributes.TITLE))) context.getDocumentModel().put(Crawler.Attributes.TITLE, context.getFile().getName()); } } catch (IOException ex) { String msg = "Couldn't convert:'" + context.getFile().getPath() + "': " + ex.getMessage(); throw new RuntimeException(msg, ex); } } catch (IOException ex) { throw new RuntimeException("Failed opening String stream: " + ex.getMessage(), ex); } }
Source:
public MainController(String applicationName, LibraryController libraryController, AppsController appsController, EnginesController enginesController, ContainersController containersController, InstallationsFeaturePanel installationsView, SettingsController settingsController, RepositoryManager repositoryManager, ThemeManager themeManager, JavaFxSettingsManager javaFxSettingsManager) { super(); this.applicationName = applicationName; this.mainWindow = new MainWindow(applicationName, libraryController.getView(), appsController.getView(), enginesController.getView(), containersController.getView(), installationsView, settingsController.getView(), themeManager, javaFxSettingsManager); this.themeManager = themeManager; this.javaFxSettingsManager = javaFxSettingsManager; repositoryManager.addCallbacks(this::setDefaultCategoryIcons, e -> { }); installationsView.setOnInstallationAdded(this.mainWindow::showInstallations); this.mainWindow.getApplicationsTab().selectedProperty().addListener((observable, oldValue, newValue) -> { if (newValue && !repositoryManager.isRepositoryLoaded()) { repositoryManager.triggerRepositoryChange(); } }); this.mainWindow.getContainersTab().selectedProperty().addListener((observable, oldValue, newValue) -> { if (newValue && !repositoryManager.isRepositoryLoaded()) { repositoryManager.triggerRepositoryChange(); } }); }

Target:
public MainController(String applicationName, LibraryController libraryController, AppsController appsController, EnginesController enginesController, ContainersController containersController, InstallationsFeaturePanel installationsView, SettingsController settingsController, RepositoryManager repositoryManager, ThemeManager themeManager, JavaFxSettingsManager javaFxSettingsManager) { super(); this.applicationName = applicationName; this.mainWindow = new MainWindow(applicationName, libraryController.getView(), appsController.getView(), enginesController.getView(), containersController.getView(), installationsView, settingsController.getView(), themeManager, javaFxSettingsManager); this.themeManager = themeManager; this.javaFxSettingsManager = javaFxSettingsManager; repositoryManager.addCallbacks(this::setDefaultCategoryIcons, e -> { }); installationsView.setOnInstallationAdded(this.mainWindow::showInstallations); final ChangeListener<Boolean> tabSelectedListener = (observable, oldValue, newValue) -> { if (newValue && !repositoryManager.isRepositoryLoaded()) { repositoryManager.triggerRepositoryChange(); } }; this.mainWindow.getApplicationsTab().selectedProperty().addListener(tabSelectedListener); this.mainWindow.getContainersTab().selectedProperty().addListener(tabSelectedListener); }