auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void GetReturnsAllAvailableMetadataFormats() throws Exception { <START> String token = getAuthToken(admin.getEmail(), password); <END> List<Map<String,String>> configs = OAIHarvester.getAvailableMetadataFormats(); getClient(token).perform( get("/api/config/harvestermetadata")) .andExpect(status().isOk()) .andExpect(jsonPath("$", Matchers.allOf( MetadataConfigsMatcher.matchMetadataConfigs(configs) ))) .andExpect(jsonPath("$._links.self.href", endsWith("/api/config/harvestermetadata"))); }</code><technical_language>a test for a non-admin user, authenticated</technical_language>

Target:
public void GetReturnsAllAvailableMetadataFormats() throws Exception { String token = getAuthToken(admin.getEmail(), password); List<Map<String,String>> configs = OAIHarvester.getAvailableMetadataFormats(); getClient(token).perform( get("/api/config/harvestermetadata")) .andExpect(status().isOk()) .andExpect(jsonPath("$", Matchers.allOf( MetadataConfigsMatcher.matchMetadataConfigs(configs) ))) .andExpect(jsonPath("$._links.self.href", endsWith("/api/config/harvestermetadata"))); getClient().perform( get("/api/config/harvestermetadata")) .andExpect(status().isOk()) .andExpect(jsonPath("$", Matchers.allOf( MetadataConfigsMatcher.matchMetadataConfigs(configs) ))) .andExpect(jsonPath("$._links.self.href", endsWith("/api/config/harvestermetadata"))); token = getAuthToken(eperson.getEmail(), password); getClient(token).perform( get("/api/config/harvestermetadata")) .andExpect(status().isOk()) .andExpect(jsonPath("$", Matchers.allOf( MetadataConfigsMatcher.matchMetadataConfigs(configs) ))) .andExpect(jsonPath("$._links.self.href", endsWith("/api/config/harvestermetadata"))); }
Source:
<code>public void write(StreamsDatum streamsDatum) { ObjectNode node; if (streamsDatum.getDocument() instanceof String) { try { node = mapper.readValue((String) streamsDatum.getDocument(), ObjectNode.class); byte[] value = node.toString().getBytes(); BoundStatement statement = insertStatement.bind(GuidUtils.generateGuid(node.toString()), ByteBuffer.wrap(value)); insertBatch.add(statement); } catch (IOException ex) { ex.printStackTrace(); LOGGER.warn("Failure adding object: {}", streamsDatum.getDocument().toString()); return; } } else { try { node = mapper.valueToTree(streamsDatum.getDocument()); byte[] value = node.toString().getBytes(); <START> BoundStatement statement = insertStatement.bind(GuidUtils.generateGuid(node.toString()), ByteBuffer.wrap(value)); <END> insertBatch.add(statement); } catch (Exception ex) { ex.printStackTrace(); LOGGER.warn("Failure adding object: {}", streamsDatum.getDocument().toString()); return; } } flushIfNecessary(); }</code><technical_language>consider streamsDatum.getMetadata().get("id") if exists, enabling stream get a write-then-overwrite behavior id is known</technical_language>

Target:
public void write(StreamsDatum streamsDatum) { ObjectNode node; if (streamsDatum.getDocument() instanceof String) { try { node = mapper.readValue((String) streamsDatum.getDocument(), ObjectNode.class); byte[] value = node.toString().getBytes(); String key = GuidUtils.generateGuid(node.toString()); if(!Objects.isNull(streamsDatum.getMetadata().get("id"))) { key = streamsDatum.getMetadata().get("id").toString(); } BoundStatement statement = insertStatement.bind(key, ByteBuffer.wrap(value)); insertBatch.add(statement); } catch (IOException ex) { LOGGER.warn("Failure adding object: {}", streamsDatum.getDocument().toString()); return; } } else { try { node = mapper.valueToTree(streamsDatum.getDocument()); byte[] value = node.toString().getBytes(); String key = GuidUtils.generateGuid(node.toString()); if(!Objects.isNull(streamsDatum.getMetadata().get("id"))) { key = streamsDatum.getMetadata().get("id").toString(); } BoundStatement statement = insertStatement.bind(key, ByteBuffer.wrap(value)); insertBatch.add(statement); } catch (Exception ex) { LOGGER.warn("Failure adding object: {}", streamsDatum.getDocument().toString()); return; } } flushIfNecessary(); }
Source:
<code>private static PullRef.Smart pullRef(final Repo repo) throws IOException { final Coordinates coords = repo.coordinates(); final JsonObject user = Json.createObjectBuilder() .add("login", coords.user()) .build(); return new PullRef.Smart( new RtPullRef( repo.github(), Json.createObjectBuilder() .add("label", LABEL) .add("ref", REF) .add("sha", SHA) .add("user", user) .add( "repo", Json.createObjectBuilder() .add("name", coords.repo()) .add("full_name", coords.toString()) .add("owner", user) .build() ) <START> .build() <END> ) ); }</code><technical_language>@cvrebert move this up</technical_language>

Target:
private static PullRef.Smart pullRef(final Repo repo) throws IOException { final Coordinates coords = repo.coordinates(); final JsonObject user = Json.createObjectBuilder() .add("login", coords.user()) .build(); return new PullRef.Smart( new RtPullRef( repo.github(), Json.createObjectBuilder() .add("label", PullRefTest.LABEL) .add("ref", PullRefTest.REF) .add("sha", PullRefTest.SHA) .add("user", user) .add( "repo", Json.createObjectBuilder() .add("name", coords.repo()) .add("full_name", coords.toString()) .add("owner", user) .build() ).build() ) ); }
Source:
<code>public static DataSet generate(final int numArticles, final int numComments) { <START> final int timeSpan = 1000 * 60 * 60 * 24 * 7; <END> final long dataStartTime = System.currentTimeMillis(); final long dataEndTime = dataStartTime + timeSpan; final long seed = new Random().nextLong(); final Random random = new Random(seed); LOG.info("Dataset PRNG seed: {}", seed); final Iterator<Integer> articlesToCommentOnSequence = zipfNormal(random, numArticles); final Article[] articles = new Article[numArticles]; final Comment[] comments = new Comment[numComments]; for (int i = 0; i < numArticles; i++) { final long timestamp = random.nextInt(timeSpan) + dataStartTime; final String text = randomText(random, 2000); articles[i] = new Article(i, timestamp, text); } for (int i = 0; i < numComments; i++) { final int articleId = articlesToCommentOnSequence.next(); final long articleTimestamp = articles[articleId].getTimestamp(); final long timestamp = random.nextInt((int) (dataEndTime - articleTimestamp)) + articleTimestamp; final String text = randomText(random, 200); final Comment comment = new Comment(i, timestamp, text, articleId); comments[i] = comment; } return new DataSet(articles, comments); }</code><technical_language>suggest put time span 4 days safer side, 7 day log retention kicks in a bit earlier</technical_language>

