auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Collection<IResource> getItems(){ if(items == null) { ModelNode listNode = get(ITEMS); if (listNode.isDefined()) { Collection<ModelNode> nodes = get(ITEMS).asList(); items = new ArrayList<>(nodes.size()); IResourceFactory factory = getClient().getResourceFactory(); if (factory != null) { for (ModelNode node : nodes) { if (kind != null && !node.get(KIND).isDefined()) { set(node, KIND, kind); } if(!node.get(APIVERSION).isDefined()) { set(node, APIVERSION, getApiVersion()); } IResource resource = factory.create(node.toJSONString(true)); items.add(resource); } } } else { items = Collections.emptyList(); } } return Collections.unmodifiableCollection(items); }

Target:
public Collection<IResource> getItems(){ if(items == null) { String key = getNode().has(OBJECTS) ? OBJECTS : ITEMS; ModelNode listNode = get(key); if (listNode.isDefined()) { Collection<ModelNode> nodes = get(key).asList(); items = new ArrayList<>(nodes.size()); IResourceFactory factory = getClient().getResourceFactory(); if (factory != null) { for (ModelNode node : nodes) { if (kind != null && !node.get(KIND).isDefined()) { set(node, KIND, kind); } if(!node.get(APIVERSION).isDefined()) { set(node, APIVERSION, getApiVersion()); } IResource resource = factory.create(node.toJSONString(true)); items.add(resource); } } } else { items = Collections.emptyList(); } } return Collections.unmodifiableCollection(items); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fui_auth_method_picker_layout); FlowParameters params = getFlowParams(); mHandler = ViewModelProviders.of(this).get(SimpleProvidersHandler.class); mHandler.init(params); populateIdpList(params.providerInfo, mHandler); int logoId = params.logoId; if (logoId == AuthUI.NO_LOGO) { findViewById(R.id.logo).setVisibility(View.GONE); ConstraintLayout layout = findViewById(R.id.root); ConstraintSet constraints = new ConstraintSet(); constraints.clone(layout); constraints.setHorizontalBias(R.id.container, 0.5f); constraints.setVerticalBias(R.id.container, 0.5f); constraints.applyTo(layout); } else { ImageView logo = findViewById(R.id.logo); logo.setImageResource(logoId); } mHandler.getOperation().observe(this, new Observer<Resource<IdpResponse>>() { @Override public void onChanged(Resource<IdpResponse> resource) { if (resource.getState() == State.LOADING) { getDialogHolder().showLoadingDialog(R.string.fui_progress_dialog_signing_in); return; } getDialogHolder().dismissDialog(); if (resource.isUsed()) { return; } if (resource.getState() == State.SUCCESS) { startSaveCredentials(mHandler.getCurrentUser(), null, resource.getValue()); } else { Exception e = resource.getException(); if (!FlowUtils.handleError(AuthMethodPickerActivity.this, e) && e.getLocalizedMessage() != null) { Toast.makeText(AuthMethodPickerActivity.this, R.string.fui_error_unknown, Toast.LENGTH_SHORT).show(); } } } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fui_auth_method_picker_layout); FlowParameters params = getFlowParams(); mHandler = ViewModelProviders.of(this).get(SocialProviderResponseHandler.class); mHandler.init(params); populateIdpList(params.providerInfo, mHandler); int logoId = params.logoId; if (logoId == AuthUI.NO_LOGO) { findViewById(R.id.logo).setVisibility(View.GONE); ConstraintLayout layout = findViewById(R.id.root); ConstraintSet constraints = new ConstraintSet(); constraints.clone(layout); constraints.setHorizontalBias(R.id.container, 0.5f); constraints.setVerticalBias(R.id.container, 0.5f); constraints.applyTo(layout); } else { ImageView logo = findViewById(R.id.logo); logo.setImageResource(logoId); } mHandler.getOperation().observe(this, new Observer<Resource<IdpResponse>>() { @Override public void onChanged(Resource<IdpResponse> resource) { if (resource.getState() == State.LOADING) { getDialogHolder().showLoadingDialog(R.string.fui_progress_dialog_signing_in); return; } getDialogHolder().dismissDialog(); if (resource.getState() == State.SUCCESS) { startSaveCredentials(mHandler.getCurrentUser(), null, resource.getValue()); } else if (resource.getState() == State.FAILURE) { Exception e = resource.getException(); if (!FlowUtils.handleError(AuthMethodPickerActivity.this, e) && !(e instanceof UserCancellationException)) { Toast.makeText(AuthMethodPickerActivity.this, R.string.fui_error_unknown, Toast.LENGTH_SHORT).show(); } } } }); }
Source:
public Term substituteAndEvaluate(Map<Variable, ? extends Term> substitution, TermContext context) { if ((!substitution.isEmpty() && !isGround()) || !isNormal()) { return (Term) this.accept(new SubstituteAndEvaluateTransformer(substitution, context)); } else { return this; } }

Target:
public Term substituteAndEvaluate(Map<Variable, ? extends Term> substitution, TermContext context) { return canSubstituteAndEvaluate(substitution) ? (Term) this.accept(new SubstituteAndEvaluateTransformer(substitution, context)) : this; }
Source:
public boolean equals(Object obj) { if (!(obj instanceof AccessToken)) { return false; } IdToken other = (IdToken) obj; return Objects.equals(super.getTokenValue(), other.getTokenValue()) && Objects.equals(this.jws, other.jws); }

Target:
public boolean equals(Object obj) { if (!(obj instanceof IdToken)) { return false; } IdToken other = (IdToken) obj; return Objects.equals(super.getTokenValue(), other.getTokenValue()) && Objects.equals(this.jsonWebSignature.getHeader(), other.jsonWebSignature.getHeader()) && Objects.equals(this.jsonWebSignature.getPayload(), other.jsonWebSignature.getPayload()); }
Source:
public void onApplicationEvent(ApplicationEvent event) { LOG.debug("onApplicationEvent: {}", event); if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext().getId().equals(this.applicationContext.getId())) { start(); } if (eventComponent != null) { eventComponent.onApplicationEvent(event); } }

Target:
public void onApplicationEvent(ApplicationEvent event) { LOG.debug("onApplicationEvent: {}", event); if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext() == this.applicationContext) { start(); } if (eventComponent != null) { eventComponent.onApplicationEvent(event); } }
Source:
public ActivationKeyDTO setPools(Set<ActivationKeyPoolDTO> pools) { if (pools != null) { if (this.pools == null) { this.pools = new HashSet<ActivationKeyPoolDTO>(); } else { this.pools.clear(); } for (ActivationKeyPoolDTO dto : pools) { if (dto == null || dto.getPoolId() == null || "".equals(dto.getPoolId())) { throw new IllegalArgumentException("collection contains null or incomplete dtos"); } this.pools.add(new ActivationKeyPoolDTO(dto.getPoolId(), dto.getQuantity())); } } else { this.pools = null; } return this; }

