auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Response work2(@HeaderParam(LRA_HTTP_HEADER) String lraId) throws NotFoundException { if (lraId != null) { return Response.status(Response.Status.PRECONDITION_FAILED).entity(Entity.text("Unexpected LRA context")).build(); } WebTarget resourcePath = ClientBuilder.newClient().target(context.getBaseUri()).path(ACTIVITIES_PATH).path("nestedActivity"); Response response = resourcePath.request().put(Entity.text("")); String id = null; if (response.hasEntity()) id = response.readEntity(String.class); if (id == null) { return Response.status(Response.Status.PRECONDITION_FAILED).entity(Entity.text("LRA context was not propagated")).build(); } return Response.ok().build(); }

Target:
public Response work2(@HeaderParam(LRA_HTTP_HEADER) String lraId) throws NotFoundException { if (lraId != null) { return Response.status(Response.Status.PRECONDITION_FAILED).entity(Entity.text("Unexpected LRA context")).build(); } WebTarget resourcePath = ClientBuilder.newClient().target(context.getBaseUri()) .path(ACTIVITIES_PATH) .path(ActivityController.MANDATORY_LRA_RESOURCE_PATH); Response response = resourcePath.request().put(Entity.text("")); String id = checkStatusAndClose(response, Response.Status.OK.getStatusCode(), true, resourcePath); if (id == null) { return Response.status(Response.Status.PRECONDITION_FAILED).entity(Entity.text("LRA context was not propagated")).build(); } return Response.ok().build(); }
Source:
public void earlyStartup() { final String version = System.getProperty(JAVA_VERSION_PROPERTY); double detectedJavaVersion = getJavaVersionInDouble(version); if (detectedJavaVersion < Constants.MINIMUM_REQUIRED_JAVA_VERSION || detectedJavaVersion > Constants.MAXIMUM_SUPPORTED_JAVA_VERSION) { final IWorkbench workbench = PlatformUI.getWorkbench(); workbench.getDisplay().asyncExec(new Runnable() { public void run() { if (workbench.getDisplay() != null) { Shell shell = new Shell(workbench.getDisplay()); Monitor primaryMonitor = workbench.getDisplay().getPrimaryMonitor(); Rectangle primaryBounds = primaryMonitor.getBounds(); Rectangle shellBounds = shell.getBounds(); int xCenter = primaryBounds.x + (primaryBounds.width - shellBounds.width) / 2; int yCenter = primaryBounds.y + (primaryBounds.height - shellBounds.height) / 2; shell.setLocation(xCenter, yCenter); String str = (Constants.MAXIMUM_SUPPORTED_JAVA_VERSION == Constants.MINIMUM_REQUIRED_JAVA_VERSION) ? "\n" : (" - " + Constants.MAXIMUM_SUPPORTED_JAVA_VERSION + ".x" + "\n"); String warningMessage = Constants.DETECTED_JAVA_VERSION_MESSAGE + version + "\n" + Constants.RECOMMENDED_JAVA_VERSION_MESSAGE + Constants.MINIMUM_REQUIRED_JAVA_VERSION + ".x" + str + Constants.JAVA_VERSION_ALERT_MESSAGE; MessageDialog dialog = new MessageDialog(shell, ALERT_TITLE, null, warningMessage, MessageDialog.ERROR, new String[] { EXIT_BUTTON }, 0) { protected void buttonPressed(int buttonId) { if (buttonId == 0) { System.exit(0); } super.buttonPressed(buttonId); } }; dialog.open(); } } }); } }

Target:
public void earlyStartup() { final String version = System.getProperty(JAVA_VERSION_PROPERTY); double detectedJavaVersion = getJavaVersionInDouble(version); if (detectedJavaVersion < Constants.MINIMUM_REQUIRED_JAVA_VERSION || detectedJavaVersion > Constants.MAXIMUM_SUPPORTED_JAVA_VERSION) { final IWorkbench workbench = PlatformUI.getWorkbench(); workbench.getDisplay().asyncExec(new Runnable() { public void run() { if (workbench.getDisplay() != null) { Shell shell = new Shell(workbench.getDisplay()); Monitor primaryMonitor = workbench.getDisplay().getPrimaryMonitor(); Rectangle primaryBounds = primaryMonitor.getBounds(); Rectangle shellBounds = shell.getBounds(); int xCenter = primaryBounds.x + (primaryBounds.width - shellBounds.width) / 2; int yCenter = primaryBounds.y + (primaryBounds.height - shellBounds.height) / 2; shell.setLocation(xCenter, yCenter); String str = (Constants.MAXIMUM_SUPPORTED_JAVA_VERSION == Constants.MINIMUM_REQUIRED_JAVA_VERSION) ? "\n" : (" - " + Constants.MAXIMUM_SUPPORTED_JAVA_VERSION + ".x" + "\n"); String warningMessage = Constants.DETECTED_JAVA_VERSION_MESSAGE + version + "\n" + Constants.RECOMMENDED_JAVA_VERSION_MESSAGE + Constants.MINIMUM_REQUIRED_JAVA_VERSION + ".x" + str + Constants.JAVA_VERSION_ALERT_MESSAGE; MessageDialog dialog = new MessageDialog(shell, ALERT_TITLE, null, warningMessage, MessageDialog.ERROR, new String[] { EXIT_BUTTON }, 0) { protected void buttonPressed(int buttonId) { System.exit(0); } protected void handleShellCloseEvent() { System.exit(0); } }; dialog.open(); } } }); } }
Source:
public void verifyBioAndHireable() throws IOException { GHUser u = gitHub.getUser("GitHub"); assertNotNull(u.getBio()); assertNotNull(u.isHireable()); }