Target:
public static DataSet generate(final int numArticles, final int numComments) { final int timeSpan = 1000 * 60 * 60 * 24 * 4; final long dataStartTime = System.currentTimeMillis(); final long dataEndTime = dataStartTime + timeSpan; final long seed = new Random().nextLong(); final Random random = new Random(seed); LOG.info("Dataset PRNG seed: {}", seed); final Iterator<Integer> articlesToCommentOnSequence = zipfNormal(random, numArticles); final Article[] articles = new Article[numArticles]; final Comment[] comments = new Comment[numComments]; for (int i = 0; i < numArticles; i++) { final long timestamp = random.nextInt(timeSpan) + dataStartTime; final String text = randomText(random, 2000); articles[i] = new Article(i, timestamp, text); } for (int i = 0; i < numComments; i++) { final int articleId = articlesToCommentOnSequence.next(); final long articleTimestamp = articles[articleId].getTimestamp(); final long timestamp = random.nextInt((int) (dataEndTime - articleTimestamp)) + articleTimestamp; final String text = randomText(random, 200); final Comment comment = new Comment(i, timestamp, text, articleId); comments[i] = comment; } return new DataSet(articles, comments); }
Source:
<code>T map(ResultSet rs, StatementContext ctx) throws SQLException; <START> default RowMapper<T> memoize(ResultSet rs, StatementContext ctx) throws SQLException { <END> return this; }</code><technical_language>if memoize is right name here. specifically refers a pure function remember return value, here. specialize beginMapping that</technical_language>

Target:
T map(ResultSet rs, StatementContext ctx) throws SQLException; default RowMapper<T> specialize(ResultSet rs, StatementContext ctx) throws SQLException { return this; }
Source:
<code>public void accept(Object obj) { for (XYSeriesConsumer consumer : fSeries) { consumer.accept(obj); <START> } <END> }</code><technical_language>forEach a List directly: fSeries.forEach(consumer -> consumer.accept(obj)); work, difference, functional syntax fit rest imo</technical_language>

Target:
public void accept(Object obj) { fSeries.forEach(consumer -> consumer.accept(obj)); }
Source:
<code><START> private int nioBuffers(Entry entry, ByteBuf buf, ByteBuffer[] nioBuffers, int nioBufferCount, int maxCount) { <END> ByteBuffer[] nioBufs = entry.bufs; if (nioBufs == null) { entry.bufs = nioBufs = buf.nioBuffers(); } for (int i = 0; i < nioBufs.length && nioBufferCount < maxCount; ++i) { ByteBuffer nioBuf = nioBufs[i]; if (nioBuf == null) { break; } else if (!nioBuf.hasRemaining()) { continue; } nioBuffers[nioBufferCount++] = nioBuf; } return nioBufferCount; }</code><technical_language>static</technical_language>

Target:
private static int nioBuffers(Entry entry, ByteBuf buf, ByteBuffer[] nioBuffers, int nioBufferCount, int maxCount) { ByteBuffer[] nioBufs = entry.bufs; if (nioBufs == null) { entry.bufs = nioBufs = buf.nioBuffers(); } for (int i = 0; i < nioBufs.length && nioBufferCount < maxCount; ++i) { ByteBuffer nioBuf = nioBufs[i]; if (nioBuf == null) { break; } else if (!nioBuf.hasRemaining()) { continue; } nioBuffers[nioBufferCount++] = nioBuf; } return nioBufferCount; }
Source:
<code>public void setXFraction(float fraction) { <START> this.xFraction = fraction; <END> if (getWidth() == 0) { if (preDrawListener == null) { preDrawListener = new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { getViewTreeObserver().removeOnPreDrawListener(preDrawListener); setXFraction(xFraction); return true; } }; getViewTreeObserver().addOnPreDrawListener(preDrawListener); } return; } float translationX = getWidth() * fraction; setTranslationX(translationX); }</code><technical_language>Nitpicking here: of this is redundant, especially naming conventions followed, in case name mXFraction clear instance variable want assign to. boils a matter of personal coding style (and a consistent pattern in rest of app) leave this totally you. Cheers</technical_language>

Target:
public void setXFraction(float fraction) { mXFraction = fraction; if (getWidth() == 0) { if (mPreDrawListener == null) { mPreDrawListener = new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { getViewTreeObserver().removeOnPreDrawListener(mPreDrawListener); setXFraction(mXFraction); return true; } }; getViewTreeObserver().addOnPreDrawListener(mPreDrawListener); } return; } float translationX = getWidth() * fraction; setTranslationX(translationX); }
Source:
<code>public static IRecipe[] getRecipes(String... keys) { ArrayList<IRecipe> recipes = new ArrayList<>(); for (String key : keys) { recipes.add(BookRecipeRegistry.getRecipe(key)); } <START> return recipes.size() > 0 ? recipes.toArray(new IRecipe[recipes.size()]) : new IRecipe[0]; <END> }</code><technical_language>size() check replaced !isEmpty()</technical_language>

