auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean comapareBaseEncodedImagesBasedOnBytes(String base1, String base2) { Base64 coder = new Base64(); byte[] baseInBytes1 = coder.decode(base1); byte[] baseInBytes2 = coder.decode(base2); boolean isTheSame = false; if (Arrays.equals(baseInBytes1, baseInBytes2)) { isTheSame = true; } return isTheSame; }

Target:
public boolean comapareBaseEncodedImagesBasedOnBytes(String base1, String base2) { Base64 coder = new Base64(); byte[] baseInBytes1 = coder.decode(base1); byte[] baseInBytes2 = coder.decode(base2); if (Arrays.equals(baseInBytes1, baseInBytes2)) { return true; } return false; }
Source:
private boolean checkIfModelIsDuplicate(FenceAgentModel model, FenceAgentModel concurrentExistingModel) { if (model.getManagementIp().getEntity().equals(concurrentExistingModel.getManagementIp().getEntity())) { model.getManagementIp().setIsValid(true); model.getManagementIp().getInvalidityReasons().clear(); model.getManagementIp().getInvalidityReasons().add(constants.duplicateFenceAgentManagementIp()); model.getManagementIp().setIsValid(false); } return model.getManagementIp().getIsValid(); }

Target:
private boolean checkIfModelIsDuplicate(FenceAgentModel model, FenceAgentModel concurrentExistingModel) { if (model.getManagementIp().getEntity().equals(concurrentExistingModel.getManagementIp().getEntity())) { model.getManagementIp().setIsValid(true); model.getManagementIp().getInvalidityReasons().add(constants.duplicateFenceAgentManagementIp()); model.getManagementIp().setIsValid(false); } return model.getManagementIp().getIsValid(); }
Source:
private RepositorySystemSession newSession(RepositorySystem system) { ArtifactRepositoryPreference artifactRepositoryPreference = new ArtifactRepositoryPreference(); artifactRepositoryPreference.defaultValue(artifactRepositoryPreference); DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); String global = artifactRepositoryPreference.getGlobalM2RepoDir(); if (global == null) { global = "repositories" + File.separator + "kie" + File.separator + "global"; log.info("using fallback {}", global); } LocalRepository localRepo = new LocalRepository(global); session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo)); return session; }

Target:
private RepositorySystemSession newSession(RepositorySystem system) { DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); LocalRepository localRepo = new LocalRepository(ArtifactRepositoryPreference.getGlobalM2RepoDirWithFallback()); session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo)); return session; }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logs); setupToolbar(); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this); mLogsRecycler = findViewById(R.id.log_recycler); mLogsRecycler.setHasFixedSize(true); mLogsRecycler.setLayoutManager(mLayoutManager); setTitle(getText(R.string.actionbar_logger)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Button deleteHistoryButton = findViewById(R.id.deleteLogHistoryButton); Button sendHistoryButton = findViewById(R.id.sendLogHistoryButton); deleteHistoryButton.setOnClickListener(v -> { Log_OC.deleteHistoryLogging(); finish(); }); sendHistoryButton.setOnClickListener(v -> sendMail()); if (savedInstanceState == null) { if (mLogPath != null) { mLogDIR = new File(mLogPath); } if (mLogDIR != null && mLogDIR.isDirectory()) { showLoadingDialog(); LoadingLogTask task = new LoadingLogTask(); task.execute(); } } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logs); setupToolbar(); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); mLogsRecycler = findViewById(R.id.log_recycler); mLogsRecycler.setHasFixedSize(true); mLogsRecycler.setLayoutManager(layoutManager); setTitle(getText(R.string.actionbar_logger)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Button deleteHistoryButton = findViewById(R.id.deleteLogHistoryButton); Button sendHistoryButton = findViewById(R.id.sendLogHistoryButton); deleteHistoryButton.setOnClickListener(v -> { Log_OC.deleteHistoryLogging(); finish(); }); sendHistoryButton.setOnClickListener(v -> sendMail()); if (savedInstanceState == null) { if (mLogPath != null) { mLogDIR = new File(mLogPath); } if (mLogDIR != null && mLogDIR.isDirectory()) { showLoadingDialog(); LoadingLogTask task = new LoadingLogTask(); task.execute(); } } }
Source:
private void save(File dir) { File f = new File(dir, MAP_FILE); try { try (AtomicFileWriter w = new AtomicFileWriter(f)) { try { for (Map.Entry<String, Integer> entry : idToNumber.entrySet()) { w.write(entry.getKey() + ' ' + entry.getValue() + '\n'); } w.commit(); } finally { w.abort(); } } } catch (IOException x) { LOGGER.log(WARNING, "could not save changes to " + f, x); } }

Target:
private void save(File dir) { File f = new File(dir, MAP_FILE); try (AtomicFileWriter w = new AtomicFileWriter(f)) { try { for (Map.Entry<String,Integer> entry : idToNumber.entrySet()) { w.write(entry.getKey() + ' ' + entry.getValue() + '\n'); } w.commit(); } finally { w.abort(); } } catch (IOException x) { LOGGER.log(WARNING, "could not save changes to " + f, x); } }
Source:
private JsonObject getEffectiveFilter(JsonArray typeFilters) { JsonArray filters = new JsonArray(); JsonObject tenantFilter = getTenantIdFilter(); if ( tenantFilter != null ) { filters.add( tenantFilter ); } filters.add( ToElasticsearch.condition( "should", typeFilters ) ); QueryFilterset facetFilter = getFacetManager().getFacetFilterset(); if ( ! facetFilter.isEmpty() ) { filters.add( ToElasticsearch.fromQueryFilterset( facetFilter ) ); } return ToElasticsearch.condition( "must", filters ); }