Target:
public ActivationKeyDTO setPools(Set<ActivationKeyPoolDTO> pools) { if (pools != null) { if (this.pools == null) { this.pools = new HashSet<ActivationKeyPoolDTO>(); } else { this.pools.clear(); } for (ActivationKeyPoolDTO dto : pools) { if (dto == null || dto.getPoolId() == null || dto.getPoolId().isEmpty()) { throw new IllegalArgumentException("collection contains null or incomplete pools"); } this.pools.add(new ActivationKeyPoolDTO(dto.getPoolId(), dto.getQuantity())); } } else { this.pools = null; } return this; }
Source:
static List<Arguments> testWhatIsValid() { return List.of( Arguments.of( "Attacker has air units and no destroyers vs Defender subs", givenBattleState() .attackingUnits(List.of(givenUnit(), givenUnitIsAir())) .defendingUnits(List.of(givenUnitCanNotBeTargetedBy(mock(UnitType.class)))) .build(), true), Arguments.of( "Attacker has air units and destroyers", givenBattleState() .attackingUnits(List.of(givenUnitDestroyer(), givenUnitIsAir())) .defendingUnits(List.of(mock(Unit.class))) .build(), false), Arguments.of( "Attacker has air units but no destroyers vs Defender with no subs", givenBattleState() .attackingUnits(List.of(givenUnit(), givenUnitIsAir())) .defendingUnits(List.of(givenUnit())) .build(), false)); }

Target:
static List<Arguments> testWhatIsValid() { return List.of( Arguments.of( "Attacker has air units and no destroyers vs Defender subs", givenBattleStateBuilder() .attackingUnits(List.of(givenAnyUnit(), givenUnitIsAir())) .defendingUnits(List.of(givenUnitCanNotBeTargetedBy(mock(UnitType.class)))) .build(), true), Arguments.of( "Attacker has air units and destroyers", givenBattleStateBuilder() .attackingUnits(List.of(givenUnitDestroyer(), givenUnitIsAir())) .defendingUnits(List.of(mock(Unit.class))) .build(), false), Arguments.of( "Attacker has air units but no destroyers vs Defender with no subs", givenBattleStateBuilder() .attackingUnits(List.of(givenAnyUnit(), givenUnitIsAir())) .defendingUnits(List.of(givenAnyUnit())) .build(), false)); }
Source:
public void onToggleItemOffline(int pageIndex) { ReadingListPage page = readingList == null ? null : readingList.pages().get(pageIndex); if (page == null) { return; } if (page.offline()) { toggleOffline(page); } else { toggleOffline(page); } }

Target:
public void onToggleItemOffline(int pageIndex) { ReadingListPage page = readingList == null ? null : readingList.pages().get(pageIndex); if (page == null) { return; } if (page.offline()) { CallbackTask.execute(() -> { List<ReadingListPage> occurrences = ReadingListDbHelper.instance().getAllPageOccurrences(ReadingListPage.toPageTitle(page)); return ReadingListDbHelper.instance().getListsFromPageOccurrences(occurrences); }, new CallbackTask.DefaultCallback<List<ReadingList>>() { @SuppressWarnings("checkstyle:magicnumber") @Override public void success(List<ReadingList> lists) { if (!isAdded()) { return; } if (lists.size() > 1) { AlertDialog dialog = new AlertDialog.Builder(getContext()) .setTitle(R.string.reading_list_confirm_remove_article_from_offline_title) .setMessage(getConfirmToggleOfflineMessage(page, lists)) .setPositiveButton(R.string.reading_list_confirm_remove_article_from_offline, (dialog1, which) -> toggleOffline(page)) .setNegativeButton(android.R.string.cancel, null) .create(); dialog.show(); TextView text = dialog.findViewById(android.R.id.message); text.setLineSpacing(0, 1.3f); } else { toggleOffline(page); } } }); } else { toggleOffline(page); } }
Source:
void printUsage() { final String usage = "java -jar VarSim.jar <tool> <tool_args>... \n" + " --= Simulation =-- \n" + " randvcf2vcf -- Randomly samples variants from a VCF file\n" + " randdgv2vcf -- Randomly samples variants from a DGV database file\n" + " --= Validation =-- \n" + " vcfcompare -- Generate JSON describing vcf accuracy relative to truth \n" + " samcompare -- Generate JSON describing alignment accuracy relative to truth \n" + " vcfstats -- Generate stats on size range and variant types in a VCF\n" + " --= Internal =-- \n" + " vcf2diploid -- Enhanced version of vcf2diploid from alleleseq \n" + " fastq_liftover -- Lifts over simulated FASTQ files to reference coordinates \n" + "\n"; System.err.println(VarSim.class.getSimpleName() + " " + VERSION); System.err.println(usage); }

Target:
private void printUsage() { final String usage = "java -jar VarSim.jar <tool> <tool_args>... \n" + " --= Simulation =-- \n" + " randvcf2vcf -- Randomly samples variants from a VCF file\n" + " randdgv2vcf -- Randomly samples variants from a DGV database file\n" + " --= Validation =-- \n" + " vcfcompare -- Generate JSON describing vcf accuracy relative to truth \n" + " samcompare -- Generate JSON describing alignment accuracy relative to truth \n" + " vcfstats -- Generate stats on size range and variant types in a VCF\n" + " --= Internal =-- \n" + " vcf2diploid -- Enhanced version of vcf2diploid from alleleseq \n" + " fastq_liftover -- Lifts over simulated FASTQ files to reference coordinates \n" + "\n"; System.err.println(VarSim.class.getSimpleName() + " " + VERSION); System.err.println(usage); }
Source:
public boolean equals(Object o) { return false; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserResourceProfilePK that = (UserResourceProfilePK) o; if (!getUserId().equals(that.getUserId())) return false; return getGatewayID().equals(that.getGatewayID()); }
Source:
public void auditLoggingOffForInboundRealTime() { AdapterCORE_X12DSRealTimeProxyObjectFactory mockFactory = mock(AdapterCORE_X12DSRealTimeProxyObjectFactory.class); PassthroughInboundCORE_X12DSRealTime realTimeX12 = new PassthroughInboundCORE_X12DSRealTime(mockFactory, getAuditLogger(false)); COREEnvelopeRealTimeRequest request = new COREEnvelopeRealTimeRequest(); AssertionType assertion = new AssertionType(); Properties webContextProperties = new Properties(); AdapterCORE_X12DSRealTimeProxy mockAdapterProxy = mock(AdapterCORE_X12DSRealTimeProxy.class); when(mockFactory.getAdapterCORE_X12DocSubmissionProxy()).thenReturn(mockAdapterProxy); COREEnvelopeRealTimeResponse expectedResponse = new COREEnvelopeRealTimeResponse(); when(mockAdapterProxy.realTimeTransaction(request, assertion)).thenReturn(expectedResponse); COREEnvelopeRealTimeResponse actualResponse = realTimeX12.realTimeTransaction(request, assertion, webContextProperties); verify(mockEJBLogger, never()).auditResponseMessage(eq(request), eq(actualResponse), eq(assertion), isNull(NhinTargetSystemType.class), eq(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_NHIN_INTERFACE), eq(Boolean.FALSE), eq(webContextProperties), eq(NhincConstants.CORE_X12DS_REALTIME_SERVICE_NAME), any(COREX12RealTimeAuditTransforms.class)); }