Target:
public static IRecipe[] getRecipes(String... keys) { ArrayList<IRecipe> recipes = new ArrayList<>(); for (String key : keys) { recipes.add(BookRecipeRegistry.getRecipe(key)); } return !recipes.isEmpty() ? recipes.toArray(new IRecipe[recipes.size()]) : new IRecipe[0]; }
Source:
<code>public void testFindJdk() { final File executable = PantsUtil.findPantsExecutable(getProjectFolder()).get(); final Sdk sdkA = getDefaultJavaSdk(executable.getPath()).get(); List<Sdk> sdkResults = Arrays.stream(ProjectJdkTable.getInstance().getAllJdks()) .filter(jdk -> jdk == sdkA) .collect(Collectors.toList()); <START> assertTrue(sdkResults.size() == 1); <END> assertTrue(sdkResults.get(0) == sdkA); ApplicationManager.getApplication().runWriteAction(() -> { ProjectJdkTable.getInstance().addJdk(sdkA); }); sdkResults = Arrays.stream(ProjectJdkTable.getInstance().getAllJdks()) .filter(jdk -> jdk == sdkA) .collect(Collectors.toList()); assertTrue(sdkResults.size() == 2); Sdk sdkB = getDefaultJavaSdk(executable.getPath()).get(); assertTrue(sdkA == sdkB); sdkResults = Arrays.stream(ProjectJdkTable.getInstance().getAllJdks()) .filter(jdk -> jdk == sdkA) .collect(Collectors.toList()); assertTrue(sdkResults.size() == 2); assertTrue(sdkResults.get(0) == sdkA); }</code><technical_language>assertEqual for</technical_language>

Target:
public void testFindJdk() { final File executable = PantsUtil.findPantsExecutable(getProjectFolder()).get(); assertEquals(Lists.newArrayList(), getAllJdks().collect(Collectors.toList())); final Sdk sdkA = getDefaultJavaSdk(executable.getPath()).get(); assertEquals(Lists.newArrayList(sdkA), getSameJdks(sdkA)); final List<Sdk> singleSdkInTable = getSameJdks(sdkA); assertTrue(singleSdkInTable.get(0).getName().contains("pants")); final List<Sdk> twoEntriesSameSdk = Lists.newArrayList(sdkA, sdkA); ApplicationManager.getApplication().runWriteAction(() -> { ProjectJdkTable.getInstance().addJdk(sdkA); }); assertEquals(twoEntriesSameSdk, getSameJdks(sdkA)); final Sdk sdkB = getDefaultJavaSdk(executable.getPath()).get(); assertTrue(sdkA == sdkB); assertEquals(twoEntriesSameSdk, getSameJdks(sdkA)); }
Source:
<code>private AsyncRequestListener(final HttpServletRequest request, final HttpServletResponse response, final long startTime, final String flowId) { this.response = response; this.flowId = flowId; this.requestLogInfo = new RequestLogInfo(request, startTime); <START> logToAccessLog(this.requestLogInfo, this.response.getStatus(), 0L); <END> }</code><technical_language>@v-stepanov changing behavior? this change log 102 clear if status in response is 102. I this is a special log for calls consumption API real response status code afterwards</technical_language>

Target:
private AsyncRequestListener(final HttpServletRequest request, final HttpServletResponse response, final long startTime, final String flowId) { this.response = response; this.flowId = flowId; this.requestLogInfo = new RequestLogInfo(request, startTime); logToAccessLog(this.requestLogInfo, HttpStatus.PROCESSING.value(), 0L); }
Source:
<code>public void testValueOf() { assertEquals(CENT, valueOf(0, 1)); assertEquals(SATOSHI, valueOf(1)); assertEquals(NEGATIVE_ONE, valueOf(-1)); assertEquals(NetworkParameters.MAX_MONEY, valueOf(NetworkParameters.MAX_MONEY.value)); assertEquals(NetworkParameters.MAX_MONEY.negate(), valueOf(NetworkParameters.MAX_MONEY.value * -1)); try { valueOf(NetworkParameters.MAX_MONEY.value + 1); org.junit.Assert.fail("should not have accepted too-great a monetary value"); } catch (ArithmeticException e) { } try { valueOf( (NetworkParameters.MAX_MONEY.value * -1) - 1); org.junit.Assert.fail("should not have accepted too-little a monetary value"); } catch (ArithmeticException e) { } try { valueOf(1, -1); fail(); } catch (IllegalArgumentException e) try { valueOf(-1, 0); fail(); } catch (IllegalArgumentException e) <START> <END> }</code><technical_language>Stray empty line</technical_language>

