auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<Path> getFilePathsForArchive(String experimentAccession, ExperimentFileType fileType) { switch (fileType) { case QUANTIFICATION_FILTERED: return Arrays.asList( dataFileHub.getSingleCellExperimentFiles(experimentAccession).tpmsMatrix.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).cellIdsTsv.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).geneIdsTsv.getPath()); case MARKER_GENES: return dataFileHub.getSingleCellExperimentFiles(experimentAccession).markerGeneTsvs .values() .stream() .map(AtlasResource::getPath) .collect(Collectors.toList()); case QUANTIFICATION_RAW: return Arrays.asList( dataFileHub.getSingleCellExperimentFiles(experimentAccession).filteredCountsMatrix.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).filteredCountsCellIdsTsv.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).filteredCountsGeneIdsTsv.getPath()); case NORMALISED: return Arrays.asList( dataFileHub.getSingleCellExperimentFiles(experimentAccession).normalisedCountsMatrix.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).normalisedCountsCellIdsTsv.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).normalisedCountsGeneIdsTsv.getPath()); default: return null; } }

Target:
public List<Path> getFilePathsForArchive(String experimentAccession, ExperimentFileType fileType) { switch (fileType) { case QUANTIFICATION_FILTERED: return ImmutableList.of( dataFileHub.getSingleCellExperimentFiles(experimentAccession).tpmsMatrix.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).cellIdsTsv.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).geneIdsTsv.getPath()); case MARKER_GENES: return dataFileHub.getSingleCellExperimentFiles(experimentAccession).markerGeneTsvs .values() .stream() .map(AtlasResource::getPath) .collect(Collectors.toList()); case QUANTIFICATION_RAW: return ImmutableList.of( dataFileHub.getSingleCellExperimentFiles(experimentAccession).filteredCountsMatrix.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).filteredCountsCellIdsTsv.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).filteredCountsGeneIdsTsv.getPath()); case NORMALISED: return ImmutableList.of( dataFileHub.getSingleCellExperimentFiles(experimentAccession).normalisedCountsMatrix.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).normalisedCountsCellIdsTsv.getPath(), dataFileHub.getSingleCellExperimentFiles(experimentAccession).normalisedCountsGeneIdsTsv.getPath()); default: return null; } }
Source:
public static OseeDslResource loadModel(String uri, String xTextData) throws Exception { OseeDslResource displayLogicResource = loadModelUnchecked(uri, xTextData); for (String error : displayLogicResource.getErrors()) { throw new IllegalStateException(error); } return displayLogicResource; }

Target:
public static OseeDslResource loadModel(String uri, String xTextData) throws Exception { OseeDslResource displayLogicResource = loadModelUnchecked(uri, xTextData); checkErrorsEmpty(displayLogicResource.getErrors()); return displayLogicResource; }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_account, container, false); TextView editText = (TextView) rootView.findViewById(R.id.account_name); editText.setText(name); editText = (TextView) rootView.findViewById(R.id.account_email); editText.setText(email); editText = (TextView) rootView.findViewById(R.id.account_organization); editText.setText(organization); return rootView; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_account, container, false); nameText = (TextView) rootView.findViewById(R.id.account_name); nameText.setText(name); emailText = (TextView) rootView.findViewById(R.id.account_email); emailText.setText(email); organizationText = (TextView) rootView.findViewById(R.id.account_organization); organizationText.setText(organization); return rootView; }
Source:
public BooleanWrapper configure(Object... policyParameters) { super.configure(policyParameters); if (policyParameters[2] == null) { throw new IllegalArgumentException("Scheduler url must be specified"); } schedulerUrl = policyParameters[2].toString(); if (policyParameters[3] == null) { try { policyParameters[3] = nodeSource.getAdministrator().getCredentials().getBase64(); } catch (KeyException e) { logger.info("Cannot use default admin credentials.", e); } } credentials = (byte[]) policyParameters[3]; if (policyParameters[4] == null) { schedulerAwarePolicyNodeSourceRecoveryDelay = PAResourceManagerProperties.RM_SCHEDULER_AWARE_POLICY_NODESOURCE_RECOVERY_TIMEOUT.getValueAsLong(); } if (policyParameters[5] == null) { schedulerAwarePolicyNodeSourceRecoveryTrialsNumber = PAResourceManagerProperties.RM_SCHEDULER_AWARE_POLICY_NODESOURCE_RECOVERY_TRIAL_NUMBER.getValueAsInt(); } return new BooleanWrapper(true); }

Target:
public BooleanWrapper configure(Object... policyParameters) { super.configure(policyParameters); if (policyParameters[2] == null) { throw new IllegalArgumentException("Scheduler url must be specified"); } schedulerUrl = policyParameters[2].toString(); credentials = (byte[]) policyParameters[3]; if (policyParameters[4] == null) { schedulerAwarePolicyNodeSourceRecoveryDelay = PAResourceManagerProperties.RM_SCHEDULER_AWARE_POLICY_NODESOURCE_RECOVERY_TIMEOUT.getValueAsLong(); } if (policyParameters[5] == null) { schedulerAwarePolicyNodeSourceRecoveryTrialsNumber = PAResourceManagerProperties.RM_SCHEDULER_AWARE_POLICY_NODESOURCE_RECOVERY_TRIAL_NUMBER.getValueAsInt(); } return new BooleanWrapper(true); }
Source:
public void close() { try { hazelcastCluster.close(); } catch (HazelcastInstanceNotActiveException e) { LOGGER.debug("Unable to close Hazelcast cluster", e); } }