Target:
public void verifyBioAndHireable() throws IOException { GHUser u = gitHub.getUser("Chew"); assertThat(u.getBio(), equalTo("I like to program things and I hope to program something cool one day :D")); assertTrue(u.isHireable()); assertNotNull(u.getTwitterUsername()); }
Source:
public static String deleteProtocolPrefixIfExist(String url) { if (url.matches("^\\w+://.*")) { return url.split(" } return url; }

Target:
public static String deleteProtocolPrefixIfExist(String url) { return url.replaceFirst("^\\w+://", ""); }
Source:
public void testSamePublicAndPrivateAddressAcrossNodes() { Node node1 = Node.newDefaultNode("foo1", "host1").setNodeGroupPort(9410).setNodePublicHostname("host2").setNodePublicPort(9410); Node node2 = Node.newDefaultNode("foo2", "host2").setNodeGroupPort(9410).setNodePublicHostname("host1").setNodePublicPort(9410); new ClusterValidator(newDefaultCluster(new Stripe(node1, node2))).validate(); }

Target:
public void testSamePublicAndPrivateAddressAcrossNodes() { Node node1 = Node.newDefaultNode("foo1", "host1").setNodePort(9410).setNodePublicHostname("host2").setNodePublicPort(9410); Node node2 = Node.newDefaultNode("foo2", "host2").setNodePort(9410).setNodePublicHostname("host1").setNodePublicPort(9410); new ClusterValidator(newDefaultCluster(new Stripe(node1, node2))).validate(); }
Source:
public KeenProject(String projectId, String writeKey, String readKey, String masterKey) { if (projectId == null || projectId.trim().isEmpty()) { throw new IllegalArgumentException("Invalid project id specified: " + projectId); } this.projectId = projectId; this.writeKey = writeKey; this.readKey = readKey; this.masterKey = masterKey; }

Target:
public KeenProject(String projectId, String writeKey, String readKey, String masterKey) { if (null == projectId || projectId.trim().isEmpty()) { throw new IllegalArgumentException("Invalid project id specified: " + projectId); } if ((null == writeKey || writeKey.trim().isEmpty()) && (null == readKey || readKey.trim().isEmpty()) && (null == masterKey || masterKey.trim().isEmpty())) { throw new IllegalArgumentException("At least one of the keys given must be non-null " + "and non-empty."); } this.projectId = projectId; this.writeKey = writeKey; this.readKey = readKey; this.masterKey = masterKey; }
Source:
public void testSimpleSpatialAnnotationOnClassLevel() throws Exception { SimpleHotel hotel = new SimpleHotel( 1, "Plazza Athénée", 24.0d, 32.0d, "Luxurious" ); FullTextSession fullTextSession = Search.getFullTextSession( openSession() ); Transaction tx = fullTextSession.beginTransaction(); fullTextSession.save( hotel ); tx.commit(); tx = fullTextSession.beginTransaction(); double centerLatitude= 24; double centerLongitude= 31.5; QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( SimpleHotel.class ).get(); org.apache.lucene.search.Query luceneQuery = SpatialQueryBuilder.buildSimpleSpatialQuery( centerLatitude, centerLongitude, 50 ); org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery( luceneQuery, SimpleHotel.class ); List results = hibQuery.list(); Assert.assertEquals( 0, results.size() ); org.apache.lucene.search.Query luceneQuery2 = SpatialQueryBuilder.buildSimpleSpatialQuery( centerLatitude, centerLongitude, 51 ); org.hibernate.Query hibQuery2 = fullTextSession.createFullTextQuery( luceneQuery2, SimpleHotel.class ); List results2 = hibQuery2.list(); Assert.assertEquals( 1, results2.size() ); List<?> events = fullTextSession.createQuery( "from " + SimpleHotel.class.getName() ).list(); for (Object entity : events) { fullTextSession.delete( entity ); } tx.commit(); fullTextSession.close(); }

Target:
public void testSimpleSpatialAnnotationOnClassLevel() throws Exception { SimpleHotel hotel = new SimpleHotel( 1, "Plazza Athénée", 24.0d, 32.0d, "Luxurious" ); FullTextSession fullTextSession = Search.getFullTextSession( openSession() ); Transaction tx = fullTextSession.beginTransaction(); fullTextSession.save( hotel ); tx.commit(); tx = fullTextSession.beginTransaction(); double centerLatitude= 24; double centerLongitude= 31.5; org.apache.lucene.search.Query luceneQuery = SpatialQueryBuilder.buildSimpleSpatialQuery( centerLatitude, centerLongitude, 50 ); org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery( luceneQuery, SimpleHotel.class ); List results = hibQuery.list(); Assert.assertEquals( 0, results.size() ); org.apache.lucene.search.Query luceneQuery2 = SpatialQueryBuilder.buildSimpleSpatialQuery( centerLatitude, centerLongitude, 51 ); org.hibernate.Query hibQuery2 = fullTextSession.createFullTextQuery( luceneQuery2, SimpleHotel.class ); List results2 = hibQuery2.list(); Assert.assertEquals( 1, results2.size() ); List<?> events = fullTextSession.createQuery( "from " + SimpleHotel.class.getName() ).list(); for (Object entity : events) { fullTextSession.delete( entity ); } tx.commit(); fullTextSession.close(); }
Source:
public JsonObject getAllLoggers() { accessControl(Group.managers()); return Holder.getAllLoggers(); }

Target:
public JsonObject getAllLoggers() { accessControl(Group.managers()); if (available) { return Holder.getAllLoggers(); } JsonObject empty = new JsonObject(); empty.add("loggers", new JsonArray()); return empty; }
Source:
public List<Long> getBytesList(String path) { return getMemorySizeList(path).stream() .map(ConfigMemorySize::toBytes) .collect(Collectors.toList()); }

Target:
public List<Long> getBytesList(String path) { ConfigValue v = find(path, ConfigValueType.LIST); return getBytesListBigInteger(path).stream() .map(bytes -> toLong(bytes, v.origin(), path)) .collect(Collectors.toList()); }
Source:
private void performBackup() throws IOException { String backupFileName = PREFIX + DateTime.now().toString("yyyy-MM-dd'T'HH:mm") + ".zip"; File backupFile = new File(destination, backupFileName); LOGGER.info("Performing backup to " + backupFile); String schedulerHome = ClasspathUtils.findSchedulerHome(); String[] foldersToZip = targets.stream() .map(target -> (new File(schedulerHome, target)).getAbsolutePath()) .toArray(String[]::new); ZipUtils.zip(foldersToZip, backupFile, null); }

Target:
private void performBackup() throws IOException { String backupFileName = PREFIX + DateTime.now().toString("yyyy-MM-dd'T'HH-mm") + ".zip"; File destinationFolder = new File(destination); if (!destinationFolder.isAbsolute()) { destinationFolder = new File(PASchedulerProperties.SCHEDULER_HOME.getValueAsString(), destination); } if (destinationFolder.exists() && destinationFolder.isDirectory() && destinationFolder.canWrite()) { File backupFile = new File(destination, backupFileName); LOGGER.info("Performing backup to " + backupFile); String[] foldersToZip = targets.stream() .map(target -> (new File(PASchedulerProperties.SCHEDULER_HOME.getValueAsString(), target)).getAbsolutePath()) .toArray(String[]::new); ZipUtils.zip(foldersToZip, backupFile, null); } else { LOGGER.error("Cannot save a backup because backup destination folder does not exist: " + destination); } }
Source:
void givenGraphQuery_whenListEvents_thenReturnAllEvents() { Map<String, Object> requestBody = new HashMap<>(); requestBody.put("query", "query ListEvents { listEvents { items { id name where when description } } }"); requestBody.put("variables", ""); requestBody.put("operationName", "ListEvents"); String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody) .bodyToMono(String.class).block(); assertNotNull(bodyString); assertTrue(bodyString.contains("My First Event")); assertTrue(bodyString.contains("where")); assertTrue(bodyString.contains("when")); }

Target:
void givenGraphQuery_whenListEvents_thenReturnAllEvents() { Map<String, Object> requestBody = new HashMap<>(); requestBody.put("query", "query ListEvents {" + " listEvents {" + " items {" + " id" + " name" + " where" + " when" + " description" + " }" + " }" + "}"); requestBody.put("variables", ""); requestBody.put("operationName", "ListEvents"); String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody) .bodyToMono(String.class).block(); assertNotNull(bodyString); assertTrue(bodyString.contains("My First Event")); assertTrue(bodyString.contains("where")); assertTrue(bodyString.contains("when")); }
Source:
public Statement apply(Statement base, Description description) { KuduClusterTestContext testContext = description.getAnnotation(KuduClusterTestContext.class); String masterHostsValue = System.getProperty(KUDU_MASTER_HOSTS_STRING_ENV); boolean runThisTest = true; if ( testContext != null) { if ((masterHostsValue != null) && (testContext.kuduClusterBasedTest())) { runThisTest = true; } if ((masterHostsValue != null) && (!testContext.kuduClusterBasedTest())) { runThisTest = false; } if ((masterHostsValue == null) && (testContext.kuduClusterBasedTest())) { runThisTest = false; } if ((masterHostsValue == null) && (!testContext.kuduClusterBasedTest())) { runThisTest = true; } } if (runThisTest) { if ((testContext != null ) && (testContext.kuduClusterBasedTest())) { try { initRealKuduClusterSetup(masterHostsValue); } catch (Exception e) { LOG.error(e.getMessage(), e); } } else { try { KuduInputOperatorCommons.initCommonConfigsForAllTypesOfTests(); } catch (Exception e) { LOG.error(e.getMessage(),e); } } return base; } else { return new Statement() { @Override public void evaluate() throws Throwable { } }; } }

Target:
public Statement apply(Statement base, Description description) { KuduClusterTestContext testContext = description.getAnnotation(KuduClusterTestContext.class); String masterHostsValue = System.getProperty(KUDU_MASTER_HOSTS_STRING_ENV); boolean runThisTest = true; if ( testContext != null) { if ((masterHostsValue != null) && (testContext.kuduClusterBasedTest())) { runThisTest = true; } if ((masterHostsValue != null) && (!testContext.kuduClusterBasedTest())) { runThisTest = false; } if ((masterHostsValue == null) && (testContext.kuduClusterBasedTest())) { runThisTest = false; } if ((masterHostsValue == null) && (!testContext.kuduClusterBasedTest())) { runThisTest = true; } } if (runThisTest) { if ((testContext != null ) && (testContext.kuduClusterBasedTest())) { try { initRealKuduClusterSetup(masterHostsValue); } catch (Exception e) { throw new RuntimeException("Not able to initialize kudu cluster",e); } } else { try { KuduInputOperatorCommons.initCommonConfigsForAllTypesOfTests(); } catch (Exception e) { throw new RuntimeException("Could not initialize commn configs required for Kudu cluster connectivity",e); } } return base; } else { return new Statement() { @Override public void evaluate() throws Throwable { } }; } }
Source:
public static Boolean stSphericalContains(@SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice left, @SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice right) { OGCGeometry leftGeometry = deserialize(left); if (leftGeometry.isEmpty()) { return null; } OGCGeometry rightGeometry = deserialize(right); if (rightGeometry.isEmpty()) { return null; } validateSphericalType("ST_Contains", leftGeometry, EnumSet.of(POLYGON)); validateSphericalType("ST_Contains", rightGeometry, EnumSet.of(POINT)); Polygon polygon = (Polygon) leftGeometry.getEsriGeometry(); Point point = (Point) rightGeometry.getEsriGeometry(); if (point.getY() == MAX_LATITUDE || point.getY() == MIN_LATITUDE) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "When applied to SphericalGeography inputs, ST_Contains only supports points which are not poles."); } if (containsEitherPole(polygon)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "When applied to SphericalGeography inputs, ST_Contains only supports polygons which do not enclose poles."); } int k = getNumberIntersectionsWithPolygon(polygon, point); if (k % 2 == 1) { return true; } else { return false; } }