Target:
public void testValueOf() { assertEquals(CENT, valueOf(0, 1)); assertEquals(SATOSHI, valueOf(1)); assertEquals(NEGATIVE_SATOSHI, valueOf(-1)); assertEquals(MAX_MONEY, valueOf(MAX_MONEY.value)); assertEquals(MAX_MONEY.negate(), valueOf(MAX_MONEY.value * -1)); try { valueOf(MAX_MONEY.value + 1); org.junit.Assert.fail("should not have accepted too-great a monetary value"); } catch (IllegalArgumentException e) { } try { valueOf( (MAX_MONEY.value * -1) - 1); org.junit.Assert.fail("should not have accepted too-little a monetary value"); } catch (IllegalArgumentException e) { } try { valueOf(1, -1); fail(); } catch (IllegalArgumentException e) try { valueOf(-1, 0); fail(); } catch (IllegalArgumentException e) }
Source:
<code>protected void saveContent(String content) { Intent savedContentIntent = new Intent(); String blockId = getIntent().getExtras().getString(ARG_BLOCK_ID); <START> savedContentIntent.putExtra(ARG_BLOCK_ID, blockId); <END> savedContentIntent.putExtra(RESULT_SAVED_CONTENT, content); setResult(RESULT_OK, savedContentIntent); finish(); }</code><technical_language>This is a confusing, I in GutenbergEditorFragment extract this RESULT_BLOCK_ID ([L473 of GutenbergEditorFragment](<LINK_0> reason works is ARG_BLOCK_ID</technical_language>

Target:
protected void saveContent(String content) { Intent savedContentIntent = new Intent(); String blockId = getIntent().getExtras().getString(ARG_BLOCK_ID); savedContentIntent.putExtra(ARG_BLOCK_ID, blockId); savedContentIntent.putExtra(ARG_BLOCK_CONTENT, content); setResult(RESULT_OK, savedContentIntent); finish(); }
Source:
<code>public static void classLevelSetup() throws Exception { Map<String, String> overrides = new HashMap<>(); overrides.put(MetastoreConf.ConfVars.EVENT_MESSAGE_FACTORY.getHiveName(), GzipJSONMessageEncoder.class.getCanonicalName()); overrides.put(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY.varname, "true"); overrides.put(HiveConf.ConfVars.HIVE_TXN_MANAGER.varname, "org.apache.hadoop.hive.ql.lockmgr.DbTxnManager"); overrides.put(MetastoreConf.ConfVars.CAPABILITY_CHECK.getHiveName(),"false"); overrides.put(HiveConf.ConfVars.REPL_BOOTSTRAP_DUMP_OPEN_TXN_TIMEOUT.varname,"1s"); overrides.put(HiveConf.ConfVars.DYNAMICPARTITIONINGMODE.varname, "nonstrict"); <START> internalBeforeClassSetup(overrides, overrides, TestReplicationScenarios.class, true, "mm"); <END> }</code><technical_language>current class name TestStatsReplicationScenariosMM</technical_language>

Target:
public static void classLevelSetup() throws Exception { Map<String, String> overrides = new HashMap<>(); overrides.put(MetastoreConf.ConfVars.EVENT_MESSAGE_FACTORY.getHiveName(), GzipJSONMessageEncoder.class.getCanonicalName()); overrides.put(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY.varname, "true"); overrides.put(HiveConf.ConfVars.HIVE_TXN_MANAGER.varname, "org.apache.hadoop.hive.ql.lockmgr.DbTxnManager"); overrides.put(MetastoreConf.ConfVars.CAPABILITY_CHECK.getHiveName(),"false"); overrides.put(HiveConf.ConfVars.REPL_BOOTSTRAP_DUMP_OPEN_TXN_TIMEOUT.varname,"1s"); overrides.put(HiveConf.ConfVars.DYNAMICPARTITIONINGMODE.varname, "nonstrict"); internalBeforeClassSetup(overrides, overrides, TestStatsReplicationScenariosMM.class, true, AcidTableKind.INSERT_ONLY); }
Source:
<code>protected boolean canDoAction() { initVmTemplate(); if (isImagesAlreadyOnTarget()) { if (ovfEntityData == null && !getParameters().isImportAsNewEntity()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_UNSUPPORTED_OVF); return false; } if (vmTemplateFromConfiguration == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_OVF_CONFIGURATION_NOT_SUPPORTED); return false; } setStorageDomainId(ovfEntityData.getStorageDomainId()); if (!validate(new StorageDomainValidator(getStorageDomain()).isDomainExistAndActive())) { return false; } if (!getStorageDomain().getStorageDomainType().isDataDomain()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_UNSUPPORTED, String.format("$domainId %1$s", getParameters().getStorageDomainId()), String.format("$domainType %1$s", getStorageDomain().getStorageDomainType())); } } <START> List<DiskImage> disks = new ArrayList(getVmTemplate().getDiskTemplateMap().values()); <END> setImagesWithStoragePoolId(getStorageDomain().getStoragePoolId(), disks); getParameters().setImages(disks); getVmTemplate().setImages((ArrayList)disks); return super.canDoAction(); }</code><technical_language>changed ArrayList avoid casting in setImages</technical_language>

Target:
protected boolean canDoAction() { initVmTemplate(); if (isImagesAlreadyOnTarget()) { if (ovfEntityData == null && !getParameters().isImportAsNewEntity()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_UNSUPPORTED_OVF); return false; } if (vmTemplateFromConfiguration == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_OVF_CONFIGURATION_NOT_SUPPORTED); return false; } setStorageDomainId(ovfEntityData.getStorageDomainId()); if (!validate(new StorageDomainValidator(getStorageDomain()).isDomainExistAndActive())) { return false; } if (!getStorageDomain().getStorageDomainType().isDataDomain()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_UNSUPPORTED, String.format("$domainId %1$s", getParameters().getStorageDomainId()), String.format("$domainType %1$s", getStorageDomain().getStorageDomainType())); } } ArrayList<DiskImage> disks = new ArrayList(getVmTemplate().getDiskTemplateMap().values()); setImagesWithStoragePoolId(getStorageDomain().getStoragePoolId(), disks); getParameters().setImages(disks); getVmTemplate().setImages(disks); return super.canDoAction(); }
Source:
<code>protected Object decodeUdp(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) throws Exception { <START> int packetId = buf.getShort(2); <END> int imeiLength = buf.getUnsignedShort(6); String imei = buf.toString(8, imeiLength, StandardCharsets.US_ASCII); int offset = 8 + imeiLength; return parseData(channel, remoteAddress, buf, offset, packetId, imei); }</code><technical_language>getXxx methods instead of readXxx? I simplify if read. need offsets</technical_language>

Target:
protected Object decodeUdp(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) throws Exception { buf.skipBytes(2); int packetId = buf.readUnsignedShort(); buf.skipBytes(2); int imeiLength = buf.readUnsignedShort(); String imei = buf.toString(8, imeiLength, StandardCharsets.US_ASCII); buf.skipBytes(imeiLength); return parseData(channel, remoteAddress, buf, packetId, imei); }
Source:
<code>public static boolean isAlgorithmSupported(String algorithm) { <START> return ALGORITHM_SIMPLE_DIGEST_MD5.equals(algorithm) || <END> ALGORITHM_SIMPLE_DIGEST_SHA_1.equals(algorithm) || ALGORITHM_SIMPLE_DIGEST_SHA_256.equals(algorithm) || ALGORITHM_SIMPLE_DIGEST_SHA_384.equals(algorithm) || ALGORITHM_SIMPLE_DIGEST_SHA_512.equals(algorithm) || ALGORITHM_PASSWORD_SALT_DIGEST_MD5.equals(algorithm) || ALGORITHM_PASSWORD_SALT_DIGEST_SHA_1.equals(algorithm) || ALGORITHM_PASSWORD_SALT_DIGEST_SHA_256.equals(algorithm) || ALGORITHM_PASSWORD_SALT_DIGEST_SHA_384.equals(algorithm) || ALGORITHM_PASSWORD_SALT_DIGEST_SHA_512.equals(algorithm) || BSDUnixDESCryptPassword.ALGORITHM_BSD_CRYPT_DES.equals(algorithm) || UnixDESCryptPassword.ALGORITHM_CRYPT_DES.equals(algorithm) || ClearPassword.ALGORITHM_CLEAR.equals(algorithm); }</code><technical_language>This is a lot of equals() calls. I a String switch here</technical_language>