Target:
public void close() { hazelcastCluster.close(); }
Source:
public ArrayList<OCShare> getPublicSharesForAFile(String filePath, String accountName){ String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND " + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?"+ "AND" + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? "; String whereArgs = new String[]{ filePath, accountName , Integer.toString(ShareType.PUBLIC_LINK.getValue())}; Cursor c = null; if (getContentResolver() != null) { c = getContentResolver().query( ProviderTableMeta.CONTENT_URI_SHARE, null, where, whereArgs, null); } else { try { c = getContentProviderClient().query( ProviderTableMeta.CONTENT_URI_SHARE, null, where, whereArgs, null); } catch (RemoteException e) { Log_OC.e(TAG, "Could not get list of shares with: " + e.getMessage()); c = null; } } ArrayList<OCShare> shares = new ArrayList<>(); OCShare share = null; if (c != null) { if (c.moveToFirst()) { do { share = createShareInstance(c); shares.add(share); } while (c.moveToNext()); } c.close(); } return shares; }

Target:
public ArrayList<OCShare> getPublicSharesForAFile(String filePath, String accountName){ String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND " + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?"+ "AND" + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? "; String whereArgs = new String[]{ filePath, accountName , Integer.toString(ShareType.PUBLIC_LINK.getValue())}; Cursor c; if (getContentResolver() != null) { c = getContentResolver().query( ProviderTableMeta.CONTENT_URI_SHARE, null, where, whereArgs, null); } else { try { c = getContentProviderClient().query( ProviderTableMeta.CONTENT_URI_SHARE, null, where, whereArgs, null); } catch (RemoteException e) { Log_OC.e(TAG, "Could not get list of shares with: " + e.getMessage()); c = null; } } ArrayList<OCShare> publicShares = new ArrayList<>(); OCShare publicShare; if (c != null) { if (c.moveToFirst()) { do { publicShare = createShareInstance(c); publicShares.add(publicShare); } while (c.moveToNext()); } c.close(); } return publicShares; }
Source:
public void onMapReady(@NonNull final MapboxMap mapboxMap) { MarathonExtrusionActivity.this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.SATELLITE, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { GeoJsonSource courseRouteGeoJson = new GeoJsonSource( "coursedata", loadJsonFromAsset("marathon_route.geojson")); mapboxMap.getStyle().addSource(courseRouteGeoJson); addExtrusionsLayerToMap(); } }); }

Target:
public void onMapReady(@NonNull final MapboxMap mapboxMap) { mapboxMap.setStyle(Style.SATELLITE, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { GeoJsonSource courseRouteGeoJson = new GeoJsonSource( "coursedata", loadJsonFromAsset("marathon_route.geojson")); style.addSource(courseRouteGeoJson); addExtrusionsLayerToMap(style); } }); }
Source:
private int getSeekDuration() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final String key = context.getString(R.string.seek_duration_key); final String value = prefs.getString(key, FAST_FORWARD_REWIND_DEFAULT_AMOUNT_MILLIS); return Integer.parseInt(value); }

Target:
private int getSeekDuration() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final String key = context.getString(R.string.seek_duration_key); final String value = prefs.getString(key, context.getString(R.string.seek_duration_default_value)); return Integer.parseInt(value); }
Source:
public Iterable<Server> listNodesByIds(final Iterable<String> ids) { return Iterables.filter(listNodes(), new Predicate<Server>() { @Override public boolean apply(Server server) { return Iterables.contains(ids, server.getId()); } }); }

Target:
public Iterable<Server> listNodesByIds(final Iterable<String> ids) { return filter(listNodes(), new Predicate<Server>() { @Override public boolean apply(Server server) { return contains(ids, server.getId()); } }); }
Source:
void validate(QueryType qt, MappingManager manager) { checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET, "Consistency level option is only allowed in save, delete and get queries"); }

Target:
void validate(QueryType qt, MappingManager manager) { }
Source:
private void restoreDialog() { IDialogSettings dialogSettings = getDialogSettings(); if (dialogSettings != null) { try { dialogHeight = dialogSettings.getInt(DIALOG_HEIGHT); dialogWidth = dialogSettings.getInt(DIALOG_WIDTH); } catch (NumberFormatException e) { dialogHeight = -1; dialogWidth = -1; } String[] orderedProviders = dialogSettings.getArray(ORDERED_PROVIDERS); previousPicksList.addAll(Arrays.asList(new QuickAccessElement[orderedProviders.length])); isLoadingPreviousElements = true; refreshQuickAccessContents = new UIJob("Finish restoring quick access elements") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { boolean restoreUiElements = true; restoreDialogEntries(dialogSettings, restoreUiElements, monitor); quickAccessContents.refresh(quickAccessContents.filterText.getText()); synchronized (previousPicksList) { List<QuickAccessElement> previousPicks = previousPicksList.stream().filter(Objects::nonNull) .collect(Collectors.toList()); previousPicksList.clear(); previousPicksList.addAll(previousPicks); } return Status.OK_STATUS; } }; refreshQuickAccessContents.setSystem(true); restoreDialogEntriesJob = Job.createSystem("Restore quick access elements", (IProgressMonitor monitor) -> { try { boolean restoreUiElements = false; restoreDialogEntries(dialogSettings, restoreUiElements, monitor); return Status.OK_STATUS; } catch (OperationCanceledException e) { return Status.CANCEL_STATUS; } finally { isLoadingPreviousElements = false; refreshQuickAccessContents.schedule(); } }); restoreDialogEntriesJob.schedule(); } }