Target:
public static Boolean stSphericalContains(@SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice left, @SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice right) { OGCGeometry leftGeometry = deserialize(left); if (leftGeometry.isEmpty()) { return false; } OGCGeometry rightGeometry = deserialize(right); if (rightGeometry.isEmpty()) { return false; } validateSphericalType("ST_Contains", leftGeometry, EnumSet.of(POLYGON)); validateSphericalType("ST_Contains", rightGeometry, EnumSet.of(POINT)); Polygon polygon = (Polygon) leftGeometry.getEsriGeometry(); Point point = (Point) rightGeometry.getEsriGeometry(); if (point.getY() == MAX_LATITUDE || point.getY() == MIN_LATITUDE) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "When applied to SphericalGeography inputs, ST_Contains only supports points which are not poles."); } if (SphericalCalculator.containsPole(polygon)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "When applied to SphericalGeography inputs, ST_Contains only supports polygons which do not enclose poles."); } return contains(polygon, point); }
Source:
@Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double rowCount = mq.getRowCount(getInput()); double bytesPerRow = getRowType().getFieldCount() * IgniteCost.AVERAGE_FIELD_SIZE; double totalBytes = rowCount * bytesPerRow; IgniteCostFactory costFactory = (IgniteCostFactory)planner.getCostFactory(); if (RelDistributions.BROADCAST_DISTRIBUTED.equals(distribution)) totalBytes *= 5; return costFactory.makeCost(rowCount, rowCount * IgniteCost.ROW_PASS_THROUGH_COST, 0D, 0D, totalBytes); }