Target:
public static boolean isAlgorithmSupported(String algorithm) { switch (algorithm) { case ALGORITHM_SIMPLE_DIGEST_MD5: case ALGORITHM_SIMPLE_DIGEST_SHA_1: case ALGORITHM_SIMPLE_DIGEST_SHA_256: case ALGORITHM_SIMPLE_DIGEST_SHA_384: case ALGORITHM_SIMPLE_DIGEST_SHA_512: case ALGORITHM_PASSWORD_SALT_DIGEST_MD5: case ALGORITHM_PASSWORD_SALT_DIGEST_SHA_1: case ALGORITHM_PASSWORD_SALT_DIGEST_SHA_256: case ALGORITHM_PASSWORD_SALT_DIGEST_SHA_384: case ALGORITHM_PASSWORD_SALT_DIGEST_SHA_512: case ALGORITHM_BSD_CRYPT_DES: case ALGORITHM_CRYPT_DES: case ALGORITHM_CLEAR: return true; default: return false; } }
Source:
<code>public EnumSet<NeededData> getNeededData() { <START> return EnumSet.of(NeededData.CHANGE); <END> }</code><technical_language>This is harder. need more change. user's notification filters include "reviewer:foo" require approvals. need loop of filters, compile them, get NeededData values union need for change here</technical_language>

Target:
public EnumSet<NeededData> getNeededData() { loadRules(); EnumSet<NeededData> needed = EnumSet.noneOf(NeededData.class); for (List<Predicate<ChangeData>> list : rules.values()) { for (Predicate<ChangeData> p : list) { if (p instanceof Prefetchable) { needed.addAll(((Prefetchable) p).getNeededData()); } } } return needed; }
Source:
<code>public String toString() { <START> return String.valueOf(leftOp) + kind.operand + rightOp; <END> }</code><technical_language>call toString ? I a bit confused fact rely + operator of strings implicit toString calls</technical_language>

Target:
public String toString() { return leftOp.toString() + kind.operand + rightOp.toString(); }
Source:
<code>@Override void apply(RequestBuilder builder, @Nullable Object value) { try { checkNotNull(value, "@Url parameter is null."); <START> } catch (NullPointerException npe) { <END> throw Utils.parameterError(method, npe, p, "@Url parameter is null."); } builder.setRelativeUrl(value); }</code><technical_language>need do this. check for null locally pass null Utils method</technical_language>

Target:
@Override void apply(RequestBuilder builder, @Nullable Object value) { if (value == null) { throw Utils.parameterError(method, p, "@Url parameter is null."); } builder.setRelativeUrl(value); }
Source:
<code>private void jobStatus(ExecutorDriver driver, TaskInfo task) { if (process == null) { LOGGER.error("No Cassandra process to handle node-job-status"); if (task != null) <START> driver.sendStatusUpdate(taskStatus(task, TaskState.TASK_ERROR, nullSlaveStatusDetails())); <END> return; } AbstractNodeJob current = currentJob.get(); if (current == null) { LOGGER.error("No current job to handle node-job-status"); return; } NodeJobStatus.Builder status = NodeJobStatus.newBuilder() .setExecutorId(this.executorInfo.getExecutorId().getValue()) .setTaskId(current.getTaskId().getValue()) .setJobType(current.getType()) .setRunning(!current.isFinished()) .addAllRemainingKeyspaces(current.getRemainingKeyspaces()) .addAllProcessedKeyspaces(current.getKeyspaceStatus().values()) .setStartedTimestamp(current.getStartTimestamp()) .setFinishedTimestamp(current.getFinishedTimestamp()); SlaveStatusDetails repairDetails = SlaveStatusDetails.newBuilder() .setStatusDetailsType(SlaveStatusDetails.StatusDetailsType.NODE_JOB_STATUS) .setNodeJobStatus(status).build(); LOGGER.debug("Sending node-job-status result, finished={}", current.isFinished()); driver.sendFrameworkMessage(repairDetails.toByteArray()); if (current.isFinished()) { driver.sendStatusUpdate(taskStatus(executorInfo.getExecutorId(), current.getTaskId(), TaskState.TASK_FINISHED, repairDetails)); currentJob.set(null); } if (task != null) { driver.sendStatusUpdate(taskStatus(task, TaskState.TASK_FINISHED, repairDetails)); } }</code><technical_language>want some detail scheduler intelligently handle if a job start a process running</technical_language>

Target:
private void jobStatus(ExecutorDriver driver, TaskInfo task) { if (process == null) { LOGGER.error("No Cassandra process to handle node-job-status"); if (task != null) { serverProcessNotRunning(driver, task); } return; } AbstractNodeJob current = currentJob.get(); if (current == null) { LOGGER.error("No current job to handle node-job-status"); return; } NodeJobStatus.Builder status = NodeJobStatus.newBuilder() .setExecutorId(this.executorInfo.getExecutorId().getValue()) .setTaskId(current.getTaskId().getValue()) .setJobType(current.getType()) .setRunning(!current.isFinished()) .addAllRemainingKeyspaces(current.getRemainingKeyspaces()) .addAllProcessedKeyspaces(current.getKeyspaceStatus().values()) .setStartedTimestamp(current.getStartTimestamp()) .setFinishedTimestamp(current.getFinishedTimestamp()); SlaveStatusDetails repairDetails = SlaveStatusDetails.newBuilder() .setStatusDetailsType(SlaveStatusDetails.StatusDetailsType.NODE_JOB_STATUS) .setNodeJobStatus(status).build(); LOGGER.debug("Sending node-job-status result, finished={}", current.isFinished()); driver.sendFrameworkMessage(repairDetails.toByteArray()); if (current.isFinished()) { driver.sendStatusUpdate(taskStatus(executorInfo.getExecutorId(), current.getTaskId(), TaskState.TASK_FINISHED, repairDetails)); currentJob.set(null); } if (task != null) { driver.sendStatusUpdate(taskStatus(task, TaskState.TASK_FINISHED, repairDetails)); } }
Source:
<code>public void testUnpackingCausesDecodeFail() { EmbeddedChannel e = new EmbeddedChannel(new Socks5InitialRequestDecoder()); e.writeInbound(Unpooled.wrappedBuffer(new byte[]{5, 2, 0})); e.writeInbound(Unpooled.wrappedBuffer(new byte[]{1})); Object o = e.readInbound(); assertTrue(o instanceof DefaultSocks5InitialRequest); DefaultSocks5InitialRequest req = (DefaultSocks5InitialRequest) o; <START> assertSame(req.decoderResult(), DecoderResult.SUCCESS); <END> }</code><technical_language>Add assertFalse(e.finish());</technical_language>