Target:
public void auditLoggingOffForInboundRealTime() { PassthroughInboundCORE_X12DSRealTime realTimeX12 = new PassthroughInboundCORE_X12DSRealTime(mockFactory, getAuditLogger(false)); when(mockFactory.getAdapterCORE_X12DocSubmissionProxy()).thenReturn(mockAdapterProxy); COREEnvelopeRealTimeResponse expectedResponse = new COREEnvelopeRealTimeResponse(); when(mockAdapterProxy.realTimeTransaction(request, assertion)).thenReturn(expectedResponse); COREEnvelopeRealTimeResponse actualResponse = realTimeX12.realTimeTransaction(request, assertion, webContextProperties); verify(mockEJBLogger, never()).auditResponseMessage(eq(request), eq(actualResponse), eq(assertion), isNull(NhinTargetSystemType.class), eq(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_NHIN_INTERFACE), eq(Boolean.FALSE), eq(webContextProperties), eq(NhincConstants.CORE_X12DS_REALTIME_SERVICE_NAME), any(COREX12RealTimeAuditTransforms.class)); }
Source:
public CacheQuery<T> limit(int limit) { this.limit = limit; return this; }

Target:
@Override public CacheQuery<T> limit(int limit) { this.limit = limit; return this; }
Source:
public Resource createNew(String newName, InputStream in, Long length, String contentType) throws IOException, DotRuntimeException { if(newName.matches("^\\.(.*)-Spotlight$")){ newName = newName + ".spotlight"; } User user=(User)HttpManager.request().getAuthorization().getTag(); if(!path.endsWith("/")){ path = path + "/"; } if(!dotDavHelper.isTempResource(newName)){ try { dotDavHelper.setResourceContent(path + newName, in, contentType, null, java.util.Calendar.getInstance().getTime(), user, isAutoPub); IFileAsset f = dotDavHelper.loadFile(path + newName,user); Resource fr = new FileResourceImpl(f, f.getFileName()); return fr; }catch (Exception e){ Logger.error(this, "An error occurred while creating new file: " + (newName != null ? newName : "Unknown") + " in this path: " + (path != null ? path : "Unknown") + " " + e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } } else { try { if(!originalPath.endsWith("/")){ originalPath = originalPath + "/"; } File f = dotDavHelper.createTempFile("/" + host.getHostname() + originalPath + newName); FileUtils.copyStreamToFile(f, in, null); Resource tr = new TempFileResourceImpl(f, originalPath + newName, isAutoPub); return tr; } catch (Exception e){ Logger.error(this, "Error creating temp file", e); throw new DotRuntimeException(e.getMessage(), e); } } }

Target:
public Resource createNew(String newName, InputStream in, Long length, String contentType) throws IOException, DotRuntimeException { if(newName.matches("^\\.(.*)-Spotlight$")){ newName = newName + ".spotlight"; } User user=(User)HttpManager.request().getAuthorization().getTag(); if(!path.endsWith("/")){ path = path + "/"; } if(!dotDavHelper.isTempResource(newName)){ try { dotDavHelper.setResourceContent(path + newName, in, contentType, null, java.util.Calendar.getInstance().getTime(), user, isAutoPub); final IFileAsset iFileAsset = dotDavHelper.loadFile(path + newName,user); final Resource fileResource = new FileResourceImpl(iFileAsset, iFileAsset.getFileName()); return fileResource; }catch (Exception e){ Logger.error(this, "An error occurred while creating new file: " + (newName != null ? newName : "Unknown") + " in this path: " + (path != null ? path : "Unknown") + " " + e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } } else { try { originalPath = (!originalPath.endsWith("/"))?originalPath + "/":originalPath; final File tempFile = dotDavHelper.createTempFile("/" + host.getHostname() + originalPath + newName); FileUtils.copyStreamToFile(tempFile, in, null); final Resource tempFileResource = new TempFileResourceImpl(tempFile, originalPath + newName, isAutoPub); return tempFileResource; } catch (Exception e){ Logger.error(this, "Error creating temp file", e); throw new DotRuntimeException(e.getMessage(), e); } } }
Source:
public String buildMessage(String userInput){ SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); String username = CommCareApplication._().getSession().getLoggedInUser().getUsername(); String version = CommCareApplication._().getCurrentVersionString(); String domain = prefs.getString(HttpRequestGenerator.USER_DOMAIN_SUFFIX,"not found"); String message = "Problem reported via CommCareODK. " + "\n User: " + username + "\n Domain: " + domain + "\n CCODK version: " + version + "\n Device Model: " + Build.MODEL + "\n Manufacturer: " + Build.MANUFACTURER + "\n Android Version: " + Build.VERSION.RELEASE + "\n Message: " + userInput; return message; }

Target:
public String buildMessage(String userInput){ SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); String username = CommCareApplication._().getSession().getLoggedInUser().getUsername(); String version = CommCareApplication._().getCurrentVersionString(); String domain = prefs.getString(HttpRequestGenerator.USER_DOMAIN_SUFFIX,"not found"); String postURL = prefs.getString("PostURL", null);; String message = "Problem reported via CommCareODK. " + "\n User: " + username + "\n Domain: " + domain + "\n PostURL: " + postURL + "\n CCODK version: " + version + "\n Device Model: " + Build.MODEL + "\n Manufacturer: " + Build.MANUFACTURER + "\n Android Version: " + Build.VERSION.RELEASE + "\n Message: " + userInput; return message; }
Source:
public Response createConnection(String resource) { if (urlValidator.isValid(resource)) { webClient = WebClient.create(resource); webClient.path(resource); } else { webClient = WebClient.create(url + resource + ".zip"); webClient.path(url + resource + ".zip"); } return webClient.get(); }