Target:
@Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double rowCount = mq.getRowCount(getInput()); double bytesPerRow = getRowType().getFieldCount() * IgniteCost.AVERAGE_FIELD_SIZE; double totalBytes = rowCount * bytesPerRow; IgniteCostFactory costFactory = (IgniteCostFactory)planner.getCostFactory(); if (RelDistributions.BROADCAST_DISTRIBUTED.equals(distribution)) totalBytes *= IgniteCost.BROADCAST_DISTRIBUTION_PENALTY; return costFactory.makeCost(rowCount, rowCount * IgniteCost.ROW_PASS_THROUGH_COST, 0, 0, totalBytes); }
Source:
public void validateTicketFromInvalid() { Ticket ticket = persistTicket(); ticket.setValid(false); testEntityManager.persist(ticket); assertEquals(false, ticket.isValid()); ticketService.validateTicket(ticket.getId()); assertEquals(true, ticket.isValid()); }

Target:
public void validateTicketFromInvalid() { Ticket ticket = persistTicket(); ticket.setValid(false); ticket = testEntityManager.persist(ticket); assertEquals(false, ticket.isValid()); ticketService.validateTicket(ticket.getId()); assertEquals(true, testEntityManager.find(Ticket.class, ticket.getId()).isValid()); }
Source:
public static Expression combineConjuncts(Collection<Expression> expressions) { requireNonNull(expressions, "expressions is null"); List<Expression> conjuncts = expressions.stream() .flatMap(e -> ExpressionUtils.extractConjuncts(e).stream()) .filter(e -> !e.equals(TRUE_LITERAL)) .collect(toList()); conjuncts = removeDuplicates(conjuncts); if (conjuncts.contains(FALSE_LITERAL)) { return FALSE_LITERAL; } return conjuncts.isEmpty() ? TRUE_LITERAL : and(conjuncts); }

Target:
public static Expression combineConjuncts(Collection<Expression> expressions) { requireNonNull(expressions, "expressions is null"); List<Expression> conjuncts = expressions.stream() .flatMap(e -> ExpressionUtils.extractConjuncts(e).stream()) .filter(e -> !e.equals(TRUE_LITERAL)) .collect(toList()); conjuncts = removeDuplicates(conjuncts); if (conjuncts.contains(FALSE_LITERAL)) { return FALSE_LITERAL; } return and(conjuncts); }
Source:
private File getMinishiftBinary(File root) { return new File(root, "minishift"); }

Target:
private File getMinishiftBinary(File root) { return new File(root, MINISHIFT); }
Source:
private boolean isStackOrClusterDrStatusComplete(Status status) { return (Status.BACKUP_FINISHED.equals(status) || Status.RESTORE_FINISHED.equals(status)) ? true : false; }

Target:
private boolean isStackOrClusterDrStatusComplete(Status status) { return Status.AVAILABLE.equals(status); }
Source:
public ParseTexResultViewModel(TexBibEntriesResolverResult resolverResult, BibDatabaseContext databaseContext) { this.resolverResult = resolverResult; this.databaseContext = databaseContext; this.referenceList = FXCollections.observableArrayList(); this.citationList = FXCollections.observableArrayList(); Set<String> newEntryKeys = resolverResult.getNewEntries().stream().map(entry -> entry.getCiteKeyOptional().orElse("")).collect(Collectors.toSet()); resolverResult.getCitations().asMap().forEach((entry, citations) -> referenceList.add(new ReferenceViewModel(entry, newEntryKeys.contains(entry), citations))); this.importButtonDisabled = new SimpleBooleanProperty(referenceList.stream().noneMatch(ReferenceViewModel::isHighlighted)); }

Target:
public ParseTexResultViewModel(TexBibEntriesResolverResult resolverResult, BibDatabaseContext databaseContext) { this.resolverResult = resolverResult; this.databaseContext = databaseContext; this.referenceList = FXCollections.observableArrayList(); this.citationList = FXCollections.observableArrayList(); Set<String> newEntryKeys = resolverResult.getNewEntries().stream().map(entry -> entry.getCiteKeyOptional().orElse("")).collect(Collectors.toSet()); for (Map.Entry<String, Collection<Citation>> entry : resolverResult.getCitations().asMap().entrySet()) { String key = entry.getKey(); referenceList.add(new ReferenceViewModel(key, newEntryKeys.contains(key), entry.getValue())); } this.importButtonDisabled = new SimpleBooleanProperty(referenceList.stream().noneMatch(ReferenceViewModel::isHighlighted)); }
Source:
public String render(final GetCacheStateResult obj) throws JsonProcessingException { final CommonJsonView view = CommonJsonView.newView(CommonJsonView.Status.OK); final List<CacheFilesystemInformation> cacheFilesystemInfo = obj.getResult(); if( (cacheFilesystemInfo == null) || (cacheFilesystemInfo.size() < 1)){ return "No valid Cache Filesystems on remote appliance"; } return JsonMapper.toJson(view.data(cacheFilesystemInfo)); }

Target:
public String render(final GetCacheStateResult obj) throws JsonProcessingException { final CommonJsonView view = CommonJsonView.newView(CommonJsonView.Status.OK); final List<CacheFilesystemInformation> cacheFilesystemInfo = obj.getResult(); if(Guard.isNullOrEmpty(cacheFilesystemInfo)){ return "No valid Cache Filesystems on remote appliance"; } return JsonMapper.toJson(view.data(cacheFilesystemInfo)); }
Source:
private static Stream<AssignmentExpressionTree> usageInAssignment(IdentifierTree usage) { Tree parent = usage.parent(); while (parent != null && !parent.is(Tree.Kind.ASSIGNMENT)) { parent = parent.parent(); } if (parent == null) { return Stream.empty(); } AssignmentExpressionTree assignment = (AssignmentExpressionTree) parent; if (ExpressionUtils.skipParentheses(assignment.variable()).equals(usage)) { return Stream.of(assignment); } return Stream.empty(); }

Target:
private static Stream<AssignmentExpressionTree> usageInAssignment(IdentifierTree usage) { Tree prevParent = usage; Tree parent = usage.parent(); while (parent != null && !parent.is(Tree.Kind.ASSIGNMENT) && parent.is(Tree.Kind.MEMBER_SELECT, Tree.Kind.IDENTIFIER)) { prevParent = parent; parent = parent.parent(); } if (parent != null && parent.is(Tree.Kind.ASSIGNMENT)) { AssignmentExpressionTree assignment = (AssignmentExpressionTree) parent; if (assignment.variable().equals(prevParent)) { return Stream.of(assignment); } } return Stream.empty(); }
Source:
private BuildCommand sync(String workingDir, String revision) { return exec("p4", "-d", workingDir, "sync", "@" + parseLong(revision)); }