Target:
public void testUnpackingCausesDecodeFail() { EmbeddedChannel e = new EmbeddedChannel(new Socks5InitialRequestDecoder()); assertFalse(e.writeInbound(Unpooled.wrappedBuffer(new byte[]{5, 2, 0}))); assertTrue(e.writeInbound(Unpooled.wrappedBuffer(new byte[]{1}))); Object o = e.readInbound(); assertTrue(o instanceof DefaultSocks5InitialRequest); DefaultSocks5InitialRequest req = (DefaultSocks5InitialRequest) o; assertSame(req.decoderResult(), DecoderResult.SUCCESS); assertFalse(e.finish()); }
Source:
<code>private void downloadPatient(final Patient patient, final Boolean showSnackBar) { new PatientApi().downloadPatientByUuid(patient.getUuid(), new DownloadPatientCallbackListener() { @Override public void onPatientDownloaded(Patient newPatient) { <START> new PatientDAO().savePatient(newPatient).subscribe(); <END> new VisitApi().syncVisitsData(newPatient); new VisitApi().syncLastVitals(newPatient.getUuid()); patients.remove(patient); notifyDataSetChanged(); if (showSnackBar) { view.showOpenPatientSnackbar(newPatient.getId()); } } @Override public void onPatientPhotoDownloaded(Patient patient) { new PatientDAO().updatePatient(patient.getId(), patient); } @Override public void onResponse() { } @Override public void onErrorResponse(String errorMessage) { ToastUtil.error("Failed to fetch patient data"); } }); }</code><technical_language>if wait for patient saved</technical_language>

Target:
private void downloadPatient(final Patient patient, final Boolean showSnackBar) { new PatientApi().downloadPatientByUuid(patient.getUuid(), new DownloadPatientCallbackListener() { @Override public void onPatientDownloaded(Patient newPatient) { new PatientDAO().savePatient(newPatient) .observeOn(AndroidSchedulers.mainThread()) .subscribe(id -> { new VisitApi().syncVisitsData(newPatient); new VisitApi().syncLastVitals(newPatient.getUuid()); patients.remove(patient); notifyDataSetChanged(); if (showSnackBar) { view.showOpenPatientSnackbar(newPatient.getId()); } }); } @Override public void onPatientPhotoDownloaded(Patient patient) { new PatientDAO().updatePatient(patient.getId(), patient); } @Override public void onResponse() { } @Override public void onErrorResponse(String errorMessage) { ToastUtil.error("Failed to fetch patient data"); } }); }
Source:
<code>public void run() { log.info(Thread.currentThread().getName() + " is starting DFS"); try { frontier.searchForScenarios(queue, flag); } catch (IOException e) { <START> e.printStackTrace(); <END> } log.info(Thread.currentThread().getName() + " is done with DFS"); }</code><technical_language>printStackTrace() instead write logger log.error("<Appropriate message>",e);</technical_language>

Target:
public void run() { log.info(Thread.currentThread().getName() + " is starting DFS"); try { frontier.searchForScenarios(queue, flag); } catch (IOException e) { log.error("", e); } log.info(Thread.currentThread().getName() + " is done with DFS"); }
Source:
<code>private static CommandScheduler createCommandScheduler() { @SuppressWarnings("AccessOfSystemProperties") <START> final String appEngineVersion = System.getProperty("com.google.appengine.runtime.version"); <END> final boolean isRunningOnAppEngine = appEngineVersion != null; if (isRunningOnAppEngine) { log().error("CommandScheduler for AppEngine is not implemented yet."); return new ExecutorCommandScheduler(); } else { return new ExecutorCommandScheduler(); } }</code><technical_language>This needs a feature of a utility class, is visible framework. called Environment that</technical_language>

Target:
private static CommandScheduler createCommandScheduler() { if (Environment.getInstance().isAppEngine()) { log().error("CommandScheduler for AppEngine is not implemented yet."); return new ExecutorCommandScheduler(); } else { return new ExecutorCommandScheduler(); } }
Source:
<code>private TypePrinter<GraphQLEnumType> enumPrinter() { return (out, type, visibility) -> { if (isIntrospectionType(type)) { return; } <START> <END> SchemaPrinterComparatorEnvironment environment = SchemaPrinterComparatorEnvironment.newEnvironment() .withParentType(GraphQLEnumType.class) .withElementType(GraphQLEnumValueDefinition.class) .build(); Comparator<? super GraphQLType> comparator = options.comparatorRegistry.getComparator(environment); printComments(out, type, ""); out.format("enum %s%s {\n", type.getName(), directivesString(GraphQLEnumType.class, type.getDirectives())); List<GraphQLEnumValueDefinition> values = type.getValues() .stream() .sorted(comparator) .collect(toList()); for (GraphQLEnumValueDefinition enumValueDefinition : values) { printComments(out, enumValueDefinition, " "); out.format(" %s%s\n", enumValueDefinition.getName(), directivesString(GraphQLEnumValueDefinition.class, enumValueDefinition.getDirectives())); } out.format("}\n\n"); }; }</code><technical_language>Static imports read builders</technical_language>

Target:
private TypePrinter<GraphQLEnumType> enumPrinter() { return (out, type, visibility) -> { if (isIntrospectionType(type)) { return; } SchemaPrinterComparatorEnvironment environment = SchemaPrinterComparatorEnvironment.newEnvironment() .parentType(GraphQLEnumType.class) .elementType(GraphQLEnumValueDefinition.class) .build(); Comparator<? super GraphQLType> comparator = options.comparatorRegistry.getComparator(environment); printComments(out, type, ""); out.format("enum %s%s {\n", type.getName(), directivesString(GraphQLEnumType.class, type.getDirectives())); List<GraphQLEnumValueDefinition> values = type.getValues() .stream() .sorted(comparator) .collect(toList()); for (GraphQLEnumValueDefinition enumValueDefinition : values) { printComments(out, enumValueDefinition, " "); out.format(" %s%s\n", enumValueDefinition.getName(), directivesString(GraphQLEnumValueDefinition.class, enumValueDefinition.getDirectives())); } out.format("}\n\n"); }; }
Source:
<code>final static public < A extends LongAccess > ArrayImg< Unsigned2BitType, A > unsigned2Bits( final A access, final long... dim ) { <START> final ArrayImg< Unsigned2BitType, A > img = new ArrayImg<>( access, dim, new Fraction( 1, 64 ) ); <END> final Unsigned2BitType t = new Unsigned2BitType( img ); img.setLinkedType( t ); return img; }</code><technical_language>this new Fraction( t.getBitsPerPixel(), 64 ) instead of new Fraction( 1, 64 ) here</technical_language>