Target:
private JsonObject getEffectiveFilter(JsonArray typeFilters) { JsonArray filters = new JsonArray(); JsonObject tenantFilter = getTenantIdFilter(); if ( tenantFilter != null ) { filters.add( tenantFilter ); } filters.add( ToElasticsearch.condition( "should", typeFilters ) ); for ( Query query : getFacetManager().getFacetFilters().getFilterQueries() ) { filters.add( ToElasticsearch.fromLuceneQuery( query ) ); } return ToElasticsearch.condition( "must", filters ); }
Source:
public void onMatch(RelOptRuleCall call) { final Filter filter = call.rel(0); final Correlate corr = call.rel(1); final List<RexNode> aboveFilters = RelOptUtil.conjunctions(filter.getCondition()); final List<RexNode> leftFilters = new ArrayList<>(); final List<RexNode> rightFilters = new ArrayList<>(); RelOptUtil.classifyFilters( corr, aboveFilters, JoinRelType.INNER, false, corr.getJoinType().returnsJustFirstInput() || !corr.getJoinType().toJoinType().generatesNullsOnLeft(), !corr.getJoinType().returnsJustFirstInput() && !corr.getJoinType().toJoinType().generatesNullsOnRight(), aboveFilters, leftFilters, rightFilters); if (leftFilters.isEmpty() && rightFilters.isEmpty()) { return; } final RexBuilder rexBuilder = corr.getCluster().getRexBuilder(); final RelBuilder relBuilder = call.builder(); final RelNode leftRel = relBuilder.push(corr.getLeft()).filter(leftFilters).build(); final RelNode rightRel = relBuilder.push(corr.getRight()).filter(rightFilters).build(); RelNode newCorrRel = corr.copy(corr.getTraitSet(), ImmutableList.of(leftRel, rightRel)); call.getPlanner().onCopy(corr, newCorrRel); if (!leftFilters.isEmpty()) { call.getPlanner().onCopy(filter, leftRel); } if (!rightFilters.isEmpty()) { call.getPlanner().onCopy(filter, rightRel); } relBuilder.push(newCorrRel); relBuilder.filter( RexUtil.fixUp(rexBuilder, aboveFilters, RelOptUtil.getFieldTypeList(relBuilder.peek().getRowType()))); call.transformTo(relBuilder.build()); }

Target:
public void onMatch(RelOptRuleCall call) { final Filter filter = call.rel(0); final Correlate corr = call.rel(1); final List<RexNode> aboveFilters = RelOptUtil.conjunctions(filter.getCondition()); final List<RexNode> leftFilters = new ArrayList<>(); final List<RexNode> rightFilters = new ArrayList<>(); RelOptUtil.classifyFilters( corr, aboveFilters, JoinRelType.INNER, false, true, corr.getJoinType() == SemiJoinType.INNER, aboveFilters, leftFilters, rightFilters); if (leftFilters.isEmpty() && rightFilters.isEmpty()) { return; } final RexBuilder rexBuilder = corr.getCluster().getRexBuilder(); final RelBuilder relBuilder = call.builder(); final RelNode leftRel = relBuilder.push(corr.getLeft()).filter(leftFilters).build(); final RelNode rightRel = relBuilder.push(corr.getRight()).filter(rightFilters).build(); RelNode newCorrRel = corr.copy(corr.getTraitSet(), ImmutableList.of(leftRel, rightRel)); call.getPlanner().onCopy(corr, newCorrRel); if (!leftFilters.isEmpty()) { call.getPlanner().onCopy(filter, leftRel); } if (!rightFilters.isEmpty()) { call.getPlanner().onCopy(filter, rightRel); } relBuilder.push(newCorrRel); relBuilder.filter( RexUtil.fixUp(rexBuilder, aboveFilters, RelOptUtil.getFieldTypeList(relBuilder.peek().getRowType()))); call.transformTo(relBuilder.build()); }
Source:
public void testBoldWithWhitespace() { String html; Pattern expectedPattern = Pattern.compile("<body><p>normal\\s*<b>\\s*bold text\\s*</b>\\s*normal</p></body>"); html = parser.parseToHtml("normal ''' bold text''' normal"); TestUtil.println(html); assertTrue(expectedPattern.matcher(html).find()); html = parser.parseToHtml("normal '''bold text ''' normal"); TestUtil.println(html); assertTrue(expectedPattern.matcher(html).find()); html = parser.parseToHtml("normal ''' bold text ''' normal"); TestUtil.println(html); assertTrue(expectedPattern.matcher(html).find()); }

Target:
public void testBoldWithWhitespace() { String html; html = parser.parseToHtml("normal ''' bold text''' normal"); TestUtil.println(html); assertTrue(html.contains("<body><p>normal <b> bold text</b> normal</p></body>")); html = parser.parseToHtml("normal '''bold text ''' normal"); TestUtil.println(html); assertTrue(html.contains("<body><p>normal <b>bold text </b> normal</p></body>")); html = parser.parseToHtml("normal ''' bold text ''' normal"); TestUtil.println(html); assertTrue(html.contains("<body><p>normal <b> bold text </b> normal</p></body>")); }
Source:
public SecurityGroup getSecurityGroupById(String id) { checkNotNull(id, "id"); ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(id); String zone = zoneAndId.getZone(); String groupId = zoneAndId.getId(); Optional<? extends SecurityGroupApi> sgApi = client.getSecurityGroupExtensionForZone(zone); if (!sgApi.isPresent()) { return null; } SecurityGroupInZone rawGroup = new SecurityGroupInZone(sgApi.get().get(groupId), zone); return groupConverter.apply(rawGroup); }

Target:
public SecurityGroup getSecurityGroupById(String id) { ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(checkNotNull(id, "id")); String zone = zoneAndId.getZone(); String groupId = zoneAndId.getId(); Optional<? extends SecurityGroupApi> sgApi = api.getSecurityGroupExtensionForZone(zone); if (!sgApi.isPresent()) { return null; } SecurityGroupInZone rawGroup = new SecurityGroupInZone(sgApi.get().get(groupId), zone); return groupConverter.apply(rawGroup); }
Source:
private Runnable createRunnable(final Pair<HttpRequest, List<Message>> request) { return new Runnable() { @Override public void run() { Stopwatch stopwatch = timer.start(); try { HttpResponse response = client.executeWithLoadBalancer(request.first()); byte[] bytes = IOUtils.toByteArray(response.getInputStream()); Map<String, Object> result = jsonMapper.readValue(bytes, new TypeReference<Map<String, Object>>(){}); List items = (List) result.get("items"); for (int i = 0; i < items.size(); ++i) { String routingKey = request.second().get(i).getRoutingKey(); Map<String, Object> resPerMessage = (Map)((Map)(items.get(i))).get("create"); if (isFailed(resPerMessage) && !getErrorMessage(resPerMessage).contains("DocumentAlreadyExistsException")) { log.error("Failed with: " + resPerMessage.get("error")); Servo.getCounter( MonitorConfig.builder(REJECTED_ROW) .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, routingKey) .build()).increment(); recover(request.second().get(i)); } else { Servo.getCounter( MonitorConfig.builder(INDEXED_ROW) .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, routingKey) .build()).increment(); } } throughput.increment(items.size()); } catch (Exception e) { log.error("Exception on bulk execute: " + e.getMessage(), e); for (Message m : request.second()) { Servo.getCounter( MonitorConfig.builder(REJECTED_ROW) .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, m.getRoutingKey()) .build()).increment(); } } finally { stopwatch.stop(); } } }; }