Target:
private BuildCommand sync(String workingDir, String revision) { return exec("p4", "-d", workingDir, "sync", "-f", "@" + parseLong(revision)).setCommandEnvVars(envVars()); }
Source:
protected void executeQueryCommand() { Set<AdditionalClusterFeature> clusterFeaturesList = getDbFacade().getClusterFeatureDao() .getClusterFeaturesForVersionAndCategory(getParameters().getVersion().getValue(), getParameters().getCategory()); getQueryReturnValue().setReturnValue(clusterFeaturesList); }

Target:
protected void executeQueryCommand() { Set<AdditionalClusterFeature> additionalClusterFeatures = clusterFeatureDao.getClusterFeaturesForVersionAndCategory(getParameters().getVersion().getValue(), getParameters().getCategory()); getQueryReturnValue().setReturnValue(additionalClusterFeatures); }
Source:
public void registerAttributes(ManagementResourceRegistration registry) { for (AttributeDefinition attr : ATTRIBUTES) { registry.registerReadWriteAttribute(attr, null, new ReloadRequiredWriteAttributeHandler(ATTRIBUTES)); } for (AttributeDefinition attr : READONLY_ATTRIBUTES) { registry.registerReadOnlyAttribute(attr, JMSBridgeHandler.INSTANCE); } }

Target:
public void registerAttributes(ManagementResourceRegistration registry) { ReloadRequiredWriteAttributeHandler reloadRequiredWriteAttributeHandler = new ReloadRequiredWriteAttributeHandler(ATTRIBUTES); for (AttributeDefinition attr : ATTRIBUTES) { registry.registerReadWriteAttribute(attr, null, reloadRequiredWriteAttributeHandler); } for (AttributeDefinition attr : READONLY_ATTRIBUTES) { registry.registerReadOnlyAttribute(attr, JMSBridgeHandler.INSTANCE); } }
Source:
public static void GetTemplateListByDataCenter(AsyncQuery aQuery, Guid dataCenterId) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { ArrayList<VmTemplate> list = new ArrayList<VmTemplate>(); if (source != null) { VmTemplate blankTemplate = null; for (VmTemplate template : (ArrayList<VmTemplate>) source) { if (template.getId().equals(Guid.Empty)) { blankTemplate = template; } else if (template.getstatus() == VmTemplateStatus.OK) { list.add(template); } } Collections.sort(list, new Linq.VmTemplateByNameComparer()); if (blankTemplate != null) { list.add(0, blankTemplate); } } return list; } }; Frontend.RunQuery(VdcQueryType.GetVmTemplatesByStoragePoolId, new GetVmTemplatesByStoragePoolIdParameters(dataCenterId), aQuery); }

Target:
public static void GetTemplateListByDataCenter(AsyncQuery aQuery, Guid dataCenterId) { aQuery.converterCallback = new TemplateConverter(); Frontend.RunQuery(VdcQueryType.GetVmTemplatesByStoragePoolId, new GetVmTemplatesByStoragePoolIdParameters(dataCenterId), aQuery); }
Source:
public ReplicaList filter(Predicate<Replica> predicate) { ArrayList<Replica> newReplicaList = new ArrayList<>(size()); for (Replica replica: replicaList) { if (predicate.test(replica)) { newReplicaList.add(replica); } } return new ReplicaList(newReplicaList); }