Target:
final static public < A extends LongAccess > ArrayImg< Unsigned2BitType, A > unsigned2Bits( final A access, final long... dim ) { final ArrayImg< Unsigned2BitType, A > img = new ArrayImg<>( access, dim, new Fraction( 2, 64 ) ); final Unsigned2BitType t = new Unsigned2BitType( img ); img.setLinkedType( t ); return img; }
Source:
<code>public Charset charset() { <START> return Charset.defaultCharset(); <END> }</code><technical_language>of that? If transpile files, while a predefined charset UTF-8</technical_language>

Target:
public Charset charset() { return StandardCharsets.UTF_8; }
Source:
<code>private LDAPStoreAttributeResourceDefinition(SimpleAttributeDefinition... attributes) { super(ModelElement.LDAP_STORE_ATTRIBUTE, new IDMConfigAddStepHandler(attributes) { @Override protected boolean isAlternativesRequired() { return false; } <START> }, null, attributes); <END> }</code><technical_language>remove handler</technical_language>

Target:
private LDAPStoreAttributeResourceDefinition(SimpleAttributeDefinition... attributes) { super(ModelElement.LDAP_STORE_ATTRIBUTE, new IDMConfigAddStepHandler(attributes) { @Override protected boolean isAlternativesRequired() { return false; } }, attributes); }
Source:
<code>public PlanWithProperties visitSort(SortNode node, PreferredProperties preferredProperties) { PlanWithProperties child = planChild(node, PreferredProperties.undistributed()); if (child.getProperties().isSingleNode()) { List<LocalProperty<Symbol>> desiredProperties = new ArrayList<>(); for (Symbol symbol : node.getOrderingScheme().getOrderBy()) { desiredProperties.add(new SortingProperty<>(symbol, node.getOrderingScheme().getOrdering(symbol))); } if (LocalProperties.match(child.getProperties().getLocalProperties(), desiredProperties).stream() .noneMatch(Optional::isPresent)) { return child; } } if (isDistributedSortEnabled(session)) { child = planChild(node, PreferredProperties.any()); <START> return withDerivedProperties( <END> mergingExchange( idAllocator.getNextId(), REMOTE, new SortNode( idAllocator.getNextId(), child.getNode(), node.getOrderingScheme()), node.getOrderingScheme()), child.getProperties()); } if (!child.getProperties().isSingleNode()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); }</code><technical_language>planChild called L430; do call again? PlanWithProperties child = planChild(node, PreferredProperties.undistributed());</technical_language>

Target:
public PlanWithProperties visitSort(SortNode node, PreferredProperties preferredProperties) { PlanWithProperties child = planChild(node, PreferredProperties.undistributed()); if (child.getProperties().isSingleNode()) { List<LocalProperty<Symbol>> desiredProperties = new ArrayList<>(); for (Symbol symbol : node.getOrderingScheme().getOrderBy()) { desiredProperties.add(new SortingProperty<>(symbol, node.getOrderingScheme().getOrdering(symbol))); } if (LocalProperties.match(child.getProperties().getLocalProperties(), desiredProperties).stream() .noneMatch(Optional::isPresent)) { return child; } } if (isDistributedSortEnabled(session)) { child = planChild(node, PreferredProperties.any()); PlanNode source = roundRobinExchange(idAllocator.getNextId(), REMOTE, child.getNode()); return withDerivedProperties( mergingExchange( idAllocator.getNextId(), REMOTE, new SortNode( idAllocator.getNextId(), source, node.getOrderingScheme()), node.getOrderingScheme()), child.getProperties()); } if (!child.getProperties().isSingleNode()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); }
Source:
<code>public List<Client> findAllClients() { <START> return getClients(); <END> }</code><technical_language>exactly. findmeans initialization happen before</technical_language>

Target:
public List<Client> findAllClients() { init(); return getClients(); }
Source:
<code><START> public void broadcastDatastreamUpdate() { <END> _adapter.touchAllInstanceAssignments(); }</code><technical_language>synchornized</technical_language>