Target:
public Response createConnection(String resource) { if (URL_VALIDATOR.isValid(resource)) { webClient = WebClient.create(resource); webClient.path(resource); } else { webClient = WebClient.create(url + resource + ".zip"); webClient.path(url + resource + ".zip"); } return webClient.get(); }
Source:
public void shouldIdentifyMultipleTimeouts() { assertEquals(6000, GremlinScriptChecker.parse("g.with('evaluationTimeout', 1000L).with(true).V().out('knows');" + "g.with('evaluationTimeout', 1000L).with(true).V().out('knows')\n" + " " \n" + " \n" + " g.with('evaluationTimeout', 1000L).with(true).V().out('knows')\n" + " g.with(Tokens.ARGS_SCRIPT_EVAL_TIMEOUT, 1000L).with(true).V().out('knows')\n" + " g.with(ARGS_EVAL_TIMEOUT, 1000L).with(true).V().out('knows')\n" + " g.with('scriptEvaluationTimeout', 1000L).with(true).V().out('knows')"). getTimeout().get().longValue()); }

Target:
public void shouldIdentifyMultipleTimeouts() { assertEquals(6000, GremlinScriptChecker.parse("g.with('evaluationTimeout', 1000L).with(true).V().out('knows');" + "g.with('evaluationTimeout', 1000L).with(true).V().out('knows');\n" + " " \n" + " \n" + " g.with('evaluationTimeout', 1000L).with(true).V().out('knows');\n" + " g.with(Tokens.ARGS_SCRIPT_EVAL_TIMEOUT, 1000L).with(true).V().out('knows');\n" + " g.with(ARGS_EVAL_TIMEOUT, 1000L).with(true).V().out('knows');\n" + " g.with('scriptEvaluationTimeout', 1000L).with(true).V().out('knows');"). getTimeout().get().longValue()); }
Source:
private void publishAlertEvent(Alert alert, String event) { HistoryReference historyReference = hrefs.get(alert.getSourceHistoryId()); if (historyReference == null) { historyReference = Control.getSingleton() .getExtensionLoader() .getExtension(ExtensionHistory.class) .getHistoryReference(alert.getSourceHistoryId()); } Map<String, String> map = new HashMap<>(); map.put(AlertEventPublisher.ALERT_ID, Integer.toString(alert.getAlertId())); map.put(AlertEventPublisher.HISTORY_REFERENCE_ID, Integer.toString(alert.getSourceHistoryId())); map.put(AlertEventPublisher.NAME, alert.getName()); map.put(AlertEventPublisher.URI, alert.getUri().toString()); map.put(AlertEventPublisher.PARAM, alert.getParam()); map.put(AlertEventPublisher.RISK, Integer.toString(alert.getRisk())); map.put(AlertEventPublisher.RISK_STRING, Alert.MSG_RISK[alert.getRisk()]); map.put(AlertEventPublisher.CONFIDENCE, Integer.toString(alert.getConfidence())); map.put(AlertEventPublisher.CONFIDENCE_STRING, Alert.MSG_CONFIDENCE[alert.getConfidence()]); map.put(AlertEventPublisher.SOURCE, alert.getSource().getI18nKey()); ZAP.getEventBus().publishSyncEvent( AlertEventPublisher.getPublisher(), new Event(AlertEventPublisher.getPublisher(), event, new Target(historyReference.getSiteNode()), map)); }

Target:
private void publishAlertEvent(Alert alert, String event) { HistoryReference historyReference = hrefs.get(alert.getSourceHistoryId()); if (historyReference == null) { historyReference = Control.getSingleton() .getExtensionLoader() .getExtension(ExtensionHistory.class) .getHistoryReference(alert.getSourceHistoryId()); } Map<String, String> map = new HashMap<>(); map.put(AlertEventPublisher.ALERT_ID, Integer.toString(alert.getAlertId())); map.put(AlertEventPublisher.HISTORY_REFERENCE_ID, Integer.toString(alert.getSourceHistoryId())); map.put(AlertEventPublisher.NAME, alert.getName()); map.put(AlertEventPublisher.URI, alert.getUri().toString()); map.put(AlertEventPublisher.PARAM, alert.getParam()); map.put(AlertEventPublisher.RISK, Integer.toString(alert.getRisk())); map.put(AlertEventPublisher.RISK_STRING, Alert.MSG_RISK[alert.getRisk()]); map.put(AlertEventPublisher.CONFIDENCE, Integer.toString(alert.getConfidence())); map.put(AlertEventPublisher.CONFIDENCE_STRING, Alert.MSG_CONFIDENCE[alert.getConfidence()]); map.put(AlertEventPublisher.SOURCE, Integer.toString(alert.getSource().getId())); ZAP.getEventBus().publishSyncEvent( AlertEventPublisher.getPublisher(), new Event(AlertEventPublisher.getPublisher(), event, new Target(historyReference.getSiteNode()), map)); }
Source:
private static String translateRef(String oldPrefix, String newPrefix, String ref) { if (!ref.startsWith(oldPrefix)) throw new IllegalArgumentException(ref + " does not start with " + oldPrefix); return newPrefix + ref.substring(oldPrefix.length()); }

Target:
private static String translateRef(String oldPrefix, String newPrefix, String ref) { if (!ref.startsWith(oldPrefix)) throw new IllegalArgumentException(MessageFormat.format( JGitText.get().invalidRefName, ref)); return newPrefix + ref.substring(oldPrefix.length()); }
Source:
public long getUsedMemoryOnHost(final String hostname) { return this.jobRepository.getTotalMemoryUsedOnHost(hostname, RUNNING_JOB_SET); }

Target:
public long getUsedMemoryOnHost(final String hostname) { return this.jobRepository.getTotalMemoryUsedOnHost(hostname, USING_MEMORY_JOB_SET); }
Source:
public void addPartitions(String databaseName, String tableName, List<CatalogProtos.PartitionDescProto> partitions , boolean ifNotExists) { HiveCatalogStoreClientPool.HiveCatalogStoreClient client = null; List<Partition> addPartitions = TUtil.newList(); CatalogProtos.PartitionDescProto existingPartition = null; try { client = clientPool.getClient(); for (CatalogProtos.PartitionDescProto partitionDescProto : partitions) { existingPartition = getPartition(databaseName, tableName, partitionDescProto.getPartitionName()); if (existingPartition == null) { Partition partition = new Partition(); partition.setDbName(databaseName); partition.setTableName(tableName); List<String> values = Lists.newArrayList(); for(CatalogProtos.PartitionKeyProto keyProto : partitionDescProto.getPartitionKeysList()) { values.add(keyProto.getPartitionValue()); } partition.setValues(values); Table table = client.getHiveClient().getTable(databaseName, tableName); StorageDescriptor sd = table.getSd(); sd.setLocation(partitionDescProto.getPath()); partition.setSd(sd); addPartitions.add(partition); } } if (addPartitions.size() > 0) { List<Partition> results = client.getHiveClient().add_partitions(addPartitions, true, true); } } catch (Exception e) { throw new TajoInternalError(e); } finally { if (client != null) { client.release(); } } }

Target:
public void addPartitions(String databaseName, String tableName, List<CatalogProtos.PartitionDescProto> partitions , boolean ifNotExists) { HiveCatalogStoreClientPool.HiveCatalogStoreClient client = null; List<Partition> addPartitions = TUtil.newList(); CatalogProtos.PartitionDescProto existingPartition = null; try { client = clientPool.getClient(); for (CatalogProtos.PartitionDescProto partitionDescProto : partitions) { existingPartition = getPartition(databaseName, tableName, partitionDescProto.getPartitionName()); if (existingPartition == null) { Partition partition = new Partition(); partition.setDbName(databaseName); partition.setTableName(tableName); List<String> values = Lists.newArrayList(); for(CatalogProtos.PartitionKeyProto keyProto : partitionDescProto.getPartitionKeysList()) { values.add(keyProto.getPartitionValue()); } partition.setValues(values); Table table = client.getHiveClient().getTable(databaseName, tableName); StorageDescriptor sd = table.getSd(); sd.setLocation(partitionDescProto.getPath()); partition.setSd(sd); addPartitions.add(partition); } } if (addPartitions.size() > 0) { client.getHiveClient().add_partitions(addPartitions, true, true); } } catch (Exception e) { throw new TajoInternalError(e); } finally { if (client != null) { client.release(); } } }
Source:
@Override public Collection<Object> statusSnapshot() { return mgr.statusSnapshot().get().stream() .filter(Objects::nonNull) .collect(Collectors.toSet()); }

Target:
@Override public Map<Object, Boolean> statusSnapshot() { return mgr.statusSnapshot().get(); }
Source:
private String loadFile(String version) throws IOException { return readAndCloseQuietly(getResource(SCHEMAS_LOCATION + version + "/" + SCHEMA_FILENAME)); }

Target:
private String loadFile(String version) throws IOException { try { return readAndCloseQuietly(getResource(SCHEMAS_LOCATION + version + "/" + SCHEMA_FILENAME)); } catch (IOException ioe) { throw new IOException( String.format( "Unable to load devfile schema with version '%s'. Supported versions are '%s'", version, SUPPORTED_VERSIONS), ioe); } }
Source:
private Credentials extractCredentials(int index) { Credentials result = new Credentials(); String uri = this.uri[index]; result.uri = uri; Credentials explicitCredentials = getUsernamePassword(); result.username = explicitCredentials.username; result.password = explicitCredentials.password; try { URL url = new URL(uri); String userInfo = url.getUserInfo(); if (StringUtils.isEmpty(userInfo) || ":".equals(userInfo)) { return result; } String bare = UriComponentsBuilder.fromHttpUrl(uri).userInfo(null).build() .toUriString(); result.uri = bare; if (!userInfo.contains(":")) { userInfo = userInfo + ":"; } int sepIndex=userInfo.indexOf(":"); result.username = userInfo.substring(0, sepIndex); result.password = userInfo.substring(sepIndex +1); if (explicitCredentials.password != null) { result.password = explicitCredentials.password; } if (!"user".equals(explicitCredentials.username)) { result.username = explicitCredentials.username; } return result; } catch (MalformedURLException e) { throw new IllegalStateException("Invalid URL: " + uri); } }

Target:
private Credentials extractCredentials(int index) { Credentials result = new Credentials(); int noOfUrl = this.uri.length; if (index < 0 || index >= noOfUrl) { throw new IllegalStateException("Trying to access an invalid array index"); } String uri = this.uri[index]; result.uri = uri; Credentials explicitCredentials = getUsernamePassword(); result.username = explicitCredentials.username; result.password = explicitCredentials.password; try { URL url = new URL(uri); String userInfo = url.getUserInfo(); if (StringUtils.isEmpty(userInfo) || ":".equals(userInfo)) { return result; } String bare = UriComponentsBuilder.fromHttpUrl(uri).userInfo(null).build() .toUriString(); result.uri = bare; if (!userInfo.contains(":")) { userInfo = userInfo + ":"; } int sepIndex = userInfo.indexOf(":"); result.username = userInfo.substring(0, sepIndex); result.password = userInfo.substring(sepIndex + 1); if (explicitCredentials.password != null) { result.password = explicitCredentials.password; } if (!"user".equals(explicitCredentials.username)) { result.username = explicitCredentials.username; } return result; } catch (MalformedURLException e) { throw new IllegalStateException("Invalid URL: " + uri); } }
Source:
public void testAcceleoMtlCollectionEvaluationOnArrayValues() { IInterpreter interpreter = new AcceleoMTLInterpreter(); EAttribute eAttribute = EcoreFactory.eINSTANCE.createEAttribute(); eAttribute.setName("a1"); String varExampleName = "varWithArray"; String[] arrayValue = new String[] { eAttribute.getName() }; interpreter.setVariable(varExampleName, arrayValue); String expression = "[" + varExampleName + "/]"; evaluateObject(interpreter, eAttribute, expression, arrayValue); evaluateCollection(interpreter, eAttribute, expression, Collections.<EObject> emptyList()); EObject[] eobjectArrayValue = new EObject[] { eAttribute }; interpreter.setVariable(varExampleName, eobjectArrayValue); evaluateObject(interpreter, eAttribute, expression, eobjectArrayValue); evaluateCollection(interpreter, eAttribute, expression, Arrays.asList(eobjectArrayValue)); interpreter.dispose(); }

Target:
public void testAcceleoMtlCollectionEvaluationOnArrayValues() { IInterpreter interpreter = new AcceleoMTLInterpreter(); EAttribute eAttribute = EcoreFactory.eINSTANCE.createEAttribute(); eAttribute.setName("a1"); String varExampleName = "varWithArray"; String[] arrayValue = new String[] { eAttribute.getName() }; interpreter.setVariable(varExampleName, arrayValue); String expression = "[" + varExampleName + "/]"; evaluateObject(interpreter, eAttribute, expression, arrayValue); evaluateCollection(interpreter, eAttribute, expression, Collections.<EObject> emptyList()); EObject[] eobjectArrayValue = new EObject[] { eAttribute }; interpreter.setVariable(varExampleName, eobjectArrayValue); evaluateObject(interpreter, eAttribute, expression, eobjectArrayValue); evaluateCollection(interpreter, eAttribute, expression, new ArrayList<EObject>(Arrays.asList(eobjectArrayValue))); interpreter.dispose(); }
Source:
public KubernetesPluginsToolingApplier( @Named("che.workspace.sidecar.image_pull_policy") String sidecarImagePullPolicy, @Named("che.workspace.sidecar.default_memory_limit_mb") long defaultSidecarMemoryLimitMB, @Named("che.workspace.sidecar.default_memory_request_mb") long defaultSidecarMemoryRequestMB, @Named("che.workspace.sidecar.default_cpu_limit_cores") String defaultSidecarCpuLimitCores, @Named("che.workspace.sidecar.default_cpu_request_cores") String defaultSidecarCpuRequestCores, @Named("che.agents.auth_enabled") boolean isAuthEnabled, ProjectsRootEnvVariableProvider projectsRootEnvVariableProvider, ChePluginsVolumeApplier chePluginsVolumeApplier, EnvVars envVars) { this.defaultSidecarMemoryLimitBytes = String.valueOf(defaultSidecarMemoryLimitMB * 1024 * 1024); this.defaultSidecarMemoryRequestBytes = String.valueOf(defaultSidecarMemoryRequestMB * 1024 * 1024); this.defaultSidecarCpuLimitCores = Float.toString(KubernetesSize.toCores(defaultSidecarCpuLimitCores)); this.defaultSidecarCpuRequestCores = Float.toString(KubernetesSize.toCores(defaultSidecarCpuRequestCores)); this.isAuthEnabled = isAuthEnabled; this.sidecarImagePullPolicy = validImagePullPolicies.contains(sidecarImagePullPolicy) ? sidecarImagePullPolicy : null; this.projectsRootEnvVariableProvider = projectsRootEnvVariableProvider; this.chePluginsVolumeApplier = chePluginsVolumeApplier; this.envVars = envVars; }

Target:
public KubernetesPluginsToolingApplier( @Named("che.workspace.sidecar.image_pull_policy") String sidecarImagePullPolicy, @Named("che.workspace.sidecar.default_memory_limit_mb") long defaultSidecarMemoryLimitMB, @Named("che.workspace.sidecar.default_memory_request_mb") long defaultSidecarMemoryRequestMB, @Named("che.workspace.sidecar.default_cpu_limit_cores") String defaultSidecarCpuLimitCores, @Named("che.workspace.sidecar.default_cpu_request_cores") String defaultSidecarCpuRequestCores, @Named("che.agents.auth_enabled") boolean isAuthEnabled, ProjectsRootEnvVariableProvider projectsRootEnvVariableProvider, ChePluginsVolumeApplier chePluginsVolumeApplier, EnvVars envVars) { this.defaultSidecarMemoryLimitBytes = toBytesString(defaultSidecarMemoryLimitMB); this.defaultSidecarMemoryRequestBytes = toBytesString(defaultSidecarMemoryRequestMB); this.defaultSidecarCpuLimitCores = Float.toString(KubernetesSize.toCores(defaultSidecarCpuLimitCores)); this.defaultSidecarCpuRequestCores = Float.toString(KubernetesSize.toCores(defaultSidecarCpuRequestCores)); this.isAuthEnabled = isAuthEnabled; this.sidecarImagePullPolicy = validImagePullPolicies.contains(sidecarImagePullPolicy) ? sidecarImagePullPolicy : null; this.projectsRootEnvVariableProvider = projectsRootEnvVariableProvider; this.chePluginsVolumeApplier = chePluginsVolumeApplier; this.envVars = envVars; }
Source:
CompletableFuture<RegistrationResponse> registerTaskExecutor(ResourceID resourceID) throws Exception { final TaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder() .createTestingTaskExecutorGateway(); ((TestingRpcService) resourceManager.getRpcService()).registerGateway(resourceID.toString(), taskExecutorGateway); final TaskExecutorRegistration taskExecutorRegistration = new TaskExecutorRegistration( resourceID.toString(), resourceID, 1234, new HardwareDescription(1, 2L, 3L, 4L), ResourceProfile.ZERO, ResourceProfile.ZERO); return runInMainThread(() -> resourceManager.registerTaskExecutor(taskExecutorRegistration, TIMEOUT_TIME)) .get(TIMEOUT_SEC, TimeUnit.SECONDS); }

Target:
CompletableFuture<RegistrationResponse> registerTaskExecutor(ResourceID resourceID) { final TaskExecutorGateway taskExecutorGateway = new TestingTaskExecutorGatewayBuilder() .createTestingTaskExecutorGateway(); RPC_SERVICE_RESOURCE.getTestingRpcService().registerGateway(resourceID.toString(), taskExecutorGateway); final TaskExecutorRegistration taskExecutorRegistration = new TaskExecutorRegistration( resourceID.toString(), resourceID, 1234, new HardwareDescription(1, 2L, 3L, 4L), ResourceProfile.ZERO, ResourceProfile.ZERO); return resourceManager.getSelfGateway(ResourceManagerGateway.class) .registerTaskExecutor(taskExecutorRegistration, TIMEOUT_TIME); }
Source:
public Long getUuid() { return new Long(999994); }

Target:
public Long getUuid() { return 999994L; }
Source:
public void testDurationWeighting() { final SleepScore.Weighting weighting = new SleepScore.DurationHeavyWeighting(); final MotionScore fakeMotion = new MotionScore(0, 0, 0.0f, 0, 90); final Integer fakeDuration = 80; final Integer fakeEnvironment = 100; final SleepScore.Builder builder = new SleepScore.Builder(); final SleepScore sleepScore = builder.withEnvironmentalScore(fakeEnvironment) .withSleepDurationScore(fakeDuration) .withMotionScore(fakeMotion) .withWeighting(weighting) .build(); Integer calculatedWeight = Math.round((weighting.motion * fakeMotion.score) + (weighting.duration * fakeDuration) + (weighting.environmental * fakeEnvironment)); assertThat(sleepScore, notNullValue()); assertThat(sleepScore.value, is(calculatedWeight)); assertThat(sleepScore.value, greaterThan(0)); assertThat(sleepScore.value, lessThan(100)); assertThat(sleepScore.motionScore, is(fakeMotion)); assertThat(sleepScore.sleepDurationScore, is(fakeDuration)); assertThat(sleepScore.environmentalScore, is(fakeEnvironment)); }

Target:
public void testDurationWeighting() { final SleepScore.Weighting weighting = new SleepScore.DurationHeavyWeighting(); final MotionScore fakeMotion = new MotionScore(0, 0, 0.0f, 0, 90); final Integer fakeDuration = 80; final Integer fakeEnvironment = 100; final SleepScore.Builder builder = new SleepScore.Builder(); final SleepScore sleepScore = builder.withEnvironmentalScore(fakeEnvironment) .withSleepDurationScore(fakeDuration) .withMotionScore(fakeMotion) .withWeighting(weighting) .build(); Integer calculatedWeight = Math.round((weighting.motion * fakeMotion.score) + (weighting.duration * fakeDuration) + (weighting.environmental * fakeEnvironment)); assertThat(sleepScore, notNullValue()); assertThat(sleepScore.value, is(calculatedWeight)); assertThat(sleepScore.value, greaterThanOrEqualTo(0)); assertThat(sleepScore.value, lessThanOrEqualTo(100)); assertThat(sleepScore.motionScore, is(fakeMotion)); assertThat(sleepScore.sleepDurationScore, is(fakeDuration)); assertThat(sleepScore.environmentalScore, is(fakeEnvironment)); }
Source:
public void prepareAnalyzer(Engine engine) throws InitializationException { super.prepareAnalyzer(engine); try { this.open(engine.getDatabase()); } catch (IOException ex) { LOGGER.debug("Exception initializing the Lucene Index", ex); throw new InitializationException("An exception occurred initializing the Lucene Index", ex); } catch (DatabaseException ex) { LOGGER.debug("Exception accessing the database", ex); throw new InitializationException("An exception occurred accessing the database", ex); } final String[] tmp = engine.getSettings().getArray(Settings.KEYS.ECOSYSTEM_SKIP_CPEANALYZER); if (tmp == null) { skipEcosystems = new ArrayList<>(); } else { LOGGER.info("Skipping CPE Analysis for {}", StringUtils.join(tmp, ",")); skipEcosystems = Arrays.asList(tmp); } minLuceneScore = engine.getSettings().getFloat(Settings.KEYS.ECOSYSTEM_SKIP_CPEANALYZER, 30); suppression = new CpeSuppressionAnalyzer(); suppression.initialize(engine.getSettings()); suppression.prepareAnalyzer(engine); }

Target:
public void prepareAnalyzer(Engine engine) throws InitializationException { super.prepareAnalyzer(engine); try { this.open(engine.getDatabase()); } catch (IOException ex) { LOGGER.debug("Exception initializing the Lucene Index", ex); throw new InitializationException("An exception occurred initializing the Lucene Index", ex); } catch (DatabaseException ex) { LOGGER.debug("Exception accessing the database", ex); throw new InitializationException("An exception occurred accessing the database", ex); } final String[] tmp = engine.getSettings().getArray(Settings.KEYS.ECOSYSTEM_SKIP_CPEANALYZER); if (tmp == null) { skipEcosystems = new ArrayList<>(); } else { LOGGER.info("Skipping CPE Analysis for {}", StringUtils.join(tmp, ",")); skipEcosystems = Arrays.asList(tmp); } minLuceneScore = engine.getSettings().getFloat(Settings.KEYS.LUCENE_MIN_SCORE_FILTER, 30); suppression = new CpeSuppressionAnalyzer(); suppression.initialize(engine.getSettings()); suppression.prepareAnalyzer(engine); }
Source:
public synchronized ITmfTimestamp readEnd() { try { Long pos = fFile.length() - 1; while (pos > 0) { while (pos > 0) { fFile.seek(pos - 1); if (fFile.read() == '<') { break; } pos--; } ITmfLocation location = new TmfLongLocation(pos); ITmfContext context = seekEvent(location); ITmfEvent event = parseEvent(context); context.dispose(); if (event != null) { return event.getTimestamp(); } pos--; } } catch (IOException e) { return null; } return null; }

Target:
public synchronized ITmfTimestamp readEnd() { byte[] inputNameBytes = ("<" + fRecordInputElement.getInputName()).getBytes(); try { Long pos = fFile.length() - inputNameBytes.length; while (pos >= 0) { searchloop: while (pos >= 0) { fFile.seek(pos); for (byte c : inputNameBytes) { if (c != fFile.read()) { break searchloop; } } pos--; } ITmfLocation location = new TmfLongLocation(pos); ITmfContext context = seekEvent(location); ITmfEvent event = parseEvent(context); context.dispose(); if (event != null) { return event.getTimestamp(); } pos -= inputNameBytes.length; } } catch (IOException e) { return null; } return null; }
Source:
protected void setAttributeValuesIfNotDefault(AztecAttributes attributes, MediaFile mediaFile) { if (!mediaFile.getTitle().equalsIgnoreCase(DEFAULT_MEDIA_TITLE)) { attributes.setValue("title", mediaFile.getTitle()); } if (mediaFile.getWidth() != DEFAULT_MEDIA_WIDTH) { attributes.setValue("width", String.valueOf(mediaFile.getWidth())); } if (mediaFile.getHeight() != DEFAULT_MEDIA_HEIGHT) { attributes.setValue("height", String.valueOf(mediaFile.getHeight())); } }

Target:
protected void setAttributeValuesIfNotDefault(AztecAttributes attributes, MediaFile mediaFile) { if (mediaFile.getWidth() != DEFAULT_MEDIA_WIDTH) { attributes.setValue(ATTR_DIMEN_WIDTH, String.valueOf(mediaFile.getWidth())); } if (mediaFile.getHeight() != DEFAULT_MEDIA_HEIGHT) { attributes.setValue(ATTR_DIMEN_HEIGHT, String.valueOf(mediaFile.getHeight())); } }
Source:
private void scheduleRelogin(Throwable error) { assert eventLoop.inEventLoop(); if (error instanceof FallbackDisallowedException) { return; } if (!provider.canRetry()) { LOG.trace("SASL Provider does not support retries"); return; } if (reloginInProgress) { return; } reloginInProgress = true; RELOGIN_EXECUTOR.schedule(new Runnable() { @Override public void run() { try { provider.relogin(); } catch (IOException e) { LOG.warn("Relogin failed", e); } eventLoop.execute(() -> { reloginInProgress = false; }); } }, ThreadLocalRandom.current().nextInt(reloginMaxBackoff), TimeUnit.MILLISECONDS); }

Target:
private void scheduleRelogin(Throwable error) { assert eventLoop.inEventLoop(); if (error instanceof FallbackDisallowedException) { return; } if (!provider.canRetry()) { LOG.trace("SASL Provider does not support retries"); return; } if (reloginInProgress) { return; } reloginInProgress = true; RELOGIN_EXECUTOR.schedule(() -> { try { provider.relogin(); } catch (IOException e) { LOG.warn("Relogin failed", e); } eventLoop.execute(() -> { reloginInProgress = false; }); }, ThreadLocalRandom.current().nextInt(reloginMaxBackoff), TimeUnit.MILLISECONDS); }
Source:
public void onUserRestrictionsChanged() { final Bundle restrictions = mUserManager.getUserRestrictions(); final boolean newlyDisallowed = restrictions.getBoolean(UserManager.DISALLOW_CONFIG_TETHERING); final boolean prevDisallowed = mDisallowTethering; mDisallowTethering = newlyDisallowed; final boolean tetheringDisallowedChanged = (newlyDisallowed != prevDisallowed); if (!tetheringDisallowedChanged) { return; } mNotificationUpdater.clearNotification(RESTRICTED_NOTIFICATION_ID); final boolean isTetheringActiveOnDevice = (mWrapper.getTetheredIfaces().length != 0); if (newlyDisallowed && isTetheringActiveOnDevice) { mWrapper.untetherAll(); mNotificationUpdater.setupRestrictedNotification(); } }

Target:
public void onUserRestrictionsChanged() { final Bundle restrictions = mUserManager.getUserRestrictions(); final boolean newlyDisallowed = restrictions.getBoolean(UserManager.DISALLOW_CONFIG_TETHERING); final boolean prevDisallowed = mDisallowTethering; mDisallowTethering = newlyDisallowed; final boolean tetheringDisallowedChanged = (newlyDisallowed != prevDisallowed); if (!tetheringDisallowedChanged) { return; } if (!newlyDisallowed) { mNotificationUpdater.tetheringRestrictionLifted(); return; } mNotificationUpdater.notifyTetheringDisabledByRestriction(); if (mWrapper.getTetheredIfaces().length != 0) { mWrapper.untetherAll(); } }
Source:
AbstractChangeNotes(GitRepositoryManager repoManager, Change change) { this.repoManager = repoManager; this.change = change; }

Target:
AbstractChangeNotes(GitRepositoryManager repoManager, Change change) { this.repoManager = repoManager; this.change = new Change(change); }
Source:
public BytesReference generateSourceAndCheckConstraints(Object[] values) throws IOException { HashMap<String, Object> source = new HashMap<>(); row.firstCells(values); row.secondCells(defaultValues); for (int i = 0; i < targets.size(); i++) { Reference target = targets.get(i); Object value = row.get(i); if (target.granularity() == RowGranularity.DOC) { ColumnIdent column = target.column(); Maps.mergeInto(source, column.name(), column.path(), value, Map::putIfAbsent); } else if (target.granularity() == RowGranularity.PARTITION && !(target instanceof GeneratedReference)) { checks.validate(target.column(), value); } } generatedColumns.setNextRow(row); generatedColumns.validateValues(source); for (var entry : generatedColumns.generatedToInject()) { ColumnIdent column = entry.getKey().column(); Maps.mergeInto(source, column.name(), column.path(), entry.getValue().value()); } checks.validate(source); if (dryRun) { return BytesArray.EMPTY; } else { return BytesReference.bytes(XContentFactory.jsonBuilder().map(source)); } }

Target:
public BytesReference generateSourceAndCheckConstraints(Object[] values) throws IOException { HashMap<String, Object> source = new HashMap<>(); row.firstCells(values); row.secondCells(defaultValues); for (int i = 0; i < targets.size(); i++) { Reference target = targets.get(i); Object value = row.get(i); if (target.granularity() == RowGranularity.DOC) { ColumnIdent column = target.column(); Maps.mergeInto(source, column.name(), column.path(), value, Map::putIfAbsent); } else if (target.granularity() == RowGranularity.PARTITION && !(target instanceof GeneratedReference)) { checks.validate(target.column(), value); } } generatedColumns.setNextRow(row); generatedColumns.validateValues(source); for (var entry : generatedColumns.generatedToInject()) { ColumnIdent column = entry.getKey().column(); Maps.mergeInto(source, column.name(), column.path(), entry.getValue().value()); } checks.validate(source); return BytesReference.bytes(XContentFactory.jsonBuilder().map(source)); }
Source:
public Response triggerGenerateBuildPlan(@Context UriInfo uriInfo) { String plansURI = uriInfo.getAbsolutePath().resolve("../plans/").toString(); String csarURI = uriInfo.getAbsolutePath().resolve("../?csar").toString(); String request = "<generatePlanForTopology><CSARURL>"; request += csarURI; request += "</CSARURL><PLANPOSTURL>"; request += plansURI; request += "</PLANPOSTURL></generatePlanForTopology>"; Client client = Client.create(); Builder wr = null; if (Utils.isResourceAvailable("http://localhost:1339/planbuilder")) { wr = client.resource("http://localhost:1339/planbuilder/sync").type(MediaType.APPLICATION_XML); } else if (Utils.isResourceAvailable("http://localhost:1337/containerapi/planbuilder")) { wr = client.resource("http://localhost:1337/containerapi/planbuilder/sync").type(MediaType.APPLICATION_XML); } try { wr.post(String.class, request); } catch (com.sun.jersey.api.client.UniformInterfaceException e) { return Response.serverError().entity(e.getMessage()).build(); } return Response.ok().build(); }

Target:
public Response triggerGenerateBuildPlan(@Context UriInfo uriInfo) { String plansURI = uriInfo.getAbsolutePath().resolve("../plans/").toString(); String csarURI = uriInfo.getAbsolutePath().resolve("../?csar").toString(); String request = "<generatePlanForTopology><CSARURL>"; request += csarURI; request += "</CSARURL><PLANPOSTURL>"; request += plansURI; request += "</PLANPOSTURL></generatePlanForTopology>"; Client client = Client.create(); Builder wr = null; if (RestUtils.isResourceAvailable("http://localhost:1339/planbuilder")) { wr = client.resource("http://localhost:1339/planbuilder/sync").type(MediaType.APPLICATION_XML); } else if (RestUtils.isResourceAvailable("http://localhost:1337/containerapi/planbuilder")) { wr = client.resource("http://localhost:1337/containerapi/planbuilder/sync").type(MediaType.APPLICATION_XML); } try { wr.post(String.class, request); } catch (com.sun.jersey.api.client.UniformInterfaceException e) { return Response.serverError().entity(e.getMessage()).build(); } return Response.ok().build(); }