Target:
public ReplicaList filter(Predicate<Replica> predicate) { ArrayList<Replica> newReplicaList = size() < 10 ? new ArrayList<>(size()) : new ArrayList<>(); for (int i=0; i<size(); i++) { Replica replica = replicaList.get(i); if (predicate.test(replica)) { newReplicaList.add(replica); } } return new ReplicaList(newReplicaList); }
Source:
public static String getString(String key, String def) { String value = System.getProperty(key); if (value != null) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Property (system): {0} => {1}", new Object[] {key, value}); } } else if (theContext != null) { value = theContext.getInitParameter(key); if (value != null) { if(LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Property (context): {0} => {1}", new Object[] {key, value}); } } } if (value == null) { value = def; if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Property (default): {0} => {1}", new Object[] {key, value}); } } return value; }

Target:
public static String getString(String key, String def) { String value = System.getProperty(key); if (value != null) { if (LOGGER.isLoggable(Level.CONFIG)) { LOGGER.log(Level.CONFIG, "Property (system): {0} => {1}", new Object[] {key, value}); } } else if (theContext != null) { value = theContext.getInitParameter(key); if (value != null) { if(LOGGER.isLoggable(Level.CONFIG)) { LOGGER.log(Level.CONFIG, "Property (context): {0} => {1}", new Object[] {key, value}); } } } if (value == null) { value = def; if (LOGGER.isLoggable(Level.CONFIG)) { LOGGER.log(Level.CONFIG, "Property (default): {0} => {1}", new Object[] {key, value}); } } return value; }
Source:
private static void requestsCheck(SubscriptionContext subscriptionContext) { CallExpression callExpr = (CallExpression) subscriptionContext.syntaxNode(); boolean isVulnerableMethod = ofNullable(callExpr.calleeSymbol()) .map(Symbol::fullyQualifiedName) .filter(requestsMethods::contains) .isPresent(); if (isVulnerableMethod) { Optional<Expression> verifyRhs = searchVerifyAssignment(callExpr) .map(Optional::of) .orElseGet(() -> searchVerifyInKwargs(callExpr)); verifyRhs.ifPresent(rhs -> { if (Expressions.isFalsy(rhs) || isFalsyCollection(rhs)) { subscriptionContext.addIssue( rhs.firstToken(), rhs.lastToken(), "Disabling certificate verification is dangerous."); } }); } }

Target:
private static void requestsCheck(SubscriptionContext subscriptionContext) { CallExpression callExpr = (CallExpression) subscriptionContext.syntaxNode(); boolean isVulnerableMethod = ofNullable(callExpr.calleeSymbol()) .map(Symbol::fullyQualifiedName) .filter(requestsMethods::contains) .isPresent(); if (isVulnerableMethod) { Optional<List<Expression>> verifyRhs = searchVerifyAssignment(callExpr) .map(Optional::of) .orElseGet(() -> searchVerifyInKwargs(callExpr)); verifyRhs.ifPresent(sensitiveSettingExpressions -> { Expression rhs = sensitiveSettingExpressions.get(sensitiveSettingExpressions.size() - 1); if (Expressions.isFalsy(rhs) || isFalsyCollection(rhs)) { PreciseIssue issue = subscriptionContext.addIssue(rhs, "Disabling certificate verification is dangerous."); for (int i = 0; i < sensitiveSettingExpressions.size() - 1; i++) { issue.secondary(sensitiveSettingExpressions.get(i), "Dictionary is passed here as **kwargs."); } } }); } }
Source:
private void handleScanTimeout(ScanTimeoutException rte) throws IOException { try { currentDelegate.close(); } catch (IOException ioe) { logger.warn("Error closing scanner before reissuing request: ", ioe); } logger.info("The client could not get a response in %d ms. Retrying the scan.", retryOptions.getReadPartialRowTimeoutMillis()); if (timeoutRetryCount == null) { timeoutRetryCount = new AtomicInteger(); } currentErrorBackoff = null; if (timeoutRetryCount.incrementAndGet() <= retryOptions.getMaxScanTimeoutRetries()) { reissueRequest(); } else { rpcMetrics.incrementFailureCount(); throw new BigtableRetriesExhaustedException( "Exhausted streaming retries after too many timeouts", rte); } }

Target:
private void handleScanTimeout(ScanTimeoutException rte) throws IOException { try { currentDelegate.close(); } catch (IOException ioe) { logger.warn("Error closing scanner before reissuing request: ", ioe); } logger.info("The client could not get a response in %d ms. Retrying the scan.", retryOptions.getReadPartialRowTimeoutMillis()); currentErrorBackoff = null; if (timeoutRetryCount == null) { timeoutRetryCount = new AtomicInteger(); } if (timeoutRetryCount.incrementAndGet() <= retryOptions.getMaxScanTimeoutRetries()) { reissueRequest(); } else { rpcMetrics.incrementRetriesExhastedCounter(); throw new BigtableRetriesExhaustedException( "Exhausted streaming retries after too many timeouts", rte); } }
Source:
public ClientOptions setHeaders(Iterable<Header> headers) { this.headers = Objects.requireNonNull(headers, "'headers' cannot be null."); return this; }

Target:
public ClientOptions setHeaders(Iterable<Header> headers) { this.headers = headers; return this; }
Source:
protected void reconnect(Watcher watcher) throws InterruptedException { _zookeeperLock.lock(); try { if (_zk == null) { throw new IllegalStateException("zk client has not been connected or already been closed"); } ZooKeeper prevZk = _zk; try { LOG.debug("Creating new ZookKeeper instance to reconnect to " + _servers + "."); _zk = new ZooKeeper(_servers, _sessionTimeOut, watcher); prevZk.close(); _getChildrenMethod = null; } catch (IOException e) { throw new ZkException("Unable to connect to " + _servers, e); } } finally { _zookeeperLock.unlock(); } }

Target:
protected void reconnect(Watcher watcher) throws InterruptedException { _zookeeperLock.lock(); try { if (_zk == null) { throw new IllegalStateException("zk client has not been connected or already been closed"); } ZooKeeper prevZk = _zk; try { LOG.debug("Creating new ZookKeeper instance to reconnect to " + _servers + "."); _zk = new ZooKeeper(_servers, _sessionTimeOut, watcher); prevZk.close(); } catch (IOException e) { throw new ZkException("Unable to connect to " + _servers, e); } } finally { _zookeeperLock.unlock(); } }
Source:
public Default() { this.processor = new MarkdownTxtmark(); }

Target:
public Default() { this.processor = new MarkdownPegdown(); }
Source:
public static void withinEntityManager(EntityManagerFactory emf, Consumer<FullTextEntityManager> consumer) { EntityManager entityManager = emf.createEntityManager(); try { FullTextEntityManager fem = Search.getFullTextEntityManager( entityManager ); consumer.accept( fem ); } finally { entityManager.close(); } }

Target:
public static void withinEntityManager(EntityManagerFactory emf, Consumer<FullTextEntityManager> consumer) { EntityManager entityManager = emf.createEntityManager(); try { FullTextEntityManager fem = Search.getFullTextEntityManager( entityManager ); consumer.accept( fem ); } catch (Throwable mainError) { try { entityManager.close(); } catch (Throwable errorOnClose) { mainError.addSuppressed( errorOnClose ); } throw mainError; } entityManager.close(); }
Source:
private Map<String, TemplateProp> listTemplate(DataStore ssStore) { String nfsVersionParam = imageStoreDetailsUtil.getNfsVersion(ssStore.getId()); Integer nfsVersion = (nfsVersionParam != null ? Integer.valueOf(nfsVersionParam) : null); ListTemplateCommand cmd = new ListTemplateCommand(ssStore.getTO(), nfsVersion); EndPoint ep = _epSelector.select(ssStore); Answer answer = null; if (ep == null) { String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; s_logger.error(errMsg); answer = new Answer(cmd, false, errMsg); } else { answer = ep.sendMessage(cmd); } if (answer != null && answer.getResult()) { ListTemplateAnswer tanswer = (ListTemplateAnswer)answer; return tanswer.getTemplateInfo(); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("can not list template for secondary storage host " + ssStore.getId()); } } return null; }

Target:
private Map<String, TemplateProp> listTemplate(DataStore ssStore) { Integer nfsVersion = imageStoreDetailsUtil.getNfsVersion(ssStore.getId()); ListTemplateCommand cmd = new ListTemplateCommand(ssStore.getTO(), nfsVersion); EndPoint ep = _epSelector.select(ssStore); Answer answer = null; if (ep == null) { String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; s_logger.error(errMsg); answer = new Answer(cmd, false, errMsg); } else { answer = ep.sendMessage(cmd); } if (answer != null && answer.getResult()) { ListTemplateAnswer tanswer = (ListTemplateAnswer)answer; return tanswer.getTemplateInfo(); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("can not list template for secondary storage host " + ssStore.getId()); } } return null; }
Source:
public static void configure( final Environment environment, Configuration config, String tracerName, Stacktraces stacktracePropagation) { Brave brave = DropwizardTracingFilters.registerTracers(environment, config, tracerName); environment.jersey().register(brave); ExceptionMappers.visitExceptionMappers( stacktracePropagation == Stacktraces.PROPAGATE, new ExceptionMappers.Consumer<ExceptionMapper<? extends Throwable>>() { @Override public void accept(ExceptionMapper<? extends Throwable> mapper) { environment.jersey().register(mapper); } }); environment.jersey().register(new OptionalAsNoContentMessageBodyWriter()); }