Target:
private Runnable createRunnable(final Pair<HttpRequest, List<Message>> request) { return new Runnable() { @Override public void run() { Stopwatch stopwatch = timer.start(); HttpResponse response = null; try { response = client.executeWithLoadBalancer(request.first()); Map<String, Object> result = jsonMapper.readValue( response.getInputStream(), new TypeReference<Map<String, Object>>(){}); List items = (List) result.get("items"); for (int i = 0; i < items.size(); ++i) { String routingKey = request.second().get(i).getRoutingKey(); Map<String, Object> resPerMessage = (Map)((Map)(items.get(i))).get("create"); if (isFailed(resPerMessage) && !getErrorMessage(resPerMessage).contains("DocumentAlreadyExistsException")) { log.error("Failed with: " + resPerMessage.get("error")); Servo.getCounter( MonitorConfig.builder(REJECTED_ROW) .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, routingKey) .build()).increment(); recover(request.second().get(i)); } else { Servo.getCounter( MonitorConfig.builder(INDEXED_ROW) .withTag(SINK_ID, getSinkId()) .withTag(TagKey.ROUTING_KEY, routingKey) .build()).increment(); } } throughput.increment(items.size()); } catch (Exception e) { log.error("Exception on bulk execute: " + e.getMessage(), e); Servo.getCounter("bulkException").increment(); for (Message m : request.second()) { writeTo(new DefaultMessageContainer(m, jsonMapper)); } } finally { if (response != null) { response.close(); } stopwatch.stop(); } } }; }
Source:
private void createOpenShiftService(String workspaceID, Set<String> exposedPorts, Map<String, String> additionalLabels) { Map<String, String> selector = new HashMap<>(); selector.put(OPENSHIFT_DEPLOYMENT_LABEL, CHE_OPENSHIFT_RESOURCES_PREFIX + workspaceID); List<ServicePort> ports = kubernetesService.getServicePortsFrom(exposedPorts); Service service = openShiftClient .services() .inNamespace(this.cheOpenShiftProjectName) .createNew() .withNewMetadata() .withName(CHE_OPENSHIFT_RESOURCES_PREFIX + workspaceID) .withAnnotations(kubernetesLabelConverter.labelsToNames(additionalLabels)) .endMetadata() .withNewSpec() .withType(OPENSHIFT_SERVICE_TYPE_NODE_PORT) .withSelector(selector) .withPorts(ports) .endSpec() .done(); LOG.info(String.format("OpenShift service %s created", service.getMetadata().getName())); }

Target:
private void createOpenShiftService(String workspaceID, Set<String> exposedPorts, Map<String, String> additionalLabels) { Map<String, String> selector = Collections.singletonMap(OPENSHIFT_DEPLOYMENT_LABEL, CHE_OPENSHIFT_RESOURCES_PREFIX + workspaceID); List<ServicePort> ports = kubernetesService.getServicePortsFrom(exposedPorts); Service service = openShiftClient .services() .inNamespace(this.openShiftCheProjectName) .createNew() .withNewMetadata() .withName(CHE_OPENSHIFT_RESOURCES_PREFIX + workspaceID) .withAnnotations(kubernetesLabelConverter.labelsToNames(additionalLabels)) .endMetadata() .withNewSpec() .withType(OPENSHIFT_SERVICE_TYPE_NODE_PORT) .withSelector(selector) .withPorts(ports) .endSpec() .done(); LOG.info("OpenShift service created", service.getMetadata().getName()); }
Source:
public void saveOrder_shouldFailIfDrugNonCodedInPreviousDrugOrderDoesNotMatchThatOfTheRevisedDrugOrder() throws Exception { executeDataSet("org/openmrs/api/include/OrderServiceTest-nonCodedDrugs.xml"); DrugOrder previousOrder = (DrugOrder)orderService.getOrder(584); DrugOrder order = previousOrder.cloneForRevision(); String drugNonCodedParacetemol = "non coded paracetemol"; order.setDateActivated(new Date()); order.setOrderer(providerService.getProvider(1)); order.setEncounter(encounterService.getEncounter(6)); assertFalse(previousOrder.getDrugNonCoded().equals(drugNonCodedParacetemol)); order.setDrugNonCoded(drugNonCodedParacetemol); order.setPreviousOrder(previousOrder); expectedException.expect(APIException.class); expectedException.expectMessage("The orderable of the previous order and the new one order don't match"); orderService.saveOrder(order, null); }

Target:
public void saveOrder_shouldFailIfDrugNonCodedInPreviousDrugOrderDoesNotMatchThatOfTheRevisedDrugOrder() throws Exception { executeDataSet("org/openmrs/api/include/OrderServiceTest-nonCodedDrugs.xml"); DrugOrder previousOrder = (DrugOrder) orderService.getOrder(584); DrugOrder order = previousOrder.cloneForRevision(); String drugNonCodedParacetemol = "non coded aspirin"; order.setDateActivated(new Date()); order.setOrderer(providerService.getProvider(1)); order.setEncounter(encounterService.getEncounter(6)); assertFalse(previousOrder.getDrugNonCoded().equals(drugNonCodedParacetemol)); order.setDrugNonCoded(drugNonCodedParacetemol); order.setPreviousOrder(previousOrder); expectedException.expect(APIException.class); expectedException.expectMessage("The orderable of the previous order and the new one order don't match"); orderService.saveOrder(order, null); }
Source:
private void relinkThumbs() { if (RelinkImagesTask.getInstance() != null && RelinkImagesTask.getInstance().getStatus() == Status.RUNNING) { UIHelper.createYesNoDialog( this , getResources().getString(R.string.relink_stop_question) , getResources().getString(R.string.relink_stop_question2) , new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { RelinkImagesTask.getInstance().cancel(true); } } }).show(); return; } final DisplaySettingsActivity dsa = this; UIHelper.createYesNoDialog( this , getResources().getString(R.string.relink_question) , getResources().getString(R.string.relink_question2) , new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { String rootPath = UIHelper.getImageRoot(dsa); RelinkImagesTask task = RelinkImagesTask.getInstance(rootPath, dsa, Constants.PREF_RELINK_THUMB_IMAGES); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else task.execute(); } } }).show(); }