Target:
private void restoreDialog() { IDialogSettings dialogSettings = getDialogSettings(); if (dialogSettings != null) { try { dialogHeight = dialogSettings.getInt(DIALOG_HEIGHT); dialogWidth = dialogSettings.getInt(DIALOG_WIDTH); } catch (NumberFormatException e) { dialogHeight = -1; dialogWidth = -1; } String[] orderedProviders = dialogSettings.getArray(ORDERED_PROVIDERS); previousPicksList.addAll(Arrays.asList(new QuickAccessElement[orderedProviders.length])); isLoadingPreviousElements = true; refreshQuickAccessContents = new UIJob("Finish restoring quick access elements") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { boolean restoreUiElements = true; restoreDialogEntries(dialogSettings, restoreUiElements, monitor); quickAccessContents.refresh(quickAccessContents.filterText.getText()); List<QuickAccessElement> previousPicks = getLoadedPreviousPicks(); previousPicksList.clear(); previousPicksList.addAll(previousPicks); return Status.OK_STATUS; } }; refreshQuickAccessContents.setSystem(true); restoreDialogEntriesJob = Job.createSystem("Restore quick access elements", (IProgressMonitor monitor) -> { try { boolean restoreUiElements = false; restoreDialogEntries(dialogSettings, restoreUiElements, monitor); return Status.OK_STATUS; } catch (OperationCanceledException e) { return Status.CANCEL_STATUS; } finally { isLoadingPreviousElements = false; refreshQuickAccessContents.schedule(); } }); restoreDialogEntriesJob.schedule(); } }
Source:
public void testBucketCount() throws InterruptedException { String regionName = "testCreateRegion"; gfsh.executeAndAssertThat("create region" + " --name=" + regionName + " --type=PARTITION_PERSISTENT" + " --total-num-buckets=1000").statusIsSuccess(); gfsh.executeAndAssertThat("query --query=\"select * from /" + regionName + "\"") .statusIsSuccess(); server1.invoke(() -> waitBucketsToInitialize(245)); server2.invoke(() -> waitBucketsToInitialize(245)); server3.invoke(() -> waitBucketsToInitialize(245)); server4.invoke(() -> waitBucketsToInitialize(245)); for (int i = 1; i < 4; i++) { final String tempname = "/" + regionName + i; gfsh.executeAndAssertThat("create region" + " --name=" + regionName + i + " --type=PARTITION_PERSISTENT" + " --total-num-buckets=1000" + " --colocated-with=" + regionName).statusIsSuccess(); } server1.invoke(() -> waitBucketsToInitialize(990)); server2.invoke(() -> waitBucketsToInitialize(990)); server3.invoke(() -> waitBucketsToInitialize(990)); server4.invoke(() -> waitBucketsToInitialize(990)); }

Target:
public void testBucketCount() { String regionName = "testCreateRegion"; gfsh.executeAndAssertThat("create region" + " --name=" + regionName + " --type=PARTITION_PERSISTENT" + " --total-num-buckets=1000").statusIsSuccess(); server1.invoke(() -> createBuckets(regionName)); server2.invoke(() -> createBuckets(regionName)); server3.invoke(() -> createBuckets(regionName)); server4.invoke(() -> createBuckets(regionName)); await().untilAsserted(() -> { final int sumOfBuckets = server1.invoke(() -> getBucketsInitialized()) + server2.invoke(() -> getBucketsInitialized()) + server3.invoke(() -> getBucketsInitialized()) + server4.invoke(() -> getBucketsInitialized()); assertEquals("Expected bucket count is 1000, and actual count is " + sumOfBuckets, sumOfBuckets, 1000); }); for (int i = 1; i < 4; i++) { gfsh.executeAndAssertThat("create region" + " --name=" + regionName + i + " --type=PARTITION_PERSISTENT" + " --total-num-buckets=1000" + " --colocated-with=" + regionName).statusIsSuccess(); } await().untilAsserted(() -> { final int sumOfBuckets = server1.invoke(() -> getBucketsInitialized()) + server2.invoke(() -> getBucketsInitialized()) + server3.invoke(() -> getBucketsInitialized()) + server4.invoke(() -> getBucketsInitialized()); assertEquals("Expected bucket count is 4000, and actual count is " + sumOfBuckets, sumOfBuckets, 4000); }); }
Source:
public void setupController() throws InterruptedException { container = ServiceContainer.Factory.create("test"); final TestFutureServiceContainer fsc = new TestFutureServiceContainer(container); ServiceBuilder<AsyncFuture<ServiceContainer>> containerBuilder = container.addService(Services.JBOSS_AS, new Service<AsyncFuture<ServiceContainer>>() { public void start(StartContext context) throws StartException { } public void stop(StopContext context) { } public AsyncFuture<ServiceContainer> getValue() throws IllegalStateException, IllegalArgumentException { return fsc; } }); containerBuilder.install(); ServiceTarget target = container.subTarget(); ModelControllerService svc = new ModelControllerService(processType, getAuditLogger(), getAuthorizer()); ServiceBuilder<ModelController> builder = target.addService(Services.JBOSS_SERVER_CONTROLLER, svc); builder.install(); svc.awaitStartup(30, TimeUnit.SECONDS); controller = svc.getValue(); }

Target:
public void setupController() throws InterruptedException { container = ServiceContainer.Factory.create("test"); ServiceTarget target = container.subTarget(); ModelControllerService svc = new ModelControllerService(processType, getAuditLogger(), getAuthorizer()); ServiceBuilder<ModelController> builder = target.addService(Services.JBOSS_SERVER_CONTROLLER, svc); builder.install(); svc.awaitStartup(30, TimeUnit.SECONDS); controller = svc.getValue(); }
Source:
public void updateUserEmail(String oldEmail, String newEmail) throws BusinessException { verifyEmail(newEmail); try { CoreDAOFactory.getDAOFactory().getUserDAO().updateEmail(oldEmail, newEmail); updatePublicationOwner(oldEmail, newEmail); } catch (DAOException e) { throw new BusinessException(e); } }

Target:
public void updateUserEmail(String oldEmail, String newEmail) throws BusinessException { verifyEmail(newEmail); try { CoreDAOFactory.getDAOFactory().getUserDAO().updateEmail(oldEmail, newEmail); } catch (DAOException e) { String errorMessage = "Error changing email from " + newEmail + " to " + newEmail; logger.error(errorMessage, e); sendErrorEmailToAdmins(errorMessage, e, oldEmail); throw new BusinessException("Error changing email address", e); } try { updatePublicationOwner(oldEmail, newEmail); } catch (BusinessException e) { String errorMessage = "Error changing email from " + newEmail + " to " + newEmail + "in the Publication table"; logger.error(errorMessage, e); sendErrorEmailToAdmins(errorMessage, e, oldEmail); } }
Source:
public void delete() throws Exception { this.sequentialFile.delete(); }