Target:
public static void configure( final Environment environment, Configuration config, String tracerName, Stacktraces stacktracePropagation) { DropwizardTracingFilters.registerTracers(environment, config, tracerName); ExceptionMappers.visitExceptionMappers( stacktracePropagation == Stacktraces.PROPAGATE, new ExceptionMappers.Consumer<ExceptionMapper<? extends Throwable>>() { @Override public void accept(ExceptionMapper<? extends Throwable> mapper) { environment.jersey().register(mapper); } }); environment.jersey().register(new OptionalAsNoContentMessageBodyWriter()); }
Source:
public boolean isBeforeCurrent() { System.out.println("createdAt = " + createdAt); System.out.println("question.getInformation().getCreatedAt() = " + question.getInformation().getCreatedAt()); return createdAt.isBefore(question.getInformation().getCreatedAt()); }

Target:
public boolean isBeforeCurrent() { return createdAt.isBefore(question.getInformation().getCreatedAt()); }
Source:
private void authenticateUser(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean basicAuth = false; try { if (StringUtils.isNotEmpty(request.getParameter(BASIC_AUTH))) { basicAuth = Boolean.parseBoolean(request.getParameter(BASIC_AUTH)); } if (basicAuth && StringUtils.isEmpty(request.getHeader(HEADER_AUTHORIZATION))) { throw new AuthenticationException("Unauthorized"); } if (!containsUserCredentials(basicAuth, request)) { throw new AuthenticationException("Credentials Required"); } try { Credentials userCredentials = getUserCredentials(basicAuth, request); AuthenticationUtils.handleCredentials( session, userCredentials.username, userCredentials.password, userCredentials.profile); request.getRequestDispatcher("/sso-redirect").forward(request, response); } catch (SQLException ex) { log.error("Internal Database Error", ex); throw new AuthenticationException("Internal Database Error", ex); } } catch (AuthenticationException ex) { if (basicAuth) { request.getRequestDispatcher("/basic").forward(request, response); } else { request.getRequestDispatcher("/WEB-INF/login.jsp?msg=" + ex.getMessage()).forward(request, response); } } }

Target:
private void authenticateUser(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean needsBasicAuthHandling = enableBasicAuth && !containsUserCredentialsInParams(request.getParameterMap()); try { Credentials userCredentials = getUserCredentials(request); if (userCredentials == null) { throw new AuthenticationException("Credentials Required"); } try { AuthenticationUtils.handleCredentials( session, userCredentials.getUsername(), userCredentials.getPassword(), userCredentials.getProfile()); request.getRequestDispatcher("/sso-redirect").forward(request, response); } catch (SQLException ex) { log.error("Internal Database Error", ex); throw new AuthenticationException("Internal Database Error", ex); } } catch (AuthenticationException ex) { if (needsBasicAuthHandling) { response.sendRedirect(request.getContextPath() + "/basic?" + request.getQueryString()); } else { request.getRequestDispatcher("/WEB-INF/login.jsp?msg=" + ex.getMessage()).forward(request, response); } } }
Source:
public ITmfStateValue increment() throws StateValueTypeException { return TmfStateValue.newValueLong(this.unboxLong() + 1); }

Target:
public ITmfStateValue increment() throws StateValueTypeException { return TmfStateValue.newValueLong(valueLong + 1); }
Source:
public void testValidCondition() throws Exception { final String query = "structuretype = 1"; final String s = SQLUtil.sanitizeParameter( query ); assertNotNull(s); assertEquals(query, s); }

Target:
public void testValidCondition() throws Exception { final String query = "structuretype = 1"; final String s = SQLUtil.sanitizeCondition( query ); assertNotNull(s); assertEquals(query, s); }
Source:
public void enqueue(Lifespan lifespan, List<SerializedPage> pages) { checkState(partitions.size() == 1, "Expected exactly one partition"); checkState(lifespanCompletionCallback != null, "lifespanCompletionCallback has to be set before starting enqueue data"); enqueue(lifespan, 0, pages); }

Target:
public void enqueue(Lifespan lifespan, List<SerializedPage> pages) { checkState(partitions.size() == 1, "Expected exactly one partition"); enqueue(lifespan, 0, pages); }
Source:
private Request makeRequest(@Nonnull String type, @Nonnull String sparql, @Nullable String accept) { Request post = httpClient.newRequest(uri); post.method(POST); if (!(timeout.isNegative() || timeout.isZero())) { post.timeout(timeout.toMillis(), MILLISECONDS); } if (accept != null) { post.header("Accept", accept); } final Fields fields = new Fields(); fields.add(type, sparql); final FormContentProvider form = new FormContentProvider(fields, UTF_8); post.content(form); return post; }

Target:
private Request makeRequest(@Nonnull String type, @Nonnull String sparql, @Nullable String accept) { Request post = httpClient.newRequest(uri); post.method(POST); if (!timeout.isNegative()) { post.timeout(timeout.toMillis(), MILLISECONDS); } if (accept != null) { post.header("Accept", accept); } final Fields fields = new Fields(); fields.add(type, sparql); final FormContentProvider form = new FormContentProvider(fields, UTF_8); post.content(form); return post; }
Source:
private boolean validatePerson(GluuCustomPerson person) throws Exception { GluuCustomPerson gluuCustomPerson = personService.getPersonByUid(person.getUid()); if (gluuCustomPerson != null){ if(!update){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "Add User failed. Uid already exist: %s", gluuCustomPerson.getUid()); }else{ facesMessages.add(FacesMessage.SEVERITY_ERROR, "Update User failed. Uid already exist: %s", gluuCustomPerson.getUid()); } return false; } gluuCustomPerson = personService.getPersonByEmail(person.getMail()); if (gluuCustomPerson != null){ if(!update){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "Add User failed. Mail id already exist: %s", gluuCustomPerson.getMail()); }else{ facesMessages.add(FacesMessage.SEVERITY_ERROR, "Update User failed. Mail id already exist: %s", gluuCustomPerson.getMail()); } return false; } return true; }

