auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public MockHelixParticipant(ClusterMapConfig clusterMapConfig) { super(clusterMapConfig, new MockHelixManagerFactory(), metricRegistry, parseDcJsonAndPopulateDcInfo(clusterMapConfig.clusterMapDcsZkConnectStrings).get( clusterMapConfig.clusterMapDatacenterName).getZkConnectStrs().get(0), true); mockReplicationManagerListener = Mockito.mock(PartitionStateChangeListener.class); doAnswer(invocation -> { replicaState = ReplicaState.BOOTSTRAP; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateBootstrap(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeStandbyFromBootstrap(any(String.class)); doAnswer(invocation -> { replicaState = ReplicaState.INACTIVE; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateDeactivation(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeInactiveFromStandby(any(String.class)); doAnswer(invocation -> { replicaState = ReplicaState.OFFLINE; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateDisconnection(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeOfflineFromInactive(any(String.class)); }

Target:
public MockHelixParticipant(ClusterMapConfig clusterMapConfig) { this(clusterMapConfig, new MockHelixManagerFactory()); mockReplicationManagerListener = Mockito.mock(PartitionStateChangeListener.class); doAnswer(invocation -> { replicaState = ReplicaState.BOOTSTRAP; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateBootstrap(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeStandbyFromBootstrap(any(String.class)); doAnswer(invocation -> { replicaState = ReplicaState.INACTIVE; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateDeactivation(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeInactiveFromStandby(any(String.class)); doAnswer(invocation -> { replicaState = ReplicaState.OFFLINE; if (replicaSyncUpService != null && currentReplica != null) { replicaSyncUpService.initiateDisconnection(currentReplica); } if (listenerLatch != null) { listenerLatch.countDown(); } return null; }).when(mockReplicationManagerListener).onPartitionBecomeOfflineFromInactive(any(String.class)); }
Source:
static void assertMonitor(NodeMonitor monitor, Computer c) throws AssertionError { AbstractNodeMonitorDescriptor<?> descriptor = monitor.getDescriptor(); final Method monitorMethod; try { monitorMethod = AbstractAsyncNodeMonitorDescriptor.class.getDeclaredMethod("monitor", Computer.class); } catch (NoSuchMethodException ex) { System.out.println("Cannot invoke monitor " + monitor + ", no monitor(Computer.class) method in the Descriptor. It will be ignored. " + ex.getMessage()); return; } try { monitorMethod.setAccessible(true); Object res = monitorMethod.invoke(descriptor, c); System.out.println("Successfully executed monitor " + monitor); } catch (Exception ex) { throw new AssertionError("Failed to run monitor " + monitor + " for computer " + c, ex); } finally { monitorMethod.setAccessible(false); } }

Target:
static void assertMonitor(NodeMonitor monitor, Computer c) throws AssertionError { AbstractNodeMonitorDescriptor<?> descriptor = monitor.getDescriptor(); final Method monitorMethod; try { monitorMethod = AbstractAsyncNodeMonitorDescriptor.class.getDeclaredMethod("monitor", Computer.class); } catch (NoSuchMethodException ex) { throw new AssertionError("Cannot invoke monitor " + monitor + ", no monitor(Computer.class) method in the Descriptor. It will be ignored. ", ex); } try { monitorMethod.setAccessible(true); Object res = monitorMethod.invoke(descriptor, c); System.out.println("Successfully executed monitor " + monitor); } catch (Exception ex) { throw new AssertionError("Failed to run monitor " + monitor + " for computer " + c, ex); } finally { monitorMethod.setAccessible(false); } }
Source:
public static boolean isSchemaCheckRequired(PTableType tableType, ReadOnlyProps props) { if (PTableType.TABLE.equals(tableType) && isNamespaceMappingEnabled(tableType, props)) { return true; } return false; }

Target:
public static boolean isSchemaCheckRequired(PTableType tableType, ReadOnlyProps props) { return PTableType.TABLE.equals(tableType) && isNamespaceMappingEnabled(tableType, props); }
Source:
public void testExactExpirationOnWrite() throws Exception { initTest(StateTtlConfig.UpdateType.OnCreateAndWrite, StateTtlConfig.StateVisibility.NeverReturnExpired); takeAndRestoreSnapshot(); timeProvider.time = 0; ctx().update(ctx().updateEmpty); takeAndRestoreSnapshot(); timeProvider.time = 20; assertEquals(UNEXPIRED_AVAIL, ctx().getUpdateEmpty, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 50; ctx().update(ctx().updateUnexpired); takeAndRestoreSnapshot(); timeProvider.time = 120; assertEquals(UPDATED_UNEXPIRED_AVAIL, ctx().getUnexpired, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 170; ctx().update(ctx().updateExpired); takeAndRestoreSnapshot(); timeProvider.time = 220; assertEquals(UPDATED_UNEXPIRED_AVAIL, ctx().getUpdateExpired, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 300; assertEquals(EXPIRED_UNAVAIL, ctx().emptyValue, ctx().get()); assertTrue(ctx().isOriginalEmptyValue()); }

Target:
public void testExactExpirationOnWrite() throws Exception { initTest(StateTtlConfig.UpdateType.OnCreateAndWrite, StateTtlConfig.StateVisibility.NeverReturnExpired); takeAndRestoreSnapshot(); timeProvider.time = 0; ctx().update(ctx().updateEmpty); takeAndRestoreSnapshot(); timeProvider.time = 20; assertEquals(UNEXPIRED_AVAIL, ctx().getUpdateEmpty, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 50; ctx().update(ctx().updateUnexpired); takeAndRestoreSnapshot(); timeProvider.time = 120; assertEquals(UPDATED_UNEXPIRED_AVAIL, ctx().getUnexpired, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 170; ctx().update(ctx().updateExpired); takeAndRestoreSnapshot(); timeProvider.time = 220; assertEquals(UPDATED_UNEXPIRED_AVAIL, ctx().getUpdateExpired, ctx().get()); takeAndRestoreSnapshot(); timeProvider.time = 300; assertEquals(EXPIRED_UNAVAIL, ctx().emptyValue, ctx().get()); assertTrue("Original state should be cleared on access", ctx().isOriginalEmptyValue()); }
Source:
protected void setCapacity(String workerIdentity, int newExecutorNum, int newWaitQueueSize) throws IOException, ServiceException { long currentTime = System.currentTimeMillis(); if (currentTime > nextCheckTime) { LlapZookeeperRegistryImpl.ConfigChangeLockResult lockResult = registry.lockForConfigChange(currentTime + this.minConfigChangeDelayMs); LOG.debug("Got result for lock check: {}", lockResult); if (lockResult.isSuccess()) { LOG.info("Setting capacity for workerIdentity={} to newExecutorNum={}, newWaitQueueSize={}", workerIdentity, newExecutorNum, newWaitQueueSize); LlapServiceInstance serviceInstance = registry.getInstances().getInstance(workerIdentity); LlapManagementProtocolClientImpl client = clientFactory.create(serviceInstance); client.setCapacity(null, SetCapacityRequestProto.newBuilder() .setExecutorNum(newExecutorNum) .setQueueSize(newWaitQueueSize) .build()); } if (lockResult.getNextConfigChangeTime() > -1L) { nextCheckTime = lockResult.getNextConfigChangeTime(); } } else { LOG.debug("Skipping check. Current time and we are waiting for {}.", currentTime, nextCheckTime); } }

Target:
protected void setCapacity(String workerIdentity, int newExecutorNum, int newWaitQueueSize) throws IOException, ServiceException { long currentTime = System.currentTimeMillis(); if (currentTime > nextCheckTime) { LlapZookeeperRegistryImpl.ConfigChangeLockResult lockResult = registry.lockForConfigChange(currentTime, currentTime + this.minConfigChangeDelayMs); LOG.debug("Got result for lock check: {}", lockResult); if (lockResult.isSuccess()) { LOG.info("Setting capacity for workerIdentity={} to newExecutorNum={}, newWaitQueueSize={}", workerIdentity, newExecutorNum, newWaitQueueSize); LlapServiceInstance serviceInstance = registry.getInstances().getInstance(workerIdentity); LlapManagementProtocolClientImpl client = clientFactory.create(serviceInstance); client.setCapacity(null, SetCapacityRequestProto.newBuilder() .setExecutorNum(newExecutorNum) .setQueueSize(newWaitQueueSize) .build()); } if (lockResult.getNextConfigChangeTime() > -1L) { nextCheckTime = lockResult.getNextConfigChangeTime(); } } else { LOG.debug("Skipping check. Current time and we are waiting for {}.", currentTime, nextCheckTime); } }
Source:
protected void schedule(GerritCause cause, GerritTriggeredEvent event, AbstractProject project) { BadgeAction badgeAction = new BadgeAction(event); int projectbuildDelay = getBuildScheduleDelay(); if (cause instanceof GerritUserCause) { projectbuildDelay = 0; } else if (project.getHasCustomQuietPeriod() && project.getQuietPeriod() > projectbuildDelay) { projectbuildDelay = project.getQuietPeriod(); } ParametersAction parameters = createParameters(event, project); Future build = project.scheduleBuild2( projectbuildDelay, cause, badgeAction, new RetriggerAction(cause.getContext()), new RetriggerAllAction(cause.getContext()), parameters); if (event instanceof ChangeBasedEvent) { ChangeBasedEvent changeBasedEvent = (ChangeBasedEvent)event; if (PluginImpl.getInstance().getConfig().isGerritBuildCurrentPatchesOnly()) { getRunningJobs().scheduled(changeBasedEvent, parameters, project.getName()); } if (null != changeBasedEvent.getPatchSet()) { logger.info("Project Build Scheduled: By event: {}", new Object[]{project.getName(), (build != null), changeBasedEvent.getChange().getNumber() + "/" + changeBasedEvent.getPatchSet().getNumber(), }); } } else if (event instanceof RefUpdated) { RefUpdated refUpdated = (RefUpdated)event; logger.info("Project Build Scheduled: By event: {}", new Object[]{project.getName(), (build != null), refUpdated.getRefUpdate().getRefName() + " " + refUpdated.getRefUpdate().getNewRev(), }); } }

Target:
protected void schedule(GerritCause cause, GerritTriggeredEvent event, AbstractProject project) { BadgeAction badgeAction = new BadgeAction(event); int projectbuildDelay = getBuildScheduleDelay(); if (cause instanceof GerritUserCause) { projectbuildDelay = 0; } else if (project.getHasCustomQuietPeriod() && project.getQuietPeriod() > projectbuildDelay) { projectbuildDelay = project.getQuietPeriod(); } ParametersAction parameters = createParameters(event, project); Future build = project.scheduleBuild2( projectbuildDelay, cause, badgeAction, new RetriggerAction(cause.getContext()), new RetriggerAllAction(cause.getContext()), parameters); if (event instanceof ChangeBasedEvent) { ChangeBasedEvent changeBasedEvent = (ChangeBasedEvent)event; if (PluginImpl.getInstance().getConfig().isGerritBuildCurrentPatchesOnly()) { getRunningJobs().scheduled(changeBasedEvent, parameters, project.getName()); } if (null != changeBasedEvent.getPatchSet()) { logger.info("Project Build Scheduled: By event: {}", new Object[]{project.getName(), (build != null), changeBasedEvent.getChange().getNumber() + "/" + changeBasedEvent.getPatchSet().getNumber(), }); } else { logger.info("Project Build Scheduled: By event: {}", new Object[]{project.getName(), (build != null), changeBasedEvent.getChange().getNumber(), }); } } else if (event instanceof RefUpdated) { RefUpdated refUpdated = (RefUpdated)event; logger.info("Project Build Scheduled: By event: {}", new Object[]{project.getName(), (build != null), refUpdated.getRefUpdate().getRefName() + " " + refUpdated.getRefUpdate().getNewRev(), }); } }
Source:
public synchronized @Nonnull String version() throws IOException { if (this.version == null) { Process p = runFunc.run(ImmutableList.of(path, "-version")); InputStream stream = p.getInputStream(); try { LineIterator iterator = IOUtils.lineIterator(stream, StandardCharsets.UTF_8); this.version = iterator.nextLine(); FFmpegUtils.throwOnError(FFMPEG, p); } finally { p.destroy(); IOUtils.closeQuietly(stream); } } return version; }

Target:
public synchronized @Nonnull String version() throws IOException { if (this.version == null) { Process p = runFunc.run(ImmutableList.of(path, "-version")); try (InputStream stream = p.getInputStream()) { LineIterator iterator = IOUtils.lineIterator(stream, StandardCharsets.UTF_8); this.version = iterator.nextLine(); FFmpegUtils.throwOnError(FFMPEG, p); } finally { p.destroy(); IOUtils.closeQuietly(p.getOutputStream(), p.getErrorStream()); } } return version; }
Source:
private ContentSource source(AbstractTreeIterator iterator) { if (iterator instanceof WorkingTreeIterator) return ContentSource.create((WorkingTreeIterator) iterator); return ContentSource.create(db.newObjectReader()); }

Target:
private ContentSource source(AbstractTreeIterator iterator) { if (iterator instanceof WorkingTreeIterator) { return ContentSource.create((WorkingTreeIterator) iterator); } return ContentSource.create(db.newObjectReader()); }
Source:
public void setMaxReadsToAccumulatePerLocus(int maxReadsToAccumulatePerLocus) { if (getMaxReadsToAccumulatePerLocus() != maxReadsToAccumulatePerLocus) { throw new UnsupportedOperationException("Locus cap is not supported for " + getClass().getSimpleName() + "."); } }

Target:
public void setMaxReadsToAccumulatePerLocus(int maxReadsToAccumulatePerLocus) { if (getMaxReadsToAccumulatePerLocus() != 0) { throw new UnsupportedOperationException("Locus cap is not supported for " + getClass().getSimpleName() + "."); } }
Source:
private String parseParamDelimiter() throws ParseException { int index = nextNonBlank(); if (index < 0 || expression.charAt(index) != ',') { throw new ParseException(errorMessage(PARAMETER_DELIMITER_EXPECTED_ERROR), parseIndex); } setParseIndex(index + 1); return ","; }

Target:
private void parseParamDelimiter() throws ParseException { int index = nextNonBlank(); if (index < 0 || expression.charAt(index) != ',') { throw new ParseException(errorMessage(PARAMETER_DELIMITER_EXPECTED_ERROR), parseIndex); } setParseIndex(index + 1); }
Source:
public AbstractListDataView<T> updateItem(T item, SerializableFunction<T, ?> identityProvider) { Objects.requireNonNull(item, "Item cannot be null"); Objects.requireNonNull(identityProvider, "Identity provider cannot be null"); Collection<T> items = getDataProvider().getItems(); if (items instanceof List) { final Object itemIdentifier = identityProvider.apply(item); Objects.requireNonNull(itemIdentifier, "Identity Provider should not return null"); final List<T> itemList = (List<T>) items; for (int itemIndex = 0; itemIndex < itemList.size(); itemIndex++) { T nextItem = itemList.get(itemIndex); if (itemIdentifier.equals( identityProvider.apply(nextItem))) { itemList.set(itemIndex, item); getDataProvider().refreshItem(item); } } return this; } throw new IllegalArgumentException( String.format(COLLECTION_TYPE_ERROR_MESSAGE_PATTERN, items.getClass().getSimpleName())); }

Target:
public AbstractListDataView<T> updateItem(T item, SerializableFunction<T, ?> identityProvider) { Objects.requireNonNull(item, "Item cannot be null"); final ListDataProvider<T> dataProvider = getDataProvider(); Collection<T> items = dataProvider.getItems(); if (items instanceof List) { final Object itemIdentifier = getIdentifier(item, identityProvider); final List<T> itemList = (List<T>) items; int itemIndex = getItemIndex(item, identityProvider); if (itemIndex != -1) { T itemToUpdate = itemList.get(itemIndex); if (itemIdentifier.equals( getIdentifier(itemToUpdate, identityProvider))) { itemList.set(itemIndex, item); dataProvider.refreshItem(item); } } return this; } throw new IllegalArgumentException( String.format(COLLECTION_TYPE_ERROR_MESSAGE_PATTERN, items.getClass().getSimpleName())); }
Source:
public void load() { reservedClasses = new ArrayList<String>(); reservedClasses.addAll(reservedGateClasses); reservedClasses.addAll(reservedTestClasses); CoreModule.addGeneralApplicationParser(new ApplicationHomeParser()); CoreModule.addSystemApplicationParser(new ApplicationSystemParser()); CoreModule.addLayoutToHomeTab(TimelineLayout.getInstance()); final AsyncCallback<List<AppClass>> callback = new AsyncCallback<List<AppClass>>() { @Override public void onFailure(Throwable caught) { Layout.getInstance().setWarningMessage("Unable to load classes:<br />" + caught.getMessage()); } @Override public void onSuccess(List<AppClass> result) { for (AppClass appClass : result) { if (!reservedClasses.contains(appClass.getName())) { CoreModule.addApplicationsTileGrid( new ApplicationTileGrid(appClass.getName())); } } } }; ApplicationService.Util.getInstance().getClasses(callback); CenterTabSet.getInstance().addCloseClickHandler(new CloseClickHandler() { @Override public void onCloseClick(TabCloseClickEvent event) { Tab tab = event.getTab(); try { ((AbstractSimulationTab) tab).destroy(); } catch (ClassCastException ex) { } } }); }

Target:
public void load() { CoreModule.addGeneralApplicationParser(new ApplicationHomeParser()); CoreModule.addSystemApplicationParser(new ApplicationSystemParser()); CoreModule.addLayoutToHomeTab(TimelineLayout.getInstance()); final AsyncCallback<List<AppClass>> callback = new AsyncCallback<List<AppClass>>() { @Override public void onFailure(Throwable caught) { Layout.getInstance().setWarningMessage("Unable to load classes:<br />" + caught.getMessage()); } @Override public void onSuccess(List<AppClass> result) { for (AppClass appClass : result) { if (!reservedClasses.keySet().contains(appClass.getName())) { CoreModule.addApplicationsTileGrid( new ApplicationTileGrid(appClass.getName())); } } } }; ApplicationService.Util.getInstance().getClasses(callback); CenterTabSet.getInstance().addCloseClickHandler(new CloseClickHandler() { @Override public void onCloseClick(TabCloseClickEvent event) { Tab tab = event.getTab(); try { ((AbstractSimulationTab) tab).destroy(); } catch (ClassCastException ex) { } } }); }
Source:
public static String encodeJavaOpts(String javaOpts) { String javaOptsBase64 = DatatypeConverter.printBase64Binary( javaOpts.getBytes(StandardCharsets.UTF_8)); return String.format("\"%s\"", javaOptsBase64.replace("=", "(61)").replace("=", "&equals;")); }

Target:
public static String encodeJavaOpts(String javaOpts) { String javaOptsBase64 = DatatypeConverter.printBase64Binary( javaOpts.getBytes(StandardCharsets.UTF_8)); return String.format("\"%s\"", javaOptsBase64.replace("=", "(61)")); }
Source:
public static void jobSchedulerCancelAll(@NonNull Context context) { JobScheduler jobScheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE); if (jobScheduler != null) { List<JobInfo> jobs = getPendingJobs(jobScheduler); if (jobs != null && !jobs.isEmpty()) { for (JobInfo jobInfo : jobs) { jobScheduler.cancel(jobInfo.getId()); } } } }

Target:
public static void jobSchedulerCancelAll(@NonNull Context context) { JobScheduler jobScheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE); if (jobScheduler != null) { List<JobInfo> jobs = getPendingJobs(jobScheduler); if (jobs != null && !jobs.isEmpty()) { for (JobInfo jobInfo : jobs) { int id = jobInfo.getId(); try { jobScheduler.cancel(id); } catch (Throwable throwable) { Logger.get().error(TAG, String.format(Locale.getDefault(), "Unable to cancel Job (%d)", id), throwable); } } } } }
Source:
protected SftpFileSystem(final GenericFileName rootName, final Session session, final FileSystemOptions fileSystemOptions) { super(rootName, null, fileSystemOptions); this.session = Objects.requireNonNull(session, "session"); this.connectTimeoutMillis = SftpFileSystemConfigBuilder.getInstance() .getConnectTimeoutMillis(fileSystemOptions); if (SftpFileSystemConfigBuilder.getInstance().isExecEnabled(fileSystemOptions)){ this.execDisabled = detectExecDisabled(); } else { this.execDisabled = true; } }

Target:
protected SftpFileSystem(final GenericFileName rootName, final Session session, final FileSystemOptions fileSystemOptions) { super(rootName, null, fileSystemOptions); this.session = Objects.requireNonNull(session, "session"); this.connectTimeoutMillis = SftpFileSystemConfigBuilder.getInstance() .getConnectTimeoutMillis(fileSystemOptions); if (SftpFileSystemConfigBuilder.getInstance().isDisableDetectExecChannel(fileSystemOptions)) { this.execDisabled = true; } else { this.execDisabled = detectExecDisabled(); } }
Source:
static String parseJDBCPassword(String jdbcUrl) throws SqlException { Properties properties = ClientDriver.tokenizeURLProperties(jdbcUrl, null); System.out.println(properties); return properties.getProperty("password"); }

Target:
static String parseJDBCPassword(String jdbcUrl) throws SqlException { Properties properties = ClientDriver.tokenizeURLProperties(jdbcUrl, null); return properties.getProperty("password"); }
Source:
private void fetchChapters() { App.getInstance().getGdgXHub().getDirectory( new Callback<Directory>() { @Override public void success(final Directory directory, Response response) { addChapters(directory.getGroups()); mLoadSwitcher.setDisplayedChild(1); App.getInstance().getModelCache().putAsync( Const.CACHE_KEY_CHAPTER_LIST_HUB, directory, DateTime.now().plusDays(4), null ); } @Override public void failure(RetrofitError error) { try { Snackbar snackbar = Snackbar.make( getView(), R.string.fetch_chapters_failed, Snackbar.LENGTH_INDEFINITE ); snackbar.setAction( "Retry", new View.OnClickListener() { @Override public void onClick(View v) { fetchChapters(); } } ); ColoredSnackBar.alert(snackbar).show(); } catch (IllegalStateException exception) { Toast.makeText(getActivity(), R.string.fetch_chapters_failed, Toast.LENGTH_SHORT).show(); } Timber.e(error, "Could'nt fetch chapter list"); } } ); }

Target:
private void fetchChapters() { App.getInstance().getGdgXHub().getDirectory().enqueue(new Callback<Directory>() { @Override public void success(Directory directory) { if (isContextValid()) { addChapters(directory.getGroups()); mLoadSwitcher.setDisplayedChild(1); } App.getInstance().getModelCache().putAsync(Const.CACHE_KEY_CHAPTER_LIST_HUB, directory, DateTime.now().plusDays(4), null); } @Override public void failure(Throwable error) { showError(R.string.fetch_chapters_failed); } @Override public void networkFailure(Throwable error) { showError(R.string.offline_alert); } }); }
Source:
public HWNetworkStore[] getNetworks() { Enumeration<NetworkInterface> interfaces; HWNetworkStore netstore; List<HWNetworkStore> result; StringBuilder sb; result = new ArrayList<>(); try { interfaces = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(interfaces)) { if (!netint.getDisplayName().equals("lo")) { netstore = new HWNetworkStore(); this.setNetworkParameters(netstore, netint); this.setNetworkStats(netstore); result.add(netstore); } } } catch (SocketException ex) { LOG.debug("Socket exception when retrieving network interfaces: " + ex.getMessage()); } return result.toArray(new HWNetworkStore[result.size()]); }

Target:
public HWNetworkStore[] getNetworks() { Enumeration<NetworkInterface> interfaces; HWNetworkStore netstore; List<HWNetworkStore> result; result = new ArrayList<>(); try { interfaces = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(interfaces)) { if (!netint.isLoopback()) { netstore = new HWNetworkStore(); this.setNetworkParameters(netstore, netint); this.setNetworkStats(netstore); netstore.setMTU(netint.getMTU()); result.add(netstore); } } } catch (SocketException ex) { LOG.debug("Socket exception when retrieving network interfaces: " + ex.getMessage()); } return result.toArray(new HWNetworkStore[result.size()]); }
Source:
private void validateProperties(ProcessingEnvironment env, Map<String, ExecutableElement> properties) { TypeElement parcelable = env.getElementUtils().getTypeElement("android.os.Parcelable"); TypeMirror serializable = TypeSimplifier.typeFromClass(env.getTypeUtils(), env.getElementUtils(), Serializable.class); for (ExecutableElement name : properties.values()) { TypeMirror type = name.getReturnType(); if (!TypeName.get(type).isPrimitive() && !TypeSimplifier.isClassOfType(env.getTypeUtils(), parcelable.asType(), type) && !TypeSimplifier.isClassOfType(env.getTypeUtils(), serializable, type)) { env.getMessager().printMessage(Diagnostic.Kind.ERROR, "AutoValue property " + name.getSimpleName() + " is not primitive, Parcelable or Serializable.", name); throw new AutoParcelException(); } } }

Target:
private void validateProperties(ProcessingEnvironment env, Map<String, ExecutableElement> properties) { TypeMirror parcelable = env.getElementUtils().getTypeElement("android.os.Parcelable").asType(); TypeMirror serializable = TypeSimplifier.typeFromClass(env.getTypeUtils(), env.getElementUtils(), Serializable.class); for (ExecutableElement name : properties.values()) { TypeMirror type = name.getReturnType(); if (!TypeName.get(type).isPrimitive() && !TypeSimplifier.isClassOfType(env.getTypeUtils(), parcelable, type) && !TypeSimplifier.isClassOfType(env.getTypeUtils(), serializable, type)) { env.getMessager().printMessage(Diagnostic.Kind.ERROR, "AutoValue property " + name.getSimpleName() + " is not primitive, Parcelable, or Serializable.", name); throw new AutoParcelException(); } } }
Source:
default void removeCharge(Location l, int charge) { Validate.isTrue(charge > 0, "The charge to remove must be greater than zero!"); int capacity = getCapacity(); if (capacity > 0) { int currentCharge = getCharge(l); if (currentCharge > 0) { int newCharge = Math.max(0, currentCharge - charge); BlockStorage.addBlockInfo(l, "energy-charge", String.valueOf(newCharge), false); if (getEnergyComponentType() == EnergyNetComponentType.CAPACITOR) { SlimefunUtils.updateCapacitorTexture(l, charge, capacity); } } } }

Target:
default void removeCharge(Location l, int charge) { Validate.notNull(l, "Location was null!"); Validate.isTrue(charge > 0, "The charge to remove must be greater than zero!"); int capacity = getCapacity(); if (capacity > 0) { int currentCharge = getCharge(l); if (currentCharge > 0) { int newCharge = Math.max(0, currentCharge - charge); BlockStorage.addBlockInfo(l, "energy-charge", String.valueOf(newCharge), false); if (getEnergyComponentType() == EnergyNetComponentType.CAPACITOR) { SlimefunUtils.updateCapacitorTexture(l, charge, capacity); } } } }
Source:
public Set<String> getHosts(String serviceName, String componentName) { Set<String> hosts = m_topology.get(serviceName + "/" + componentName); if (null == hosts) { hosts = Sets.newHashSet(); } return hosts; }

Target:
public Set<String> getHosts(String serviceName, String componentName) { Set<String> hosts = m_topology.get(serviceName + "/" + componentName); if (null == hosts) { hosts = new HashSet<>(); } return hosts; }
Source:
private void createShellExecutor(String executorClassName) throws ExecutorException { executor = (SqlExecutor) createInstance(executorClassName); }

Target:
private void createShellExecutor(String executorClassName) throws ExecutorException { try { executor = (SqlExecutor) createInstance(executorClassName); } catch (ClassCastException e) { String errMsg = String.format("Error trying to cast Object of class %s to SqlExecutor", executorClassName); LOG.error(errMsg); throw new ExecutorException(errMsg, e); } catch (Exception e) { LOG.error(e.getMessage()); throw new ExecutorException(e); } }
Source:
private void repaintPosition(final double position) { int zoomSwitchLevel = MAX_ZOOM - diagram.getLevel(); if (zoomLevel > zoomSwitchLevel) { if (currentZoomLevel != zoomLevel || repaintNow) { Group diagramDrawing = new Group(); double width = unifiedEnd * scale * VertexView.HORIZONTALSCALE; int diagramLevel = zoomLevel - zoomSwitchLevel; diagramDrawing.getChildren().add( diagramView.drawDiagram(diagram, diagramLevel, width)); diagramDrawing.getChildren().add(new Rectangle(width, 0)); scrollPane.setContent(diagramDrawing); wrapper.setCenter(scrollPane); currentZoomLevel = zoomLevel; repaintNow = false; } } else { int[] bucketLocations = getStartandEndBucket(position); int startBucket = bucketLocations[0]; int endBucket = bucketLocations[1]; if (currEndPosition != endBucket && currStartPosition != startBucket || repaintNow) { Group graphDrawing = new Group(); graphDrawing.setManaged(false); graphDrawing.getChildren().add( drawGraph(startBucket, endBucket)); graphDrawing.getChildren().add( new Rectangle(unifiedEnd * scale * VertexView.HORIZONTALSCALE, 0)); scrollPane.setContent(graphDrawing); wrapper.setCenter(scrollPane); currEndPosition = endBucket; currStartPosition = startBucket; repaintNow = false; } } }

Target:
private void repaintPosition(final double position) { int zoomSwitchLevel = MAX_ZOOM - diagram.getLevel(); double scaledVertex = scale * VertexView.HORIZONTALSCALE; if (zoomLevel > zoomSwitchLevel) { if (currentZoomLevel != zoomLevel || repaintNow) { Group diagramDrawing = new Group(); double width = maxUnifiedEnd * scaledVertex; int diagramLevel = zoomLevel - zoomSwitchLevel; diagramDrawing.getChildren().addAll( diagramView.drawDiagram(diagram, diagramLevel, width), new Rectangle(width, 0)); scrollPane.setContent(diagramDrawing); wrapper.setCenter(scrollPane); currentZoomLevel = zoomLevel; repaintNow = false; } } else { int[] bucketLocations = getStartandEndBucket(position); int startBucket = bucketLocations[0]; int endBucket = bucketLocations[1]; if (currEndPosition != endBucket && currStartPosition != startBucket || repaintNow) { Group graphDrawing = new Group(); graphDrawing.setManaged(false); graphDrawing.getChildren().addAll( drawGraph(startBucket, endBucket), new Rectangle(maxUnifiedEnd * scaledVertex, 0)); scrollPane.setContent(graphDrawing); wrapper.setCenter(scrollPane); currEndPosition = endBucket; currStartPosition = startBucket; repaintNow = false; } } }
Source:
private Properties getProperties() { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Properties properties = new Properties(); String dbType = "postgres"; if (System.getProperty("databaseType")!=null){ dbType = System.getProperty("databaseType"); } else if(System.getenv("databaseType")!=null){ dbType = System.getenv("databaseType"); } try (InputStream resourceStream = loader.getResourceAsStream(dbType + "-db-config.properties")) { properties.load(resourceStream); } catch (Exception e) { Logger.error(this.getClass(), "Unable to get properties from file db-config.properties", e); throw new DotRuntimeException(e); } return properties; }

Target:
private Properties getProperties() { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Properties properties = new Properties(); final String dbType = System.getProperty("databaseType", (System.getenv("databaseType") != null ? System.getenv("databaseType") : "postgres")); try (InputStream resourceStream = loader.getResourceAsStream(dbType + "-db-config.properties")) { properties.load(resourceStream); } catch (Exception e) { Logger.error(this.getClass(), "Unable to get properties from file db-config.properties", e); throw new DotRuntimeException(e); } return properties; }
Source:
public void checkPortVisibility() throws Exception { simpleImport("resources/rt/PortModel.emx"); openEditor(); rootPackage.getPackagedElements().stream() .filter(Port.class::isInstance) .filter(p -> !((Port) p).isService()) .forEach(port -> assertEquals(" Port visibility Error: port should be protected", VisibilityKind.PROTECTED_LITERAL, port.getVisibility())); }

Target:
public void checkPortVisibility() throws Exception { simpleImport("resources/rt/PortModel.emx"); openEditor(); rootPackage.getOwnedElements().stream() .filter(Port.class::isInstance) .filter(p -> !((Port) p).isService()) .forEach(port -> assertEquals(" Port visibility Error: port should be protected", VisibilityKind.PROTECTED_LITERAL, ((Port) port).getVisibility())); }
Source:
private API addSystemVersion(API api) { String ProductVersion = getConfigurationValue(String.class, ConfigurationValues.ProductRPMVersion, null); api.setProductInfo(new ProductInfo()); api.getProductInfo().setName("oVirt Engine"); api.getProductInfo().setVendor("ovirt.org"); api.getProductInfo().setVersion(VersionHelper.parseVersion(ProductVersion)); return api; }

Target:
private API addSystemVersion(API api) { String productVersion = getConfigurationValue(String.class, ConfigurationValues.ProductRPMVersion, null); api.setProductInfo(new ProductInfo()); api.getProductInfo().setName("oVirt Engine"); api.getProductInfo().setVendor("ovirt.org"); api.getProductInfo().setVersion(VersionHelper.parseVersion(productVersion)); return api; }
Source:
public Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint) { String source; if (message.getPayload() instanceof byte[]) { source = new String((byte[]) message.getPayload()); } else { source = (String) message.getPayload(); } return TupleBuilder.fromString(source); }

Target:
public Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint) { String source; if (message.getPayload() instanceof byte[]) { source = new String((byte[]) message.getPayload(), Charset.forName("UTF-8")); } else { source = message.getPayload().toString(); } return TupleBuilder.fromString(source); }
Source:
public ChatComponent addExtra(ChatComponent component) { if (!hasExtra(component, true)) { $lock.writeLock().lock(); this.extra.add(component); $lock.writeLock().unlock(); } return this; }

Target:
public ChatComponent addExtra(ChatComponent component) { if (!hasExtra(component, true)) { this.extra.add(component); } return this; }
Source:
public void indexQuestion(Question q) { try { SolrInputDocument doc = toDoc(q); server.add(doc); server.commit(); } catch (IOException | SolrServerException e) { throw new IndexException("Could not index Question", e); } }

Target:
public void indexQuestion(Question q) { try { SolrInputDocument doc = toDoc(q); server.add(doc); server.commit(); } catch (IOException | SolrServerException e) { throw new IndexException("Could not index Question [" + q.getId() + "]", e); } }
Source:
public void onCreate() { super.onCreate(); this.context = this; ThemeHelper.init(context); if (LeakCanary.isInAnalyzerProcess(this)) { return; } refWatcher = installLeakCanary(); SettingsActivity.initSettings(this); NewPipe.init(getDownloader(), org.schabi.newpipe.util.Localization.getPreferredExtractorLocal(this)); StateSaver.init(this); initNotificationChannel(); ImageLoader.getInstance().init(getImageLoaderConfigurations(10, 50)); configureRxJavaErrorHandler(); }

Target:
public void onCreate() { super.onCreate(); ThemeHelper.init(this); if (LeakCanary.isInAnalyzerProcess(this)) { return; } refWatcher = installLeakCanary(); app = this; SettingsActivity.initSettings(this); NewPipe.init(getDownloader(), org.schabi.newpipe.util.Localization.getPreferredExtractorLocal(this)); StateSaver.init(this); initNotificationChannel(); ImageLoader.getInstance().init(getImageLoaderConfigurations(10, 50)); configureRxJavaErrorHandler(); new CheckForNewAppVersionTask().execute(); }
Source:
public ObjectId getHead() throws IOException { Repository subRepo = getRepository(); if (subRepo == null) return null; ObjectId head; try { head = subRepo.resolve(Constants.HEAD); } finally { subRepo.close(); } return head; }

Target:
public ObjectId getHead() throws IOException { Repository subRepo = getRepository(); if (subRepo == null) return null; try { return subRepo.resolve(Constants.HEAD); } finally { subRepo.close(); } }
Source:
public void stopQueue() { if (isStarted.compareAndSet(true, false)) { isInitialized.set(false); super.stopQueue(); reaper.stop(); dao.close(); dispatcher.stop(); } }

Target:
public void stopQueue() { if (isStarted.compareAndSet(true, false)) { isInitialized.set(false); reaper.stop(); super.stopQueue(); dispatcher.stop(); dao.close(); } }
Source:
public void test_isLeapYear_nearestEndOf(DayOfWeek dayOfWeek, Month ending) { AccountingChronology chronology = new AccountingChronologyBuilder().endsOn(dayOfWeek).nearestEndOf(ending) .withDivision(AccountingYearDivision.QUARTERS_OF_PATTERN_4_4_5_WEEKS).leapWeekInMonth(12) .toChronology(); IntFunction<LocalDate> getYearEnd = year -> { return LocalDate.of(year, ending, 1).plusMonths(1).plusDays(3 - 1).with(TemporalAdjusters.previousOrSame(dayOfWeek)); }; Predicate<Integer> isLeapYear = year -> { LocalDate currentYearEnd = getYearEnd.apply(year); LocalDate prevYearEnd = getYearEnd.apply(year - 1); return prevYearEnd.until(currentYearEnd, DAYS) == 371; }; for (int year = -200; year < 600; year++) { assertEquals(chronology.isLeapYear(year), isLeapYear.test(year), "Fails on " + year); } }

Target:
public void test_isLeapYear_nearestEndOf(DayOfWeek dayOfWeek, Month ending) { AccountingChronology chronology = new AccountingChronologyBuilder().endsOn(dayOfWeek).nearestEndOf(ending) .withDivision(AccountingYearDivision.QUARTERS_OF_PATTERN_4_4_5_WEEKS).leapWeekInMonth(12) .toChronology(); IntFunction<LocalDate> getYearEnd = year -> { return LocalDate.of(year, ending, 3).plusMonths(1).with(TemporalAdjusters.previousOrSame(dayOfWeek)); }; Predicate<Integer> isLeapYear = year -> { LocalDate currentYearEnd = getYearEnd.apply(year); LocalDate prevYearEnd = getYearEnd.apply(year - 1); return prevYearEnd.until(currentYearEnd, DAYS) == 371; }; for (int year = -200; year < 600; year++) { assertEquals(chronology.isLeapYear(year), isLeapYear.test(year), "Fails on " + year); } }
Source:
public TmfVertex(final long ts) { this.fTimestamp = ts; this.fId = count++; }

Target:
public TmfVertex(final long ts) { fTimestamp = ts; synchronized (TmfVertex.class) { fId = count++; } }
Source:
private void checkEmbulkVersion() { boolean isValidVersion = true; try { String[] versionNumber = EmbulkVersion.VERSION.split("-"); if (versionNumber[0] != null) { String[] versions = versionNumber[0].split("\\."); if (versions.length == 3) { if (Integer.valueOf(versions[1]) <= 8 && Integer.valueOf(versions[2]) < 22) { isValidVersion = false; } } } } catch (NoClassDefFoundError ex) { isValidVersion = false; } if (!isValidVersion) { throw new ConfigException("embulk-output-td v0.4.x+ only supports Embulk v0.8.22 or higher versions"); } }

Target:
private void checkEmbulkVersion() { boolean isValidVersion = true; try { Class.forName("org.embulk.EmbulkVersion"); String[] versionNumber = EmbulkVersion.VERSION.split("-"); if (versionNumber[0] != null) { String[] versions = versionNumber[0].split("\\."); if (versions.length == 3) { if (Integer.valueOf(versions[1]) <= 8 && Integer.valueOf(versions[2]) < 22) { isValidVersion = false; } } } } catch (ClassNotFoundException ex) { isValidVersion = false; } if (!isValidVersion) { throw new ConfigException("embulk-output-td v0.4.x+ only supports Embulk v0.8.22 or higher versions"); } }
Source:
public Map<TopicPartition, OffsetAndMetadata> getAcknowledged() throws InterruptedException { lock.writeLock().lock(); try { Map<TopicPartition, OffsetAndMetadata> currentOffsets = new HashMap<>(pendingOffsets.size()); currentOffsets.putAll(pendingOffsets); return currentOffsets; } finally { lock.writeLock().unlock(); } }

Target:
public Map<TopicPartition, OffsetAndMetadata> getAcknowledged() { Map<TopicPartition, OffsetAndMetadata> currentOffsets = new HashMap<>(offsets); return currentOffsets; }
Source:
public static boolean isAnyNotEmpty(final CharSequence... css) { if (ArrayUtils.isEmpty(css)) { return true; } for (final CharSequence cs : css){ if (isNotEmpty(cs)) { return true; } } return false; }

Target:
public static boolean isAnyNotEmpty(final CharSequence... css) { if (ArrayUtils.isEmpty(css)) { return false; } for (final CharSequence cs : css){ if (isNotEmpty(cs)) { return true; } } return false; }
Source:
public void testKeyWrapAndUnwrap() throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher keyWrapCipher = Cipher.getInstance("AESWrap/ECB/NoPadding"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); byte[] kek = new byte[16]; random.nextBytes(kek); byte[] randomKey = new byte[16]; random.nextBytes(randomKey); keyWrapCipher.init(Cipher.WRAP_MODE, new SecretKeySpec(kek, "AES")); Key randKey = new SecretKeySpec(randomKey, "AES"); byte[] wrappedKey = keyWrapCipher.wrap(randKey); assert (wrappedKey != null); assert (wrappedKey.length == randomKey.length + 8); Cipher keyUnwrapCipher = Cipher.getInstance("AESWrap/ECB/NoPadding"); keyUnwrapCipher.init(Cipher.UNWRAP_MODE, new SecretKeySpec(kek, "AES")); Key unwrappedKey = keyUnwrapCipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); byte[] unwrappedKeyBytes = unwrappedKey.getEncoded(); assert (Arrays.equals(unwrappedKeyBytes, randomKey)); }

Target:
public void testKeyWrapAndUnwrap() throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher keyWrapCipher = Cipher.getInstance("AESWrap/ECB/NoPadding"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); byte[] kek = new byte[16]; random.nextBytes(kek); byte[] randomKey = new byte[16]; random.nextBytes(randomKey); keyWrapCipher.init(Cipher.WRAP_MODE, new SecretKeySpec(kek, "AES")); Key randKey = new SecretKeySpec(randomKey, "AES"); byte[] wrappedKey = keyWrapCipher.wrap(randKey); assertNotNull(wrappedKey); assertEquals(wrappedKey.length, randomKey.length + 8); Cipher keyUnwrapCipher = Cipher.getInstance("AESWrap/ECB/NoPadding"); keyUnwrapCipher.init(Cipher.UNWRAP_MODE, new SecretKeySpec(kek, "AES")); Key unwrappedKey = keyUnwrapCipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); byte[] unwrappedKeyBytes = unwrappedKey.getEncoded(); assertArrayEquals(unwrappedKeyBytes, randomKey); }
Source:
CosmosItemResponse mapItemResponseAndBlock(Mono<CosmosAsyncItemResponse> itemMono) throws CosmosClientException { try { return itemMono .map(this::convertResponse) .block(); } catch (Exception ex) { final Throwable throwable = Exceptions.unwrap(ex); if (throwable instanceof CosmosClientException) { throw (CosmosClientException) throwable; } else { throw Exceptions.propagate(ex); } } }

Target:
CosmosItemResponse mapItemResponseAndBlock(Mono<CosmosAsyncItemResponse> itemMono) throws CosmosClientException { try { return itemMono .map(this::convertResponse) .block(); } catch (Exception ex) { final Throwable throwable = Exceptions.unwrap(ex); if (throwable instanceof CosmosClientException) { throw (CosmosClientException) throwable; } else { throw ex; } } }
Source:
public FileInputFormatter create(Map<String, String> properties, @Nullable Schema schema) { if (schema != null) { Schema.Field offsetField = schema.getField("offset"); if (offsetField != null) { Schema offsetSchema = offsetField.getSchema(); Schema.Type offsetType = offsetSchema.isNullable() ? offsetSchema.getNonNullable().getType() : offsetSchema.getType(); if (offsetType != Schema.Type.LONG) { throw new IllegalArgumentException("Type of 'offset' field must be 'long', but found " + offsetType); } } Schema.Field bodyField = schema.getField("body"); if (bodyField == null) { throw new IllegalArgumentException("Schema for text format must have a field named 'body'"); } Schema bodySchema = bodyField.getSchema(); Schema.Type bodyType = bodySchema.isNullable() ? bodySchema.getNonNullable().getType() : bodySchema.getType(); if (bodyType != Schema.Type.STRING) { throw new IllegalArgumentException("Type of 'body' field must be 'string', but found + " + bodyType); } } if (schema == null) { schema = getSchema(properties.get("pathField")); } return new TextInputFormatter(schema); }

Target:
public FileInputFormatter create(Map<String, String> properties, @Nullable Schema schema) { if (schema != null) { Schema.Field offsetField = schema.getField("offset"); if (offsetField != null) { Schema offsetSchema = offsetField.getSchema(); Schema.Type offsetType = offsetSchema.isNullable() ? offsetSchema.getNonNullable().getType() : offsetSchema.getType(); if (offsetType != Schema.Type.LONG) { throw new IllegalArgumentException("Type of 'offset' field must be 'long', but found " + offsetType); } } Schema.Field bodyField = schema.getField("body"); if (bodyField == null) { throw new IllegalArgumentException("Schema for text format must have a field named 'body'"); } Schema bodySchema = bodyField.getSchema(); Schema.Type bodyType = bodySchema.isNullable() ? bodySchema.getNonNullable().getType() : bodySchema.getType(); if (bodyType != Schema.Type.STRING) { throw new IllegalArgumentException("Type of 'body' field must be 'string', but found + " + bodyType); } } if (schema == null) { schema = getDefaultSchema(properties.get("pathField")); } return new TextInputFormatter(schema); }
Source:
private void initLogging() { String off = "OFF"; IEclipsePreferences prefs = getEMFComparePreferences(); LOGGER.setLevel(Level.toLevel(prefs.get(LOG_LEVEL_KEY, off))); if (off.equals(LOGGER.getLevel().toString())) { return; } RollingFileAppender appender = (RollingFileAppender)LOGGER.getAppender(EMFC_APPENDER_NAME); String logFileName = prefs.get(LOG_FILENAME_KEY, ""); if (logFileName.length() > 0) { if (appender == null) { try { createLogAppender(logFileName); } catch (IOException e) { prefs.put(LOG_FILENAME_KEY, ""); } } else { appender.setMaxBackupIndex(prefs.getInt(LOG_BACKUP_COUNT_KEY, 10)); appender.setMaximumFileSize((prefs.getInt(LOG_FILE_MAX_SIZE_KEY, 100)) * MEGABYTE); } } preferenceChangeListener = new LoggingPreferenceChangeListener(); prefs.addPreferenceChangeListener(preferenceChangeListener); }

Target:
private void initLogging() { IEclipsePreferences prefs = getEMFComparePreferences(); LOGGER.setLevel(Level.toLevel(prefs.get(LOG_LEVEL_KEY, "OFF"))); if (Level.OFF.equals(LOGGER.getLevel())) { RollingFileAppender appender = (RollingFileAppender)LOGGER.getAppender(EMFC_APPENDER_NAME); String logFileName = prefs.get(LOG_FILENAME_KEY, ""); if (logFileName.length() > 0) { if (appender == null) { try { createLogAppender(logFileName); } catch (IOException e) { prefs.put(LOG_FILENAME_KEY, ""); } } else { appender.setMaxBackupIndex(prefs.getInt(LOG_BACKUP_COUNT_KEY, 10)); appender.setMaximumFileSize((prefs.getInt(LOG_FILE_MAX_SIZE_KEY, 100)) * MEGABYTE); } } } preferenceChangeListener = new LoggingPreferenceChangeListener(); prefs.addPreferenceChangeListener(preferenceChangeListener); }
Source:
public int copyResource(String resource, String target) { String dest = target; if (!new File(target).isAbsolute()) { dest = getRunDir() + "/" + target; } int result = -1; if (resource.toLowerCase().matches("^https?://.*")) { result = getMachine().execCommands("download", ImmutableList.of( CommonCommands.INSTALL_CURL, String.format("curl --silent --insecure %s -o %s", resource, dest))); } if (result != 0) { result = getMachine().copyTo(getResource(resource), dest); } if (log.isDebugEnabled()) log.debug("Copied file for {}: to - result {}", new Object[] { entity, resource, dest, result }); return result; }

Target:
public int copyResource(String resource, String target) { return copyResource(MutableMap.of(), resource, target); }
Source:
public List<String> getArchivedCourseIds(List<CourseDetailsBundle> allCourses, List<InstructorAttributes> instructorList) { List<String> activeCourseIds = new ArrayList<String>(); for (CourseDetailsBundle cdb : allCourses) { if (cdb.course.isArchived) { activeCourseIds.add(cdb.course.id); } } for (InstructorAttributes instructor : instructorList) { if (instructor.isArchived != null && instructor.isArchived == true) { activeCourseIds.add(instructor.courseId); } } return activeCourseIds; }

Target:
public List<String> getArchivedCourseIds(List<CourseDetailsBundle> allCourses, List<InstructorAttributes> instructorList) { List<String> archivedCourseIds = new ArrayList<String>(); for (CourseDetailsBundle cdb : allCourses) { if (cdb.course.isArchived) { archivedCourseIds.add(cdb.course.id); } } for (InstructorAttributes instructor : instructorList) { if (instructor.isArchived != null && instructor.isArchived == true) { archivedCourseIds.add(instructor.courseId); } } return archivedCourseIds; }