Target:
public void delete() throws IOException, InterruptedException, ActiveMQException { this.sequentialFile.delete(); }
Source:
protected CompletionStage<Object> totalOrderPrepare(TxInvocationContext<?> ctx, PrepareCommand command, Collection<Address> recipients) { try { CompletionStage<Map<Address, Response>> remoteInvocation; if (recipients != null) { Set<Address> realRecipients; realRecipients = new HashSet<>(recipients); realRecipients.add(rpcManager.getAddress()); remoteInvocation = rpcManager.invokeCommand(realRecipients, command, new MapResponseCollector(true, realRecipients.size()), rpcManager.getTotalSyncRpcOptions()); } else { remoteInvocation = rpcManager.invokeCommandOnAll(command, new MapResponseCollector(true), rpcManager.getTotalSyncRpcOptions()); } return remoteInvocation.handle((responses, t) -> { transactionRemotelyPrepared(ctx); CompletableFutures.rethrowException(t); return null; }); } catch (Throwable t) { transactionRemotelyPrepared(ctx); throw t; } }

Target:
protected CompletionStage<Object> totalOrderPrepare(TxInvocationContext<?> ctx, PrepareCommand command, Collection<Address> recipients) { try { CompletionStage<Map<Address, Response>> remoteInvocation; if (recipients != null) { Set<Address> realRecipients = new HashSet<>(recipients); realRecipients.add(rpcManager.getAddress()); remoteInvocation = rpcManager.invokeCommand(realRecipients, command, new MapResponseCollector(true, realRecipients.size()), rpcManager.getTotalSyncRpcOptions()); } else { remoteInvocation = rpcManager.invokeCommandOnAll(command, new MapResponseCollector(true), rpcManager.getTotalSyncRpcOptions()); } return remoteInvocation.handle((responses, t) -> { transactionRemotelyPrepared(ctx); CompletableFutures.rethrowException(t); return null; }); } catch (Throwable t) { transactionRemotelyPrepared(ctx); throw t; } }
Source:
public static String getTempDirectory() { final String basedir = System.getenv("STRONGBOX_TMP") != null ? System.getenv("STRONGBOX_TMP") : System.getProperty("strongbox.tmp"); if (basedir != null) { return new File(basedir).getAbsolutePath(); } else { return new File("./tmp").getAbsolutePath(); } }

Target:
public static String getTempDirectory() { final String basedir = System.getenv("STRONGBOX_TMP") != null ? System.getenv("STRONGBOX_TMP") : System.getProperty("strongbox.tmp"); if (basedir != null) { return new File(basedir).getAbsolutePath(); } else { return new File("tmp").getAbsolutePath(); } }
Source:
public ObservableValue<String> getFields(OrFields fields) { ObservableValue<String> value = fieldValues.get(fields); if (value != null) { return value; } else { value = Bindings.createStringBinding(() -> { boolean isName = false; Optional<String> content = Optional.empty(); Field anEntry = null; for (Field field : fields) { content = entry.getResolvedFieldOrAliasLatexFree(field, database); if (content.isPresent()) { anEntry = field; isName = field.getProperties().contains(FieldProperty.PERSON_NAMES); break; } } String result = content.orElse(null); if (isName) { String latexFreeBeforeNameFormatter = nameFormatter.formatName(result); String unformattedName = entry.getResolvedFieldOrAlias(anEntry, database).orElse(null); String formattedName = nameFormatter.formatName(unformattedName); String latexFreeAfterNameFormatter = new LatexToUnicodeFormatter().format(formattedName); if (!latexFreeAfterNameFormatter.equals(latexFreeBeforeNameFormatter)) { LOGGER.info("latexFreeBeforeNameFormatter = " + latexFreeBeforeNameFormatter); LOGGER.info("latexFreeAfterNameFormatter = " + latexFreeAfterNameFormatter); } return latexFreeAfterNameFormatter; } else { return result; } }, entry.getObservables()); fieldValues.put(fields, value); return value; } }

Target:
public ObservableValue<String> getFields(OrFields fields) { ObservableValue<String> value = fieldValues.get(fields); if (value != null) { return value; } value = Bindings.createStringBinding(() -> { for (Field field : fields) { if (field.getProperties().contains(FieldProperty.PERSON_NAMES)) { Optional<String> name = entry.getResolvedFieldOrAlias(field, database); if (name.isPresent()) { return nameFormatter.formatNameLatexFree(name.get()); } } else { Optional<String> content = entry.getResolvedFieldOrAliasLatexFree(field, database); if (content.isPresent()) { return content.get(); } } } return ""; }, entry.getObservables()); fieldValues.put(fields, value); return value; }
Source:
Properties loadMigrationProperties() { try { return AccessUtils.doPrivileged( () -> { try (InputStream inputStream = new FileInputStream( Paths.get( System.getProperty(ConfigurationMigrationManager.DDF_HOME_KEY), "etc", ConfigurationMigrationManager.MIGRATION_PROPERTIES_FILENAME) .toString())) { Properties props = new Properties(); props.load(inputStream); return props; } }); } catch (IOException e) { LOGGER.error( String.format( "unable to load migration properties from '%s'; ", ConfigurationMigrationManager.MIGRATION_PROPERTIES_FILENAME), e); throw new IOError(e); } }

Target:
private static Properties loadMigrationProperties() throws IOException { try (InputStream inputStream = new FileInputStream( Paths.get( System.getProperty(ConfigurationMigrationManager.DDF_HOME_KEY), "etc", ConfigurationMigrationManager.MIGRATION_PROPERTIES_FILENAME) .toString())) { Properties props = new Properties(); props.load(inputStream); return props; } }
Source:
private Map<String, List<String>> getNodeIdToDependencies() { Map<String, List<String>> result = new HashMap<String, List<String>>(); try { Graph stageGraph = queryPlan.getQueryPlan().getStageGraph(); if (stageGraph == null) { return result; } List<Adjacency> adjacencies = stageGraph.getAdjacencyList(); if (adjacencies == null) { return result; } for (Adjacency adj : adjacencies) { String nodeId = AmbroseHiveUtil.getNodeIdFromNodeName(conf, adj.getNode()); if (!nodeIdToDAGNode.containsKey(nodeId)) { continue; } List<String> children = adj.getChildren(); if (children == null || children.isEmpty()) { return result; } List<String> filteredAdjacencies = getMRAdjacencies(children, nodeIdToDAGNode); result.put(nodeId, filteredAdjacencies); } } catch (IOException e) { LOG.error("Couldn't get queryPlan!", e); } return result; }