Target:
private boolean validatePerson(GluuCustomPerson person) throws Exception { List<GluuCustomPerson> gluuCustomPersons = personService.getPersonsByUid(person.getUid()); if (gluuCustomPersons != null){ if(!update){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "#{msg['UpdatePersonAction.faileAddUserUidExist']} %s", person.getUid()); return false; }else{ if(gluuCustomPersons.size()>0){ for(GluuCustomPerson gluuCustomPerson : gluuCustomPersons){ if(!gluuCustomPerson.getInum().trim().equals(person.getInum())){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "#{msg['UpdatePersonAction.faileUpdateUserUidExist']} %s", person.getUid()); return false; } } } } } gluuCustomPersons = personService.getPersonsByEmail(person.getMail()); if (gluuCustomPersons != null){ if(!update){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "#{msg['UpdatePersonAction.faileAddUserMailidExist']} %s", person.getMail()); return false; }else{ if(gluuCustomPersons.size()>0){ for(GluuCustomPerson gluuCustomPerson : gluuCustomPersons){ if(!gluuCustomPerson.getInum().trim().equals(person.getInum())){ facesMessages.add(FacesMessage.SEVERITY_ERROR, "#{msg['UpdatePersonAction.faileUpdateUserMailidExist']} %s", person.getMail()); return false; } } } } } return true; }
Source:
public static synchronized Pair<Set<Range<Token>>, Set<Range<Token>>> getAvailableRanges(String keyspace, IPartitioner partitioner) { String query = "SELECT * FROM system.%s WHERE keyspace_name=?"; UntypedResultSet rs = executeInternal(format(query, AVAILABLE_RANGES_V2), keyspace); Set<Range<Token>> full = new HashSet<>(); Set<Range<Token>> trans = new HashSet<>(); for (UntypedResultSet.Row row : rs) { Optional.ofNullable(row.getSet("full_ranges", BytesType.instance)) .ifPresent(full_ranges -> full_ranges.stream() .map(buf -> byteBufferToRange(buf, partitioner)) .forEach(full::add)); Optional.ofNullable(row.getSet("transient_ranges", BytesType.instance)) .ifPresent(transient_ranges -> transient_ranges.stream() .map(buf -> byteBufferToRange(buf, partitioner)) .forEach(trans::add)); } return Pair.create(full, trans); }

Target:
public static synchronized AvailableRanges getAvailableRanges(String keyspace, IPartitioner partitioner) { String query = "SELECT * FROM system.%s WHERE keyspace_name=?"; UntypedResultSet rs = executeInternal(format(query, AVAILABLE_RANGES_V2), keyspace); ImmutableSet.Builder<Range<Token>> full = new ImmutableSet.Builder<>(); ImmutableSet.Builder<Range<Token>> trans = new ImmutableSet.Builder<>(); for (UntypedResultSet.Row row : rs) { Optional.ofNullable(row.getSet("full_ranges", BytesType.instance)) .ifPresent(full_ranges -> full_ranges.stream() .map(buf -> byteBufferToRange(buf, partitioner)) .forEach(full::add)); Optional.ofNullable(row.getSet("transient_ranges", BytesType.instance)) .ifPresent(transient_ranges -> transient_ranges.stream() .map(buf -> byteBufferToRange(buf, partitioner)) .forEach(trans::add)); } return new AvailableRanges(full.build(), trans.build()); }
Source:
private static void handleCounterAspect(ITmfEvent event, ITmfStateSystemBuilder ss, CounterAspect aspect, int rootQuark) { String[] groupIds = aspect.getGroupIds(); int quark = (groupIds.length > 0) ? ss.getQuarkRelativeAndAdd(rootQuark, groupIds) : rootQuark; quark = ss.getQuarkRelativeAndAdd(quark, aspect.getName()); Long eventContent = aspect.resolve(event); ss.modifyAttribute(event.getTimestamp().toNanos(), eventContent == null ? null : eventContent, quark); }

Target:
private static void handleCounterAspect(ITmfEvent event, ITmfStateSystemBuilder ss, CounterAspect aspect, int rootQuark) { String[] groupIds = aspect.getGroupIds(); int quark = (groupIds.length > 0) ? ss.getQuarkRelativeAndAdd(rootQuark, groupIds) : rootQuark; quark = ss.getQuarkRelativeAndAdd(quark, aspect.getName()); Long eventContent = aspect.resolve(event); ss.modifyAttribute(event.getTimestamp().toNanos(), eventContent, quark); }
Source:
public void close() { workPlanOrchestrator.close(); streamOrchestrator.close(); }

Target:
public void close() { try ( Closer<IOException> closer = new Closer<>() ) { closer.push( ElasticsearchWorkOrchestrator::close, workPlanOrchestrator ); closer.push( ElasticsearchWorkOrchestrator::close, streamOrchestrator ); } catch (IOException e) { throw log.failedToShutdownIndexManager( hibernateSearchIndexName, e, indexingBackendContext.getEventContext() ); } }
Source:
void writeMetadata(BinaryMetadata binMeta) { if (!CU.isPersistenceEnabled(ctx.config())) return; try { File file = new File(workDir, binMeta.typeId() + ".bin"); byte[] marshalled = U.marshal(ctx, binMeta); if (ctx.config() != null && ctx.config().getDataStorageConfiguration() != null && ctx.config().getDataStorageConfiguration().getFileIOFactory() != null) { try (final FileIO out = ctx.config().getDataStorageConfiguration().getFileIOFactory().create(file)) { out.write(marshalled, 0, marshalled.length); } } else { try (FileOutputStream out = new FileOutputStream(file, false)) { out.write(marshalled); } } } catch (Exception e) { U.error(log, "Failed to save metadata for typeId: " + binMeta.typeId() + "; exception was thrown: " + e.getMessage()); ctx.failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e)); } }

Target:
void writeMetadata(BinaryMetadata binMeta) { if (!CU.isPersistenceEnabled(ctx.config())) return; try { File file = new File(workDir, binMeta.typeId() + ".bin"); byte[] marshalled = U.marshal(ctx, binMeta); try (final FileIO out = fileIOFactory.create(file)) { int left = marshalled.length; while ((left -= out.writeFully(marshalled, 0, Math.min(marshalled.length, left))) > 0) ; out.force(); } } catch (Exception e) { final String msg = "Failed to save metadata for typeId: " + binMeta.typeId() + "; exception was thrown: " + e.getMessage(); U.error(log, msg); ctx.failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e)); throw new IgniteException(msg, e); } }