Target:
private void relinkThumbs() { String rootPath = UIHelper.getImageRoot(this); RelinkImagesTask task = RelinkImagesTask.getInstance(rootPath, this, Constants.PREF_RELINK_THUMB_IMAGES); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else task.execute(); }
Source:
public String getTitle() { while (session.getFrame().getSteps().size() > 0 && (!SessionFrame.STATE_DATUM_VAL.equals(session.getNeededData()) || !(session.getNeededDatum() != null && session.getNeededDatum().getLongDetail() != null))) { session.stepBack(); } if(session.getFrame().getSteps().size() == 0) { return null;} EvaluationContext ec = getEvaluationContext(); String value = session.getPoppedStep().getValue(); SessionDatum datum = session.getNeededDatum(); TreeReference nodesetRef = datum.getNodeset().clone(); Vector<XPathExpression> predicates = nodesetRef.getPredicate(nodesetRef.size() -1); predicates.add(new XPathEqExpr(true, XPathReference.getPathExpr(datum.getValue()), new XPathStringLiteral(value))); Vector<TreeReference> elements = ec.expandReference(nodesetRef); if(elements.size() != 1 ) { return null;} EvaluationContext element = new EvaluationContext(ec, elements.firstElement()); Text t = session.getDetail(datum.getLongDetail()).getTitle().getText(); boolean isPrettyPrint = true; try { String outcome = t.evaluate(); if(outcome != null) { isPrettyPrint = false; } } catch(Exception e) { } if(isPrettyPrint) { return t.evaluate(element); } else { SqlStorage<ACase> storage = CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class); try { ACase ourCase = storage.getRecordForValue(ACase.INDEX_CASE_ID, value); if(ourCase != null) { return ourCase.getName(); } else { return null; } } catch(Exception e) { return null; } } }

Target:
public String getTitle() { while (session.getFrame().getSteps().size() > 0 && (!SessionFrame.STATE_DATUM_VAL.equals(session.getNeededData()) || session.getNeededDatum().getLongDetail() == null)) { session.stepBack(); } if(session.getFrame().getSteps().size() == 0) { return null;} EvaluationContext ec = getEvaluationContext(); String value = session.getPoppedStep().getValue(); SessionDatum datum = session.getNeededDatum(); TreeReference nodesetRef = datum.getNodeset().clone(); Vector<XPathExpression> predicates = nodesetRef.getPredicate(nodesetRef.size() -1); predicates.add(new XPathEqExpr(true, XPathReference.getPathExpr(datum.getValue()), new XPathStringLiteral(value))); Vector<TreeReference> elements = ec.expandReference(nodesetRef); if(elements.size() != 1 ) { return null;} EvaluationContext element = new EvaluationContext(ec, elements.firstElement()); Text t = session.getDetail(datum.getLongDetail()).getTitle().getText(); boolean isPrettyPrint = true; try { String outcome = t.evaluate(); if(outcome != null) { isPrettyPrint = false; } } catch(Exception e) { } if(isPrettyPrint) { return t.evaluate(element); } else { SqlStorage<ACase> storage = CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class); try { ACase ourCase = storage.getRecordForValue(ACase.INDEX_CASE_ID, value); if(ourCase != null) { return ourCase.getName(); } else { return null; } } catch(Exception e) { return null; } } }
Source:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (!operation.hasDefined(CommonAttributes.JGROUPS_CLUSTER.getName()) && operation.hasDefined(CommonAttributes.LEGACY_JGROUPS_CLUSTER.getName())) { operation.get(CommonAttributes.JGROUPS_CLUSTER.getName()).set(operation.get(CommonAttributes.LEGACY_JGROUPS_CLUSTER.getName())); operation.remove(CommonAttributes.LEGACY_JGROUPS_CLUSTER.getName()); } if (operation.hasDefined(JGROUPS_CLUSTER.getName())) { if (operation.hasDefined(JGROUPS_CHANNEL_FACTORY.getName()) && !operation.hasDefined(JGROUPS_CHANNEL.getName())) { String channel = operation.get(JGROUPS_CLUSTER.getName()).asString(); operation.get(JGROUPS_CHANNEL.getName()).set(channel); PathAddress channelAddress = context.getCurrentAddress().getParent().getParent().getParent().append(ModelDescriptionConstants.SUBSYSTEM, "jgroups").append("channel", channel); ModelNode addChannelOperation = Util.createAddOperation(channelAddress); addChannelOperation.get("stack").set(operation.get(JGROUPS_CHANNEL_FACTORY.getName())); System.out.println("Executing " + addChannelOperation); context.addStep(addChannelOperation, AddIfAbsentStepHandler.INSTANCE, OperationContext.Stage.MODEL); } } super.execute(context, operation); }

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { CommonAttributes.renameChannelToCluster(operation); if (operation.hasDefined(JGROUPS_CLUSTER.getName())) { if (operation.hasDefined(JGROUPS_CHANNEL_FACTORY.getName()) && !operation.hasDefined(JGROUPS_CHANNEL.getName())) { String channel = operation.get(JGROUPS_CLUSTER.getName()).asString(); operation.get(JGROUPS_CHANNEL.getName()).set(channel); PathAddress channelAddress = context.getCurrentAddress().getParent().getParent().getParent().append(ModelDescriptionConstants.SUBSYSTEM, "jgroups").append("channel", channel); ModelNode addChannelOperation = Util.createAddOperation(channelAddress); addChannelOperation.get("stack").set(operation.get(JGROUPS_CHANNEL_FACTORY.getName())); context.addStep(addChannelOperation, AddIfAbsentStepHandler.INSTANCE, OperationContext.Stage.MODEL); } } super.execute(context, operation); }
Source:
public void dispose() { menuManager.dispose(); if (toolbarManager != null) { ((ToolBarManager) toolbarManager).dispose(); } super.dispose(); }

Target:
public void dispose() { menuManager.dispose(); if (toolbarManager != null) { toolbarManager.dispose(); } super.dispose(); }
Source:
public void should_hash_consistently() { ByteBuffer byteBuffer = Bytes.fromHexString("0xCAFEBABE"); Token tokenA = factory.hash(byteBuffer); Token tokenB = factory.hash(byteBuffer); assertThat(tokenA).isEqualTo(factory.fromString("59959303159920881837560881824507314222")); assertThat(tokenA).isEqualTo(tokenB); }