Target:
public synchronized void broadcastDatastreamUpdate() { _adapter.touchAllInstanceAssignments(); }
Source:
<code>int getPid(Process process) { if (PID_FIELD != null) { try { return ((Number) PID_FIELD.get(process)).intValue(); } catch (IllegalAccessException e) { <START> throw new IllegalStateException("Cannot get process id. Not a UNIX system?", e); <END> } } else if (PID_METHOD != null) { try { return ((Long) PID_METHOD.invoke(process)).intValue(); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Cannot get process id. Not a UNIX system?", e); } } else { throw new IllegalStateException("Cannot get process id. Not a UNIX system?"); } }</code><technical_language>suggestion throw new IllegalStateException("Cannot get process ID. a UNIX system?", e);</technical_language>

Target:
int getPid(Process process) { if (PID_FIELD != null) { try { return ((Number) PID_FIELD.get(process)).intValue(); } catch (IllegalAccessException e) { throw new IllegalStateException("Cannot get process ID. Not a UNIX system?", e); } } else if (PID_METHOD != null) { try { return ((Long) PID_METHOD.invoke(process)).intValue(); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Cannot get process ID. Not a UNIX system?", e); } } else { throw new IllegalStateException("Cannot get process ID. Not a UNIX system?"); } }
Source:
<code>public Set<DiscoveredResourceDetails> discoverResources( ResourceDiscoveryContext<ApacheVirtualHostServiceComponent> context) throws InvalidPluginConfigurationException, Exception { Set<DiscoveredResourceDetails> discoveredResources = new LinkedHashSet<DiscoveredResourceDetails>(); ApacheDirective vhost = context.getParentResourceComponent().getDirective(); ApacheDirectiveTree tree = new ApacheDirectiveTree(); tree.setRootNode(vhost); final List<ApacheDirective> allDirectories = tree.search("/"+ApacheDirectoryComponent.DIRECTORY_DIRECTIVE); ResourceType resourceType = context.getResourceType(); for (ApacheDirective apacheDirective : allDirectories) { String directoryParam; boolean isRegexp; List<String> params = apacheDirective.getValues(); if (params.size() > 1 && StringUtil.isNotBlank(params.get(1))) { directoryParam = params.get(1); isRegexp = true; } else { directoryParam = params.get(0); isRegexp = false; } Configuration pluginConfiguration = context.getDefaultPluginConfiguration(); pluginConfiguration.put(new PropertySimple(ApacheDirectoryComponent.REGEXP_PROP, isRegexp)); String resourceName = AugeasNodeValueUtil.unescape(directoryParam); int index = 1; for (DiscoveredResourceDetails detail : discoveredResources) { if(detail.getResourceName().endsWith(resourceName)) index++; } StringBuilder resourceKey = new StringBuilder(); <START> resourceKey.append(apacheDirective.getName()).append("|").append(directoryParam).append("|").append(index).append(";"); <END> discoveredResources.add(new DiscoveredResourceDetails(resourceType, resourceKey.toString(), resourceName, null, null, pluginConfiguration, null)); } return discoveredResources; }</code><technical_language>I notice before, changing resource key format requires discovery component implement ResourceUpgradeFacet interface. this facet, "port" directories discovered method (and resource key in format) new format. If do that, end duplicate resources in inventory tree upgrade older version of RHQ</technical_language>

Target:
public Set<DiscoveredResourceDetails> discoverResources( ResourceDiscoveryContext<ApacheVirtualHostServiceComponent> context) throws InvalidPluginConfigurationException, Exception { Set<DiscoveredResourceDetails> discoveredResources = new LinkedHashSet<DiscoveredResourceDetails>(); ApacheDirective vhost = context.getParentResourceComponent().getDirective(); return discoverResources(context, discoveredResources, vhost, ""); }
Source:
<code>public static void setNameService (Map<String, String> domainIpMapProvided) { try { List<sun.net.spi.nameservice.NameService> nameServices = (List<sun.net.spi.nameservice.NameService>) org.apache.commons.lang3.reflect.FieldUtils.readStaticField(InetAddress.class, "nameServices", true); if (domainIpMap != null) { domainIpMap = domainIpMapProvided; } nameServices.add(new CustomDnsResolver()); } catch (IllegalAccessException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>replace log message</technical_language>

Target:
public static void setNameService (Map<String, String> domainIpMapProvided) { try { List<sun.net.spi.nameservice.NameService> nameServices = (List<sun.net.spi.nameservice.NameService>) org.apache.commons.lang3.reflect.FieldUtils.readStaticField(InetAddress.class, "nameServices", true); if (domainIpMap != null) { domainIpMap = domainIpMapProvided; } nameServices.add(new CustomDnsResolver()); } catch (IllegalAccessException e) { logger.error("Error during setNameService: ",e); } }
Source:
<code>public ODataEntry insertEntityToTable(String tableName, ODataEntry entity) { ODataEntry createdEntry = new ODataEntry(); final Document document = new Document(); for (String columnName : entity.getData().keySet()) { String columnValue = entity.getValue(columnName); document.put(columnName, columnValue); entity.addValue(columnName, columnValue); } <START> document.put("_id", new ObjectId()); <END> jongo.getCollection(tableName).insert(document); String documentIdValue = document.get("_id").toString(); entity.addValue(DOCUMENT_ID, documentIdValue); createdEntry.addValue(DOCUMENT_ID, documentIdValue); createdEntry.addValue(ODataConstants.E_TAG, ODataUtils.generateETag(this.configId, tableName, entity)); return createdEntry; }</code><technical_language>constant</technical_language>

Target:
public ODataEntry insertEntityToTable(String tableName, ODataEntry entity) { ODataEntry createdEntry = new ODataEntry(); final Document document = new Document(); for (String columnName : entity.getData().keySet()) { String columnValue = entity.getValue(columnName); document.put(columnName, columnValue); entity.addValue(columnName, columnValue); } ObjectId objectId = new ObjectId(); document.put(DOCUMENT_ID, objectId); jongo.getCollection(tableName).insert(document); String documentIdValue = objectId.toString(); createdEntry.addValue(DOCUMENT_ID, documentIdValue); createdEntry.addValue(ODataConstants.E_TAG, ODataUtils.generateETag(this.configId, tableName, entity)); return createdEntry; }
Source:
<code>private List<Observation> convertObservationMapToList(Map<String, String> observations, DateTime obsDatetime) { List<Observation> observationList = new ArrayList<>(); for (String observationConceptName : observations.keySet()) { if (valueIsNotEmpty(observations, observationConceptName)) { <START> String[] observationsValues = observations.get(observationConceptName).replace(" ", "").split(","); <END> for (String value : observationsValues) { Observation observation = new Observation(); ConceptName conceptName = new ConceptName(observationConceptName); Concept concept = new Concept(conceptName); observation.setConcept(concept); Observation.ObservationValue observationValue = new Observation.ObservationValue(value); observation.setValue(observationValue); observation.setObsDatetime(obsDatetime.toDate()); observationList.add(observation); } } else { LOGGER.warn("Observation value is null or empty for concept: " + observationConceptName + " and will not be created"); } } return observationList; }</code><technical_language>if string space, remove space in string</technical_language>

Target:
private List<Observation> convertObservationMapToList(Map<String, String> observations, DateTime obsDatetime) { List<Observation> observationList = new ArrayList<>(); for (String observationConceptName : observations.keySet()) { if (valueIsNotEmpty(observations, observationConceptName)) { String[] observationValues = observations.get(observationConceptName).replace(", ", ",").split(","); for (String value : observationValues) { Observation observation = new Observation(); ConceptName conceptName = new ConceptName(observationConceptName); Concept concept = new Concept(conceptName); observation.setConcept(concept); Observation.ObservationValue observationValue = new Observation.ObservationValue(value); observation.setValue(observationValue); observation.setObsDatetime(obsDatetime.toDate()); observationList.add(observation); } } else { LOGGER.warn("Observation value is null or empty for concept: " + observationConceptName + " and will not be created"); } } return observationList; }