Target:
private Map<String, List<String>> getNodeIdToDependencies() { Map<String, List<String>> result = Maps.newHashMap(); try { Graph stageGraph = queryPlan.getQueryPlan().getStageGraph(); if (stageGraph == null) { return result; } List<Adjacency> adjacencies = stageGraph.getAdjacencyList(); if (adjacencies == null) { return result; } for (Adjacency adj : adjacencies) { String nodeId = AmbroseHiveUtil.getNodeIdFromNodeName(conf, adj.getNode()); if (!nodeIdToDAGNode.containsKey(nodeId)) { continue; } List<String> children = adj.getChildren(); if (children == null || children.isEmpty()) { return result; } List<String> filteredAdjacencies = getMRAdjacencies(children, nodeIdToDAGNode); result.put(nodeId, filteredAdjacencies); } } catch (IOException e) { LOG.error("Couldn't get queryPlan!", e); } return result; }
Source:
public DateGsonConverter() { this.iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); }

Target:
public DateGsonConverter() { this.iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); }
Source:
public Response getAccessToken(@Context HttpHeaders httpHeaders, MultivaluedMap<String, String> tokenRequestParams) { tokenReqCount++; String basicHeader = httpHeaders.getHeaderString("Authorization"); if (validateCredentials(basicHeader, tokenRequestParams)) { return Response.status(200).entity(new Token(Constants.accessToken, Constants.expiresIn, Constants.tokenType)).build(); } return Response.status(401).entity("Invalid Credentials").build(); }

Target:
public Response getAccessToken(@Context HttpHeaders httpHeaders, MultivaluedMap<String, String> tokenRequestParams) { tokenReqCount++; String basicHeader = httpHeaders.getHeaderString("Authorization"); if (validateCredentials(basicHeader, tokenRequestParams)) { return Response.status(Response.Status.OK).entity(new Token(Constants.accessToken, Constants.expiresIn, Constants.tokenType)).build(); } return Response.status(Response.Status.UNAUTHORIZED).entity("Invalid Credentials").build(); }
Source:
public void testUpdateReadOnlyPropertyOnChange() { final UpdateVmDiskParameters parameters = createParameters(); parameters.getDiskInfo().setReadOnly(true); when(diskDao.get(diskImageGuid)).thenReturn(createDiskImage()); VmDevice device = createVmDevice(diskImageGuid, vmId); initializeCommand(parameters); command.executeVmCommand(); device.setIsReadOnly(true); verify(vmDeviceDAO, times(1)).update(device); }

Target:
public void testUpdateReadOnlyPropertyOnChange() { final UpdateVmDiskParameters parameters = createParameters(); parameters.getDiskInfo().setReadOnly(true); when(diskDao.get(diskImageGuid)).thenReturn(createDiskImage()); initializeCommand(parameters); VmDevice vmDevice = stubVmDevice(diskImageGuid, vmId); command.executeVmCommand(); verify(command, atLeast(1)).updateReadOnlyRequested(); assertTrue(command.updateReadOnlyRequested()); verify(vmDeviceDAO).update(any(VmDevice.class)); }
Source:
public SwiftAccessIO getSwiftObject() { try { DataFileIO dataFileIO = getFile().getDataFileIO(); try { SwiftAccessIO swiftIO = (SwiftAccessIO)dataFileIO; return swiftIO; } catch (Exception e){ e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } return null; }

Target:
public SwiftAccessIO getSwiftObject() { try { StorageIO<DataFile> storageIO = getFile().getStorageIO(); if (storageIO != null && storageIO instanceof SwiftAccessIO) { return (SwiftAccessIO)storageIO; } else { logger.fine("FilePage: Failed to cast storageIO as SwiftAccessIO"); } } catch (IOException e) { logger.fine("FilePage: Failed to get storageIO"); } return null; }
Source:
public void createFromString() { String socketString = "Amqpwebsockets"; AmqpTransportType actual = AmqpTransportType.fromString(socketString); actual.toString(); Assertions.assertEquals(AmqpTransportType.AMQP_WEB_SOCKETS, actual); }

Target:
public void createFromString() { String socketString = "Amqpwebsockets"; AmqpTransportType actual = AmqpTransportType.fromString(socketString); Assertions.assertEquals(AmqpTransportType.AMQP_WEB_SOCKETS, actual); }
Source:
CacheUpdateMasterWork(Configuration conf, boolean shouldRunPrewarm) { this.shouldRunPrewarm = shouldRunPrewarm; String rawStoreClassName = MetastoreConf.getVar(conf, ConfVars.CACHED_RAW_STORE_IMPL, ObjectStore.class.getName()); try { rawStore = JavaUtils.getClass(rawStoreClassName, RawStore.class).newInstance(); rawStore.setConf(conf); } catch (InstantiationException | IllegalAccessException | MetaException e) { throw new RuntimeException("Cannot instantiate " + rawStoreClassName, e); } List<TransactionalMetaStoreEventListener> transactionalListeners = null; try { transactionalListeners = MetaStoreServerUtils.getMetaStoreListeners(TransactionalMetaStoreEventListener.class, conf, MetastoreConf.getVar(conf, ConfVars.TRANSACTIONAL_EVENT_LISTENERS)); } catch (MetaException e) { throw new RuntimeException("Failed getting notification listeners", e); } if (!transactionalListeners.isEmpty()) { canUseEvents = true; } }

Target:
CacheUpdateMasterWork(Configuration conf, boolean shouldRunPrewarm) { this.shouldRunPrewarm = shouldRunPrewarm; String rawStoreClassName = MetastoreConf.getVar(conf, ConfVars.CACHED_RAW_STORE_IMPL, ObjectStore.class.getName()); try { rawStore = JavaUtils.getClass(rawStoreClassName, RawStore.class).newInstance(); rawStore.setConf(conf); } catch (InstantiationException | IllegalAccessException | MetaException e) { throw new RuntimeException("Cannot instantiate " + rawStoreClassName, e); } }
Source:
public void postCollectionDefaultBitstreamReadGroupCreateDefaultBitstreamReadGroupUnProcessablePermanent() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); groupRest.setPermanent(true); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); }