Target:
public void should_hash_consistently() { ByteBuffer byteBuffer = Bytes.fromHexString("0xCAFEBABE"); Token tokenA = factory.hash(byteBuffer); Token tokenB = factory.hash(byteBuffer); assertThat(tokenA) .isEqualTo(factory.fromString("59959303159920881837560881824507314222")) .isEqualTo(tokenB); }
Source:
protected void executeQueryCommand() { List<Disk> diskList = DbFacade.getInstance() .getDiskDao() .getAllAttachableDisksByPoolId(getParameters().getStoragePoolId(), getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (CollectionUtils.isEmpty(diskList)) { setReturnValue(new ArrayList<>()); return; } VM vm = DbFacade.getInstance().getVmDao().get(getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (vm == null) { setReturnValue(new ArrayList<>()); return; } List<Disk> filteredDiskList = new ArrayList<Disk>(); for (Disk disk : diskList) { if (DiskValidator.isDiskInterfaceSupportedByOs(disk.getDiskInterface(), vm.getOs(), vm.getVdsGroupCompatibilityVersion())) { filteredDiskList.add(disk); } } setReturnValue(filteredDiskList); }

Target:
protected void executeQueryCommand() { List<Disk> diskList = DbFacade.getInstance() .getDiskDao() .getAllAttachableDisksByPoolId(getParameters().getStoragePoolId(), getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (CollectionUtils.isEmpty(diskList)) { setReturnValue(new ArrayList<>()); return; } VM vm = DbFacade.getInstance().getVmDao().get(getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (vm == null) { setReturnValue(new ArrayList<>()); return; } List<Disk> filteredDiskList = new ArrayList<>(); for (Disk disk : diskList) { if (DiskValidator.isDiskInterfaceSupportedByOs(disk.getDiskInterface(), vm.getOs(), vm.getVdsGroupCompatibilityVersion())) { filteredDiskList.add(disk); } } setReturnValue(filteredDiskList); }
Source:
static HttpHeaders getHeaders(StripeRequest request) { Map<String, List<String>> headerMap = new HashMap<>(request.headers().map()); headerMap.put("User-Agent", Arrays.asList(buildUserAgentString())); headerMap.put("X-Stripe-Client-User-Agent", Arrays.asList(buildXStripeClientUserAgentString())); return HttpHeaders.of(headerMap); }

Target:
static HttpHeaders getHeaders(StripeRequest request) { Map<String, List<String>> userAgentHeadersMap = new HashMap<>(); userAgentHeadersMap.put("User-Agent", Arrays.asList(buildUserAgentString())); userAgentHeadersMap.put( "X-Stripe-Client-User-Agent", Arrays.asList(buildXStripeClientUserAgentString())); return request.headers().withAdditionalHeaders(userAgentHeadersMap); }
Source:
Field getField(ColumnIdent path, Operation operation) throws UnsupportedOperationException, ColumnUnknownException; QualifiedName getQualifiedName(); List<Symbol> outputs(); WhereClause where(); List<Symbol> groupBy(); @Nullable HavingClause having(); @Nullable OrderBy orderBy(); @Nullable Symbol limit(); @Nullable Symbol offset(); boolean hasAggregates(); @Override default void visitSymbols(Consumer<? super Symbol> consumer) { for (Symbol output : outputs()) { consumer.accept(output); } where().accept(consumer); for (Symbol groupKey : groupBy()) { consumer.accept(groupKey); } HavingClause having = having(); if (having != null) { having.accept(consumer); } OrderBy orderBy = orderBy(); if (orderBy != null) { orderBy.accept(consumer); } Symbol limit = limit(); if (limit != null) { consumer.accept(limit); } Symbol offset = offset(); if (offset != null) { consumer.accept(offset); } }

Target:
Field getField(ColumnIdent path, Operation operation) throws UnsupportedOperationException, ColumnUnknownException; @Nonnull List<Field> fields(); QualifiedName getQualifiedName(); List<Symbol> outputs(); WhereClause where(); List<Symbol> groupBy(); @Nullable HavingClause having(); @Nullable OrderBy orderBy(); @Nullable Symbol limit(); @Nullable Symbol offset(); boolean hasAggregates(); @Override default void visitSymbols(Consumer<? super Symbol> consumer) { for (Symbol output : outputs()) { consumer.accept(output); } where().accept(consumer); for (Symbol groupKey : groupBy()) { consumer.accept(groupKey); } HavingClause having = having(); if (having != null) { having.accept(consumer); } OrderBy orderBy = orderBy(); if (orderBy != null) { orderBy.accept(consumer); } Symbol limit = limit(); if (limit != null) { consumer.accept(limit); } Symbol offset = offset(); if (offset != null) { consumer.accept(offset); } }
Source:
private void saveUUID(String uuid) { File eclipseUUIDFile = new File(System.getProperty("user.home") + UUID_PATH); if (!eclipseUUIDFile.getParentFile().exists()) { if (!eclipseUUIDFile.getParentFile().mkdirs()) return; } OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(eclipseUUIDFile)); Properties prop = new Properties(); prop.setProperty(PROP_UUID, uuid); prop.setProperty("version", "1"); prop.store(os, ""); } catch (IOException e) { return; } finally { if (os != null) { try { os.close(); } catch (IOException e) { } } } }

Target:
private void saveUUID(String uuid) { File eclipseUUIDFile = new File(System.getProperty("user.home") + UUID_PATH); if (!eclipseUUIDFile.getParentFile().exists()) { if (!eclipseUUIDFile.getParentFile().mkdirs()) return; } try (OutputStream os = new BufferedOutputStream(new FileOutputStream(eclipseUUIDFile))){ Properties prop = new Properties(); prop.setProperty(PROP_UUID, uuid); prop.setProperty("version", "1"); prop.store(os, ""); } catch (IOException e) { return; } }
Source:
public void close() { final int usages = referencing.dropReference(); if (usages > 0) { lock.unlock(); } }

Target:
public void close() { referencing.dropReference(); lock.unlock(); }
Source:
public static String getCssValueFromTheme(Display display, String value) { BundleContext context = FrameworkUtil.getBundle(E4ThemeColor.class).getBundleContext(); try { Object reference = MethodUtils.invokeMethod(context, "getServiceReference", "org.eclipse.e4.ui.css.swt.theme.IThemeManager"); if (reference != null) { Object iThemeManager = MethodUtils.invokeMethod(context, "getService", reference); if (iThemeManager != null) { final Object themeEngine = MethodUtils.invokeMethod(iThemeManager, "getEngineForDisplay", display); if (themeEngine != null) { Shell shell = display.getActiveShell(); if (shell == null) { shell = Iterables.find(Arrays.asList(display.getShells()), new Predicate<Shell>() { @Override public boolean apply(Shell input) { try { Object shellStyle = MethodUtils.invokeMethod(themeEngine, "getStyle", input); if (shellStyle instanceof CSSStyleDeclaration) { return true; } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { return false; } return false; } }, null); } if (shell != null) { Object shellStyle = MethodUtils.invokeMethod(themeEngine, "getStyle", shell); if (shellStyle instanceof CSSStyleDeclaration) { CSSValue cssValue = ((CSSStyleDeclaration) shellStyle).getPropertyCSSValue(value); if (cssValue != null) { return cssValue.getCssText(); } } } } } } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { logOnce(e); return null; } return null; }

Target:
public static String getCssValueFromTheme(Display display, String value) { BundleContext context = FrameworkUtil.getBundle(E4ThemeColor.class).getBundleContext(); try { Object reference = MethodUtils.invokeMethod(context, "getServiceReference", "org.eclipse.e4.ui.css.swt.theme.IThemeManager"); if (reference != null) { Object iThemeManager = MethodUtils.invokeMethod(context, "getService", reference); if (iThemeManager != null) { final Object themeEngine = MethodUtils.invokeMethod(iThemeManager, "getEngineForDisplay", display); if (themeEngine != null) { Shell shell = display.getActiveShell(); if (shell == null) { for (Shell input : display.getShells()) { Object shellStyle = MethodUtils.invokeMethod(themeEngine, "getStyle", input); if (shellStyle instanceof CSSStyleDeclaration) { shell = input; break; } } } if (shell != null) { Object shellStyle = MethodUtils.invokeMethod(themeEngine, "getStyle", shell); if (shellStyle instanceof CSSStyleDeclaration) { CSSValue cssValue = ((CSSStyleDeclaration) shellStyle).getPropertyCSSValue(value); if (cssValue != null) { return cssValue.getCssText(); } } } } } } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { logOnce(e); return null; } return null; }
Source:
@Test public void overrideDoesNotCopyDefaultModifier() { TypeElement classElement = getElement(ExtendsIterableWithDefaultMethods.class); DeclaredType classType = (DeclaredType) classElement.asType(); List<ExecutableElement> methods = methodsIn(elements.getAllMembers(classElement)); ExecutableElement exec = findFirst(methods, "iterator"); Assume.assumeTrue(Util.DEFAULT != null); exec = findFirst(methods, "spliterator"); MethodSpec method = MethodSpec.overriding(exec, classType, types).build(); assertThat(method.toString()).isEqualTo("" + "@java.lang.Override\n" + "public java.util.Spliterator<java.lang.Object> spliterator() {\n" + "}\n"); }

Target:
@Test public void overrideDoesNotCopyDefaultModifier() { TypeElement classElement = getElement(ExtendsIterableWithDefaultMethods.class); DeclaredType classType = (DeclaredType) classElement.asType(); List<ExecutableElement> methods = methodsIn(elements.getAllMembers(classElement)); ExecutableElement exec = findFirst(methods, "iterator"); assume().that(Util.DEFAULT).isNotNull(); exec = findFirst(methods, "spliterator"); MethodSpec method = MethodSpec.overriding(exec, classType, types).build(); assertThat(method.toString()).isEqualTo("" + "@java.lang.Override\n" + "public java.util.Spliterator<java.lang.Object> spliterator() {\n" + "}\n"); }
Source:
static <T> Iterator<T> iteratorFrom(WorkProcessor<T> processor) { return new AbstractIterator<T>() { final Iterator<Optional<T>> yieldingIterator = yieldingIteratorFrom(processor); @Override protected T computeNext() { if (!yieldingIterator.hasNext()) { return endOfData(); } Optional<T> elementOptional = yieldingIterator.next(); if (!elementOptional.isPresent()) { throw new IllegalStateException("Work has yielded"); } return elementOptional.get(); } }; }

Target:
static <T> Iterator<T> iteratorFrom(WorkProcessor<T> processor) { requireNonNull(processor, "processor is null"); return new AbstractIterator<T>() { final Iterator<Optional<T>> yieldingIterator = yieldingIteratorFrom(processor); @Override protected T computeNext() { if (!yieldingIterator.hasNext()) { return endOfData(); } return yieldingIterator.next() .orElseThrow(() -> new IllegalStateException("Cannot iterate over yielding WorkProcessor")); } }; }
Source:
public ModelAndView membershipDetail() { ModelAndView modelAndView = new ModelAndView("/membership-give-edit"); modelAndView.addObject("userGroups", MembershipUserGroup.values()); modelAndView.addObject("membershipLevels", Lists.newArrayList(0, 1, 2, 3, 4, 5)); return modelAndView; }

Target:
public ModelAndView membershipDetail() { ModelAndView modelAndView = new ModelAndView("/membership-give-edit"); modelAndView.addObject("userGroups", MembershipUserGroup.values()); modelAndView.addObject("membershipLevels", Lists.newArrayList(userMembershipService.getAllLevels())); return modelAndView; }
Source:
private boolean createOffheapResource(OffHeapResourceIdentifier identifier, long size) { if (resources.containsKey(identifier)) { return false; } OffHeapResourceImpl offHeapResource = new OffHeapResourceImpl( identifier.getName(), size, (res, update) -> { for (EntityManagementRegistry registry : registries) { Map<String, String> attrs = new HashMap<>(); attrs.put("oldThreshold", String.valueOf(update.old)); attrs.put("threshold", String.valueOf(update.now)); attrs.put("capacity", String.valueOf(res.capacity())); attrs.put("available", String.valueOf(res.available())); registry.pushServerEntityNotification(res.getManagementBinding(), "OFFHEAP_RESOURCE_THRESHOLD_REACHED", attrs); } }, (res, oldCapacity, newCapacity) -> { updateCurrentUsage(newCapacity - oldCapacity); for (EntityManagementRegistry registry : registries) { Map<String, String> attrs = new HashMap<>(); attrs.put("oldCapacity", Long.toString(oldCapacity)); attrs.put("newCapacity", Long.toString(newCapacity)); registry.pushServerEntityNotification(res.getManagementBinding(), "OFFHEAP_RESOURCE_CAPACITY_CHANGED", attrs); } }); resources.put(identifier, offHeapResource); Map<String, Object> properties = new HashMap<>(); properties.put("discriminator", "OffHeapResource"); properties.put("offHeapResourceIdentifier", identifier.getName()); StatisticsManager.createPassThroughStatistic( offHeapResource, "allocatedMemory", new HashSet<>(Arrays.asList("OffHeapResource", "tier")), properties, StatisticType.GAUGE, () -> offHeapResource.capacity() - offHeapResource.available() ); return true; }

Target:
private boolean createOffheapResource(OffHeapResourceIdentifier identifier, long size) { if (resources.containsKey(identifier)) { return false; } OffHeapResourceImpl offHeapResource = new OffHeapResourceImpl( identifier.getName(), size, (res, update) -> { for (EntityManagementRegistry registry : registries) { Map<String, String> attrs = new HashMap<>(); attrs.put("oldThreshold", String.valueOf(update.old)); attrs.put("threshold", String.valueOf(update.now)); attrs.put("capacity", String.valueOf(res.capacity())); attrs.put("available", String.valueOf(res.available())); registry.pushServerEntityNotification(res.getManagementBinding(), "OFFHEAP_RESOURCE_THRESHOLD_REACHED", attrs); } }, (res, oldCapacity, newCapacity) -> { updateCurrentUsage(newCapacity - oldCapacity); for (EntityManagementRegistry registry : registries) { Map<String, String> attrs = new HashMap<>(); attrs.put("oldCapacity", Long.toString(oldCapacity)); attrs.put("newCapacity", Long.toString(newCapacity)); registry.pushServerEntityNotification(res.getManagementBinding(), "OFFHEAP_RESOURCE_CAPACITY_CHANGED", attrs); } }); if (resources.putIfAbsent(identifier, offHeapResource) != null) { return false; } Map<String, Object> properties = new HashMap<>(); properties.put("discriminator", "OffHeapResource"); properties.put("offHeapResourceIdentifier", identifier.getName()); StatisticsManager.createPassThroughStatistic( offHeapResource, "allocatedMemory", new HashSet<>(Arrays.asList("OffHeapResource", "tier")), properties, StatisticType.GAUGE, () -> offHeapResource.capacity() - offHeapResource.available() ); return true; }
Source:
public CourseStudent update(CourseStudent courseStudent, Student student, CourseEnrolmentType courseEnrolmentType, CourseParticipationType participationType, Date enrolmentDate, Boolean lodging, CourseOptionality optionality) throws DuplicateCourseStudentException { EntityManager entityManager = getEntityManager(); List<CourseStudent> courseStudents = listByCourseAndStudent(courseStudent.getCourse(), student); if (!courseStudents.isEmpty()) { for (CourseStudent cs : courseStudents) { if (cs.getId() != courseStudent.getId()) throw new DuplicateCourseStudentException(); } } courseStudent.setStudent(student); courseStudent.setCourseEnrolmentType(courseEnrolmentType); courseStudent.setEnrolmentTime(enrolmentDate); courseStudent.setParticipationType(participationType); courseStudent.setLodging(lodging); courseStudent.setOptionality(optionality); entityManager.persist(courseStudent); courseStudentUpdatedEvent.fire(new CourseStudentUpdatedEvent(courseStudent.getId(), courseStudent.getCourse().getId(), courseStudent.getStudent().getId())); return courseStudent; }

Target:
public CourseStudent update(CourseStudent courseStudent, Student student, CourseEnrolmentType courseEnrolmentType, CourseParticipationType participationType, Date enrolmentDate, Boolean lodging, CourseOptionality optionality) throws DuplicateCourseStudentException { EntityManager entityManager = getEntityManager(); List<CourseStudent> courseStudents = listByCourseAndStudent(courseStudent.getCourse(), student); if (!courseStudents.isEmpty()) { for (CourseStudent courseStudent2 : courseStudents) { if (courseStudent2.getId() != courseStudent.getId()) throw new DuplicateCourseStudentException(); } } courseStudent.setStudent(student); courseStudent.setCourseEnrolmentType(courseEnrolmentType); courseStudent.setEnrolmentTime(enrolmentDate); courseStudent.setParticipationType(participationType); courseStudent.setLodging(lodging); courseStudent.setOptionality(optionality); entityManager.persist(courseStudent); courseStudentUpdatedEvent.fire(new CourseStudentUpdatedEvent(courseStudent.getId(), courseStudent.getCourse().getId(), courseStudent.getStudent().getId())); return courseStudent; }
Source:
public ComponentBuilder(ComponentBuilder original) { current = new TextComponent( original.getCurrent() ); for (BaseComponent baseComponent : original.getParts()) { parts.add( new TextComponent( (TextComponent) baseComponent ) ); } }

Target:
public ComponentBuilder(ComponentBuilder original) { current = new TextComponent( original.current ); for (BaseComponent baseComponent : original.parts) { parts.add( baseComponent.duplicate() ); } }
Source:
public int compareTo(Location other) { if (equals(other)) { return 0; } return Double.compare(toDouble(), other.toDouble()); }

Target:
public int compareTo(Location other) { return (other == INVALID) ? 0 : -1; }
Source:
public void basic() { Assert.assertTrue(getClassPath(true).contains("\t")); Assert.assertTrue(getClassPath(true).contains("Java System Classloader")); Assert.assertTrue(getClassPath(true).contains("Level")); Assert.assertTrue(getClassPath(true).length() > getClassPath(false).length()); Assert.assertFalse(getClassPath(false).contains("\t")); Assert.assertFalse(getClassPath(false).contains("Java System Classloader")); Assert.assertFalse(getClassPath(false).contains("Level")); }

Target:
public void basic() { assertPattern(getClassPath(true), "(?s).*\\s+.*\\n$", true); Assert.assertTrue(getClassPath(true).contains("Java System Classloader")); Assert.assertTrue(getClassPath(true).contains("Level")); Assert.assertTrue(getClassPath(true).length() > getClassPath(false).length()); assertPattern(getClassPath(false), "(?s).*\\s+.*\\n$", false); Assert.assertFalse(getClassPath(false).contains("Java System Classloader")); Assert.assertFalse(getClassPath(false).contains("Level")); }
Source:
public SerializedString toBytes(Codec<PlanFragment> codec) { requireNonNull(codec, "codec is null"); if (cachedSerialization == null) { cachedSerialization = new SerializedString(new String(codec.toBytes(this))); } return cachedSerialization; }

Target:
public synchronized byte[] toBytes(Codec<PlanFragment> codec) { requireNonNull(codec, "codec is null"); if (cachedSerialization != null) { verify(codec == lastUsedCodec, "Only one Codec may be used to serialize PlanFragments"); } else { cachedSerialization = codec.toBytes(this); lastUsedCodec = codec; } return cachedSerialization; }
Source:
public List<Long> getAgentProvider(String providedServiceLabel, long accountId) { return Arrays.asList(create().select(INSTANCE.AGENT_ID) .from(INSTANCE) .join(INSTANCE_LABEL_MAP) .on(INSTANCE_LABEL_MAP.INSTANCE_ID.eq(INSTANCE.ID)) .join(LABEL) .on(LABEL.ID.eq(INSTANCE_LABEL_MAP.LABEL_ID).and(LABEL.KEY.eq(providedServiceLabel))) .join(INSTANCE_HOST_MAP) .on(INSTANCE.ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID)) .join(HOST) .on(INSTANCE_HOST_MAP.HOST_ID.eq(HOST.ID)) .join(AGENT) .on(AGENT.ID.eq(HOST.AGENT_ID)) .where(INSTANCE.ACCOUNT_ID.eq(accountId) .and(INSTANCE.AGENT_ID.isNotNull()) .and(INSTANCE.STATE.eq(InstanceConstants.STATE_RUNNING)) .and(INSTANCE.HEALTH_STATE.in(HealthcheckConstants.HEALTH_STATE_HEALTHY, HealthcheckConstants.HEALTH_STATE_UPDATING_HEALTHY))) .and(AGENT.STATE.eq(AgentConstants.STATE_ACTIVE)) .orderBy(INSTANCE.AGENT_ID.asc()) .fetch().intoArray(INSTANCE.AGENT_ID)); }

Target:
public List<Long> getAgentProvider(String providedServiceLabel, long accountId) { return Arrays.asList(create().select(INSTANCE.AGENT_ID) .from(INSTANCE) .join(INSTANCE_LABEL_MAP) .on(INSTANCE_LABEL_MAP.INSTANCE_ID.eq(INSTANCE.ID)) .join(LABEL) .on(LABEL.ID.eq(INSTANCE_LABEL_MAP.LABEL_ID).and(LABEL.KEY.eq(providedServiceLabel))) .join(INSTANCE_HOST_MAP) .on(INSTANCE.ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID)) .join(HOST) .on(INSTANCE_HOST_MAP.HOST_ID.eq(HOST.ID)) .join(AGENT) .on(AGENT.ID.eq(HOST.AGENT_ID)) .where(INSTANCE.ACCOUNT_ID.eq(accountId) .and(INSTANCE.AGENT_ID.isNotNull()) .and(INSTANCE.STATE.eq(InstanceConstants.STATE_RUNNING)) .and(INSTANCE.HEALTH_STATE.in(HealthcheckConstants.HEALTH_STATE_HEALTHY, HealthcheckConstants.HEALTH_STATE_UPDATING_HEALTHY))) .and(AGENT.STATE.eq(CommonStatesConstants.ACTIVE)) .orderBy(INSTANCE.AGENT_ID.asc()) .fetch().intoArray(INSTANCE.AGENT_ID)); }
Source:
public C4Error getError() { return error; }

Target:
public CouchbaseLiteException getError() { return error.getCode() != 0 ? CBLStatus.convertError(error) : null; }
Source:
public String toString() { StringBuilder url = new StringBuilder(); url.append("http"); if (secure) { url.append("s"); } url.append("://"); url.append(host); if (port != 80 && port != 443) { url.append(":"); url.append(port); } url.append(path); return url.toString(); }

Target:
public String toString() { StringBuilder url = new StringBuilder(); url.append("http"); if (secure) { url.append("s"); } url.append("://"); url.append(host); if (!(port == 80 && !secure) && !(port == 443 && secure)) { url.append(":"); url.append(port); } url.append(path); return url.toString(); }
Source:
private String parseForNext(JSONObject resp, List<SyncActivityItem> items) throws JSONException { if (resp.has("items")) { JSONArray activities = resp.getJSONArray("items"); for (int i = 0; i < activities.length(); i++) { JSONObject item = activities.getJSONObject(i); SyncActivityItem ai = new SyncActivityItem(); String startTime = item.getString("start_time"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); try { ai.setStartTime(format.parse(startTime).getTime()/ONE_THOUSEND); } catch (ParseException e) { Log.e(Constants.LOG, e.getMessage()); return null; } Float time = Float.parseFloat(item.getString("duration")); ai.setDuration(time.longValue()); BigDecimal dist = new BigDecimal(Float.parseFloat(item.getString("total_distance"))); dist = dist.setScale(2, BigDecimal.ROUND_UP); ai.setDistance(dist.floatValue()); ai.setURI(REST_URL + item.getString("uri")); ai.setId((long) items.size()); String sport = item.getString("type"); if (SPORT_MAP.containsKey(sport)) { ai.setSport(SPORT_MAP.get(sport)); } else { ai.setSport(Sport.OTHER.getDbValue()); } items.add(ai); } } if (resp.has("next")) { return REST_URL + resp.getString("next"); } return null; }

Target:
private String parseForNext(JSONObject resp, List<SyncActivityItem> items) throws JSONException { if (resp.has("items")) { JSONArray activities = resp.getJSONArray("items"); for (int i = 0; i < activities.length(); i++) { JSONObject item = activities.getJSONObject(i); SyncActivityItem ai = new SyncActivityItem(); String startTime = item.getString("start_time"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); try { ai.setStartTime(TimeUnit.MILLISECONDS.toSeconds(format.parse(startTime).getTime())); } catch (ParseException e) { Log.e(Constants.LOG, e.getMessage()); return null; } Float time = Float.parseFloat(item.getString("duration")); ai.setDuration(time.longValue()); BigDecimal dist = new BigDecimal(Float.parseFloat(item.getString("total_distance"))); dist = dist.setScale(2, BigDecimal.ROUND_UP); ai.setDistance(dist.floatValue()); ai.setURI(REST_URL + item.getString("uri")); ai.setId((long) items.size()); String sport = item.getString("type"); if (SPORT_MAP.containsKey(sport)) { ai.setSport(SPORT_MAP.get(sport)); } else { ai.setSport(Sport.OTHER.getDbValue()); } items.add(ai); } } if (resp.has("next")) { return REST_URL + resp.getString("next"); } return null; }