Target:
public void postCollectionDefaultBitstreamReadGroupCreateDefaultBitstreamReadGroupUnProcessablePermanent() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); groupRest.setPermanent(true); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); Group anon = groupService.findByName(context, Group.ANONYMOUS); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup")) .andExpect(status().isOk()) .andExpect( jsonPath("$", GroupMatcher.matchGroupEntry(anon.getID(), anon.getName()))); }
Source:
public synchronized void acquireWakeLock(int lockLevel) { if (wakelock != null) { if (wakelock.isHeld()) { wakelock.release(); } } PowerManager pm = (PowerManager)boundActivity.getSystemService(Context.POWER_SERVICE); wakelock = pm.newWakeLock(lockLevel, "CommCareLock"); wakelock.acquire(); }

Target:
public synchronized void acquireWakeLock(int lockLevel) { releaseWakeLock(); PowerManager pm = (PowerManager)boundActivity.getSystemService(Context.POWER_SERVICE); wakelock = pm.newWakeLock(lockLevel, "CommCareLock"); wakelock.acquire(); }
Source:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitMethodDeclaration(@NotNull GoMethodDeclaration o) { super.visitMethodDeclaration(o); visitDeclaration(holder, o.getSignature(), "Method"); } @Override public void visitFunctionDeclaration(@NotNull GoFunctionDeclaration o) { super.visitFunctionDeclaration(o); if (GoTestFinder.isTestFile(o.getContainingFile()) && GoTestFunctionType.fromName(o.getName()) != null) { return; } visitDeclaration(holder, o.getSignature(), "Function"); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { super.visitFunctionLit(o); visitDeclaration(holder, o.getSignature(), "Closure"); } }; }

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitMethodDeclaration(@NotNull GoMethodDeclaration o) { super.visitMethodDeclaration(o); visitDeclaration(holder, o.getSignature(), "Method"); } @Override public void visitFunctionDeclaration(@NotNull GoFunctionDeclaration o) { super.visitFunctionDeclaration(o); visitDeclaration(holder, o.getSignature(), "Function"); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { super.visitFunctionLit(o); visitDeclaration(holder, o.getSignature(), "Closure"); } }; }
Source:
public Future<PlanResult> execute(final Plan plan) { return mainExecutor.submit(new Callable<PlanResult>() { @Override public PlanResult call() throws Exception { if (plan.getEvaluatorsToAdd().isEmpty() && plan.getTransferSteps().isEmpty()) { return new PlanResultImpl(); } executingPlan = new ExecutingPlan(plan); for (final String evaluatorToAdd : plan.getEvaluatorsToAdd()) { LOG.log(Level.INFO, "Add new evaluator {0}", evaluatorToAdd); elasticMemory.add(1, evalSize, 1, new ContextActiveHandler()); } executingPlan.awaitActiveContexts(); LOG.log(Level.INFO, "All evaluators were added, will transfer data."); try { for (final TransferStep transferStep : plan.getTransferSteps()) { elasticMemory.move( transferStep.getDataInfo().getDataType(), transferStep.getDataInfo().getNumUnits(), transferStep.getSrcId(), executingPlan.getActualContextId(transferStep.getDstId()), new DataTransferredHandler(), new MovedHandler()); } } catch (final Exception e) { LOG.log(Level.WARNING, "Caught Exception, closing Evaluators.", e); executingPlan.onSynchronizedExecutionFailed(); } executingPlan.awaitDataTransfers(); LOG.log(Level.INFO, "All data transfers were completed, will submit evaluators and applyUpdates on pause."); driverSync.execute(new SynchronizedExecutionHandler(executingPlan), new SynchronizedExecutionFailedHandler(executingPlan)); executingPlan.awaitSynchronizedExecution(); executingPlan = null; return new PlanResultImpl(); } }); }

Target:
public Future<PlanResult> execute(final Plan plan) { return mainExecutor.submit(new Callable<PlanResult>() { @Override public PlanResult call() throws Exception { if (plan.getEvaluatorsToAdd().isEmpty() && plan.getTransferSteps().isEmpty() && plan.getEvaluatorsToDelete().isEmpty()) { return new PlanResultImpl(); } executingPlan = new ExecutingPlan(plan); for (final String evaluatorToAdd : plan.getEvaluatorsToAdd()) { LOG.log(Level.INFO, "Add new evaluator {0}", evaluatorToAdd); elasticMemory.add(1, evalSize, 1, new ContextActiveHandler()); } executingPlan.awaitActiveContexts(); LOG.log(Level.INFO, "All evaluators were added, will transfer data."); try { for (final TransferStep transferStep : plan.getTransferSteps()) { elasticMemory.move( transferStep.getDataInfo().getDataType(), transferStep.getDataInfo().getNumUnits(), transferStep.getSrcId(), executingPlan.getActualContextId(transferStep.getDstId()), new DataTransferredHandler(), new MovedHandler()); } } catch (final Exception e) { LOG.log(Level.WARNING, "Caught Exception, closing Evaluators.", e); executingPlan.onSynchronizedExecutionFailed(); } executingPlan.awaitDataTransfers(); LOG.log(Level.INFO, "All data transfers were completed, will submit evaluators and applyUpdates on pause."); driverSync.execute(new SynchronizedExecutionHandler(executingPlan), new SynchronizedExecutionFailedHandler(executingPlan)); executingPlan.awaitSynchronizedExecution(); executingPlan = null; return new PlanResultImpl(); } }); }
Source:
public synchronized LocalDB upsertLocalDBEntry(final LocalDBEntry localDBEntry) throws Exception { if (localDBEntry.getTimeLastReferenced() == null) throw new Exception("Time last referenced in localDB can never be null"); if (localDBEntry.getBackupTime() == null) throw new Exception("Backup time for localDB can never be null"); final Path localDBFile = getLocalDBPath(localDBEntry.getFileUploadResult()); if (!localDBFile.getParent().toFile().exists()) localDBFile.getParent().toFile().mkdirs(); LocalDB localDB = getLocalDB(localDBEntry.getFileUploadResult()); if (localDB == null) localDB = new LocalDB(new ArrayList<>()); LocalDBEntry entry = getLocalDBEntry(localDBEntry.getFileUploadResult(), localDB); if (entry == null) { localDB.getLocalDb().add(localDBEntry); writeLocalDB(localDBFile, localDB); }else{ entry.setBackupTime(localDBEntry.getBackupTime()); entry.setTimeLastReferenced(localDBEntry.getTimeLastReferenced()); writeLocalDB(localDBFile, localDB); } return localDB; }

Target:
public synchronized LocalDB upsertLocalDBEntry(final LocalDBEntry localDBEntry) throws Exception { if (localDBEntry.getTimeLastReferenced() == null) throw new Exception("Time last referenced in localDB can never be null"); if (localDBEntry.getBackupTime() == null) throw new Exception("Backup time for localDB can never be null"); final Path localDBFile = getLocalDBPath(localDBEntry.getFileUploadResult()); localDBFile.getParent().toFile().mkdirs(); LocalDB localDB = readAndGetLocalDB(localDBEntry.getFileUploadResult()); if (localDB == null) localDB = new LocalDB(new ArrayList<>()); LocalDBEntry entry = getLocalDBEntry(localDBEntry.getFileUploadResult(), localDB); if (entry == null) { localDB.getLocalDBEntries().add(localDBEntry); writeLocalDB(localDBFile, localDB); } else { entry.setBackupTime(localDBEntry.getBackupTime()); entry.setTimeLastReferenced(localDBEntry.getTimeLastReferenced()); writeLocalDB(localDBFile, localDB); } return localDB; }
Source:
public String getDeviceOrganizationParent(String deviceId) throws DeviceOrganizationException { String tempParent = null; try { DeviceManagementDAOFactory.beginTransaction(); tempParent = deviceOrganizationDAOimpl.getDeviceOrganizationParent(deviceId); DeviceManagementDAOFactory.commitTransaction(); } catch (DeviceOrganizationDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while getting parent of device with ID: '" + deviceId + "'"; log.error(msg, e); throw new DeviceOrganizationException(msg,e); } catch (TransactionManagementException e) { String msg = "Error occurred while initiating transaction"; log.error(msg, e); } finally { DeviceManagementDAOFactory.closeConnection(); return tempParent; } }

Target:
public String getDeviceOrganizationParent(String deviceId) throws DeviceOrganizationException { String tempParent = null; try { DeviceManagementDAOFactory.beginTransaction(); tempParent = deviceOrganizationDAOimpl.getDeviceOrganizationParent(deviceId); DeviceManagementDAOFactory.commitTransaction(); } catch (DeviceOrganizationDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while getting parent of device with ID: '" + deviceId + "'"; log.error(msg, e); throw new DeviceOrganizationException(msg, e); } catch (TransactionManagementException e) { log.error("Error occurred while initiating transaction", e); } finally { DeviceManagementDAOFactory.closeConnection(); return tempParent; } }
Source:
public String loadProfilePage(Model model, HttpSession session) { Member member = (Member) session.getAttribute("member"); if (member == null || member.getContext() != UserType.PLAYER) { return "redirect:/denied"; } Set<Team> teams = member.getTeams(); model.addAttribute("teams", teams); Set<Team> invitedTeams = member.getInvitedTeams(); model.addAttribute("invitedTeams", invitedTeams); model.addAttribute("invitedTeamsSize", invitedTeams.size()); TournamentDao tournamentDao = new TournamentDao(); List<Tournament> tournaments = tournamentDao.getLastXTournaments(5); model.addAttribute("tournaments", tournaments); return "profile"; }

Target:
public String loadProfilePage(Model model, HttpSession session) { Member member = (Member) session.getAttribute("member"); MemberDao memberDao = new MemberDao(); member = memberDao.getMemberById(member.getId()); if (member == null || member.getContext() != UserType.PLAYER) { return "redirect:/denied"; } Set<Team> invitedTeams = member.getInvitedTeams(); model.addAttribute("invitedTeams", invitedTeams); model.addAttribute("invitedTeamsSize", invitedTeams.size()); Set<Team> teams = member.getTeams(); model.addAttribute("teams", teams); TournamentDao tournamentDao = new TournamentDao(); List<Tournament> tournaments = tournamentDao.getLastXTournaments(5); model.addAttribute("tournaments", tournaments); session.setAttribute("member", memberDao.getMemberById(member.getId())); return "profile"; }
Source:
protected FetchResult fetch(IProgressMonitor monitor, int timeout) throws InvocationTargetException { RemoteConfig config = repository.getConfig().getDefaultRemoteConfig(); FetchOperation fetchOperation = new FetchOperation( repository.getRepository(), config, timeout, false); fetchOperation.run(monitor); return fetchOperation.getOperationResult(); }

Target:
protected FetchResult fetch(IProgressMonitor monitor, int timeout) throws URISyntaxException, InvocationTargetException { RemoteConfig config = repository.getConfig().getDefaultRemoteConfig(); FetchOperation fetchOperation = new FetchOperation( repository.getRepository(), config, timeout, false); fetchOperation.run(monitor); return fetchOperation.getOperationResult(); }
Source:
public static byte[] encodeBase64(byte[] binaryData) { if(binaryData == null){ return null; } return com.google.common.io.BaseEncoding.base64().encode(binaryData).getBytes(); }

Target:
public static byte[] encodeBase64(byte[] binaryData) { if (binaryData == null) { return null; } return BaseEncoding.base64().encode(binaryData).getBytes(); }
Source:
SamzaContainer createSamzaContainer(String processorId, JobModel jobModel) { return SamzaContainer.apply(processorId, jobModel, ScalaJavaUtil.toScalaMap(this.customMetricsReporter), this.taskFactory, JobContextImpl.fromConfigWithDefaults(this.config), Option.apply(this.applicationDefinedContainerContextFactory), Option.apply(this.applicationDefinedTaskContextFactory)); }

Target:
SamzaContainer createSamzaContainer(String processorId, JobModel jobModel) { return SamzaContainer.apply(processorId, jobModel, ScalaJavaUtil.toScalaMap(this.customMetricsReporter), this.taskFactory, JobContextImpl.fromConfigWithDefaults(this.config), Option.apply(this.applicationDefinedContainerContextFactoryOptional.orElse(null)), Option.apply(this.applicationDefinedTaskContextFactoryOptional.orElse(null))); }
Source:
public AbstractPartTreeBlazePersistenceQuery(EntityViewAwareJpaQueryMethod method, EntityManager em, PersistenceProvider persistenceProvider, CriteriaBuilderFactory cbf, EntityViewManager evm) { super(method, em); this.cbf = cbf; this.evm = evm; this.entityViewClass = method.getEntityViewClass(); this.domainClass = method.getEntityInformation().getJavaType(); this.parameters = method.getJpaParameters(); String methodName = method.getName(); boolean matchesSpecificationSignature = parameters.hasSpecificationParameter() && QUERY_PATTERN.matcher(methodName).matches(); boolean hasEntityViewSettingProcessorParameter = parameters.hasEntityViewSettingProcessorParameter(); String source = (matchesSpecificationSignature || hasEntityViewSettingProcessorParameter) ? "" : methodName; this.tree = new PartTree(source, domainClass); boolean recreateQueries = parameters.potentiallySortsDynamically() || entityViewClass != null || matchesSpecificationSignature || hasEntityViewSettingProcessorParameter; this.query = isCountProjection(tree) ? new AbstractPartTreeBlazePersistenceQuery.CountQueryPreparer(persistenceProvider, recreateQueries) : new AbstractPartTreeBlazePersistenceQuery.QueryPreparer(persistenceProvider, recreateQueries); }

Target:
public AbstractPartTreeBlazePersistenceQuery(EntityViewAwareJpaQueryMethod method, EntityManager em, PersistenceProvider persistenceProvider, CriteriaBuilderFactory cbf, EntityViewManager evm) { super(method, em); this.cbf = cbf; this.evm = evm; this.entityViewClass = method.getEntityViewClass(); this.domainClass = method.getEntityInformation().getJavaType(); this.parameters = method.getJpaParameters(); String methodName = method.getName(); boolean skipMethodNamePredicateMatching = QUERY_PATTERN.matcher(methodName).matches(); String source = skipMethodNamePredicateMatching ? "" : methodName; this.tree = new PartTree(source, domainClass); boolean hasEntityViewSettingProcessorParameter = parameters.hasEntityViewSettingProcessorParameter(); boolean recreateQueries = parameters.potentiallySortsDynamically() || entityViewClass != null || skipMethodNamePredicateMatching || hasEntityViewSettingProcessorParameter; this.query = isCountProjection(tree) ? new AbstractPartTreeBlazePersistenceQuery.CountQueryPreparer(persistenceProvider, recreateQueries) : new AbstractPartTreeBlazePersistenceQuery.QueryPreparer(persistenceProvider, recreateQueries); }
Source:
private StorageDomainStatus getStorageDomainStatus() { StorageDomainStatus status = null; if (getStorageDomain() != null && getStorageDomain().getstatus() != null) { status = getStorageDomain().getstatus(); } return status; }

Target:
private StorageDomainStatus getStorageDomainStatus() { StorageDomainStatus status = null; if (getStorageDomain() != null) { status = getStorageDomain().getstatus(); } return status; }
Source:
public void after() throws MuleException { flow.stop(); flow.dispose(); stopIfNeeded(muleContext.getSchedulerService()); }

Target:
public void after() throws MuleException { flow.stop(); flow.dispose(); }
Source:
public List<ITmfStateInterval> queryHistoryRange(int attributeQuark, long t1, long t2, long resolution, IProgressMonitor monitor) throws TimeRangeException, AttributeNotFoundException, StateSystemDisposedException { if (isDisposed) { throw new StateSystemDisposedException(); } List<ITmfStateInterval> intervals; ITmfStateInterval currentInterval; long ts, tEnd; IProgressMonitor mon = monitor; if (mon == null) { mon = new NullProgressMonitor(); } if (t2 < t1 || resolution <= 0) { throw new TimeRangeException(); } if (t2 > this.getCurrentEndTime()) { tEnd = this.getCurrentEndTime(); } else { tEnd = t2; } intervals = new ArrayList<>(); currentInterval = querySingleState(t1, attributeQuark); intervals.add(currentInterval); for (ts = t1; (currentInterval.getEndTime() != -1) && (ts < tEnd); ts += ((currentInterval.getEndTime() - ts) / resolution + 1) * resolution) { if (mon.isCanceled()) { return intervals; } currentInterval = querySingleState(ts, attributeQuark); intervals.add(currentInterval); } if (currentInterval.getEndTime() < tEnd) { currentInterval = querySingleState(tEnd, attributeQuark); intervals.add(currentInterval); } return intervals; }

Target:
public List<ITmfStateInterval> queryHistoryRange(int attributeQuark, long t1, long t2, long resolution, IProgressMonitor monitor) throws TimeRangeException, AttributeNotFoundException, StateSystemDisposedException { if (isDisposed) { throw new StateSystemDisposedException(); } List<ITmfStateInterval> intervals; ITmfStateInterval currentInterval; long ts, tEnd; IProgressMonitor mon = monitor; if (mon == null) { mon = new NullProgressMonitor(); } if (t2 < t1 || resolution <= 0) { throw new TimeRangeException(); } if (t2 > this.getCurrentEndTime()) { tEnd = this.getCurrentEndTime(); } else { tEnd = t2; } intervals = new ArrayList<>(); currentInterval = querySingleState(t1, attributeQuark); intervals.add(currentInterval); for (ts = t1; ts < tEnd; ts = Math.max(currentInterval.getEndTime() + 1, ts + resolution)) { if (mon.isCanceled()) { return intervals; } currentInterval = querySingleState(ts, attributeQuark); intervals.add(currentInterval); } if (currentInterval.getEndTime() < tEnd) { currentInterval = querySingleState(tEnd, attributeQuark); intervals.add(currentInterval); } return intervals; }