auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>int deliver(String urlString, JsonStream.Streamable streamable, Map<String, String> headers) throws DeliveryFailureException { checkHasNetworkConnection(); HttpURLConnection conn = null; try { URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setChunkedStreamingMode(0); conn.addRequestProperty("Content-Type", "application/json"); for (Map.Entry<String, String> entry : headers.entrySet()) { conn.addRequestProperty(entry.getKey(), entry.getValue()); } JsonStream stream = null; try { OutputStream out = conn.getOutputStream(); Charset charset = Charset.forName("UTF-8"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, charset)); stream = new JsonStream(writer); streamable.toStream(stream); } finally { IOUtils.closeQuietly(stream); } return conn.getResponseCode(); } catch (IOException exception) { throw new DeliveryFailureException("IOException encountered in request", exception); } catch (Exception exception) { Logger.warn("Unexpected error delivering payload", exception); <START> return HTTP_BAD_REQUEST; <END> } finally { IOUtils.close(conn); } }</code><technical_language>confirm return statement finally block unreachable</technical_language>

Target:
int deliver(String urlString, JsonStream.Streamable streamable, Map<String, String> headers) throws DeliveryFailureException { checkHasNetworkConnection(); HttpURLConnection conn = null; try { URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setChunkedStreamingMode(0); conn.addRequestProperty("Content-Type", "application/json"); for (Map.Entry<String, String> entry : headers.entrySet()) { conn.addRequestProperty(entry.getKey(), entry.getValue()); } JsonStream stream = null; try { OutputStream out = conn.getOutputStream(); Charset charset = Charset.forName("UTF-8"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, charset)); stream = new JsonStream(writer); streamable.toStream(stream); } finally { IOUtils.closeQuietly(stream); } return conn.getResponseCode(); } catch (IOException exception) { throw new DeliveryFailureException("IOException encountered in request", exception); } catch (Exception exception) { Logger.warn("Unexpected error delivering payload", exception); return HTTP_REQUEST_FAILED; } finally { IOUtils.close(conn); } }
Source:
<code>private void cloneMetaData(CharSequence tableName, CharSequence root, CharSequence backupRoot, int mkDirMode, TableReader reader) { path.of(backupRoot).concat(tableName).put(Files.SEPARATOR).$(); if (ff.exists(path)) { throw CairoException.instance(0).put("Backup dir for table \"").put(tableName).put("\" already exists [dir=").put(path).put(']'); } if (ff.mkdirs(path, mkDirMode) != 0) { throw CairoException.instance(ff.errno()).put("Could not create [dir=").put(path).put(']'); } <START> TableReaderMetadata sourceMetaData = (TableReaderMetadata) reader.getMetadata(); <END> int rootLen = path.length(); try { mem.of(ff, path.trimTo(rootLen).concat(TableUtils.META_FILE_NAME).$(), ff.getPageSize()); sourceMetaData.cloneTo(mem); path.trimTo(rootLen).$(); int symbolMapCount = 0; for (int i = 0; i < sourceMetaData.getColumnCount(); i++) { if (sourceMetaData.getColumnType(i) == ColumnType.SYMBOL) { SymbolMapReader mapReader = reader.getSymbolMapReader(i); SymbolMapWriter.createSymbolMapFiles(ff, mem, path, sourceMetaData.getColumnName(i), mapReader.getSymbolCapacity(), mapReader.isCached()); symbolMapCount++; } } mem.of(ff, path.trimTo(rootLen).concat(TableUtils.TXN_FILE_NAME).$(), ff.getPageSize()); TableUtils.resetTxn(mem, symbolMapCount, 0L, TableUtils.INITIAL_TXN); } finally { mem.close(); } }</code><technical_language>formatting</technical_language>

Target:
private void cloneMetaData(CharSequence tableName, CharSequence root, CharSequence backupRoot, int mkDirMode, TableReader reader) { path.of(backupRoot).concat(tableName).put(Files.SEPARATOR).$(); if (ff.exists(path)) { throw CairoException.instance(0).put("Backup dir for table \"").put(tableName).put("\" already exists [dir=").put(path).put(']'); } if (ff.mkdirs(path, mkDirMode) != 0) { throw CairoException.instance(ff.errno()).put("Could not create [dir=").put(path).put(']'); } TableReaderMetadata sourceMetaData = (TableReaderMetadata) reader.getMetadata(); int rootLen = path.length(); try { mem.of(ff, path.trimTo(rootLen).concat(TableUtils.META_FILE_NAME).$(), ff.getPageSize()); sourceMetaData.cloneTo(mem); path.trimTo(rootLen).$(); int symbolMapCount = 0; for (int i = 0, sz = sourceMetaData.getColumnCount(); i < sz; i++) { if (sourceMetaData.getColumnType(i) == ColumnType.SYMBOL) { SymbolMapReader mapReader = reader.getSymbolMapReader(i); SymbolMapWriter.createSymbolMapFiles(ff, mem, path, sourceMetaData.getColumnName(i), mapReader.getSymbolCapacity(), mapReader.isCached()); symbolMapCount++; } } mem.of(ff, path.trimTo(rootLen).concat(TableUtils.TXN_FILE_NAME).$(), ff.getPageSize()); TableUtils.resetTxn(mem, symbolMapCount, 0L, TableUtils.INITIAL_TXN); } finally { mem.close(); } }
Source:
<code>public void close() throws IOException { if (!closed.compareAndSet(false, true)) { log.warn(new ISE("Already Closed!"), "Already closed"); return; } <START> if (objects.size() < objectsCacheSize && !objects.offer(object)) { <END> log.warn(new ISE("Queue offer failed"), "Could not offer object [%s] back into the queue", object); } }</code><technical_language>If size is big is reasonable put a debug log</technical_language>

Target:
public void close() throws IOException { if (!closed.compareAndSet(false, true)) { log.warn(new ISE("Already Closed!"), "Already closed"); return; } if (objects.size() < objectsCacheMaxCount) { if (!objects.offer(object)) { log.warn(new ISE("Queue offer failed"), "Could not offer object [%s] back into the queue", object); } } else { log.debug("cache num entries is exceeding max limit [%s]", objectsCacheMaxCount); } }
Source:
<code>void addPartitionToFaultZone(String faultZoneId, String resourceName, String partition) { if (!_assignmentForFaultZoneMap.containsKey(faultZoneId)) { _assignmentForFaultZoneMap.put(faultZoneId, new HashMap<>()); } if (!_assignmentForFaultZoneMap.get(faultZoneId).containsKey(resourceName)) { _assignmentForFaultZoneMap.get(faultZoneId).put(resourceName, new HashSet<>()); } <START> _assignmentForFaultZoneMap.get(faultZoneId).get(resourceName).add(partition); <END> }</code><technical_language>For this code block, cleaner if computeIfAbsent()? java _assignmentForFaultZoneMap.computeIfAbsent(faultZoneId, -> new HashMap<>()) .computeIfAbsent(resourceName, -> new HashSet<>()) .add(partition);</technical_language>

Target:
void addPartitionToFaultZone(String faultZoneId, String resourceName, String partition) { if (!_assignmentForFaultZoneMap.computeIfAbsent(faultZoneId, k -> new HashMap<>()) .computeIfAbsent(resourceName, k -> new HashSet<>()).add(partition)) { throw new HelixException(String .format("Resource %s already has a replica from partition %s in fault zone %s", resourceName, partition, faultZoneId)); } }
Source:
<code>protected List<RowMap> getRowsForSQLTransactional(final String[] input) throws Exception { MaxwellTestSupportCallback callback = getMaxwellTestSupportCallback(input); return MaxwellTestSupport.getRowsWithReplicator(server, null, callback, null); <START> } <END></code><technical_language>^ this delegate overload (with null, null)</technical_language>

Target:
protected List<RowMap> getRowsForSQLTransactional(final String[] input) throws Exception { return getRowsForSQLTransactional(input, null, null); }
Source:
<code><START> public static ImmutableSortedSet<String> hosts(int...ports) { <END> if (ports.length == 0) { return ImmutableSortedSet.of( HostAndPort.fromParts("", DEFAULT_INTERNAL_PORT).toString()); } ImmutableSortedSet.Builder<String> sbld = ImmutableSortedSet.naturalOrder(); for (int p: ports) { sbld.add(HostAndPort.fromParts("", p).toString()); } return sbld.build(); }</code><technical_language>this for passing IP/hostname</technical_language>

Target:
public static ImmutableSortedSet<String> hosts(int...ports) { if (ports.length == 0) { return ImmutableSortedSet.of( HostAndPort.fromParts("", Constants.DEFAULT_INTERNAL_PORT).toString()); } ImmutableSortedSet.Builder<String> sbld = ImmutableSortedSet.naturalOrder(); for (int p: ports) { sbld.add(HostAndPort.fromParts("", p).toString()); } return sbld.build(); }
Source:
<code>public Double getAggregate() { if (count == 0) { <START> return null; <END> } return stddev; }</code><technical_language>This dangerous, interface method return Optional instead</technical_language>

Target:
public Double getAggregate() { return stats.stddev(); }
Source:
<code><START> public void :testSequentialIntegerDataSequence() throws Exception { <END> XMLConfigParser parser = new XMLConfigParser(matcherScenario); DataModel model = parser.getDataModels().get(0); WriteWorkload loader = new WriteWorkload(parser); RulesApplier rulesApplier = loader.getRulesApplier(); Column targetColumn = null; for (Column column : model.getDataMappingColumns()) { DataSequence sequence = column.getDataSequence(); if (DataTypeMapping.INTEGER.equals(column.getType()) && sequence == DataSequence.SEQUENTIAL) { targetColumn = column; break; } } assertNotNull("Could not find a DataSequence.SEQENTIAL rule.", targetColumn); assertMultiThreadedIncrementValue(targetColumn, rulesApplier); }</code><technical_language>extra ":" , this compile</technical_language>

Target:
public void testSequentialIntegerDataSequence() throws Exception { XMLConfigParser parser = new XMLConfigParser(matcherScenario); DataModel model = parser.getDataModels().get(0); WriteWorkload loader = new WriteWorkload(parser); RulesApplier rulesApplier = loader.getRulesApplier(); Column targetColumn = null; for (Column column : model.getDataMappingColumns()) { DataSequence sequence = column.getDataSequence(); if (DataTypeMapping.INTEGER.equals(column.getType()) && sequence == DataSequence.SEQUENTIAL) { targetColumn = column; break; } } assertNotNull("Could not find a DataSequence.SEQENTIAL rule.", targetColumn); assertMultiThreadedIncrementValue(targetColumn, rulesApplier); }
Source:
<code>public BufferedReader getInput() throws IOException { <START> StringBuilder buffer = new StringBuilder(); <END> for (String current : inputList) { buffer.append(current).append('\n'); } BufferedReader br = new BufferedReader(new StringReader(buffer.toString())); return br; }</code><technical_language>a joiner: <LINK_0>, join this iterable of string</technical_language>

Target:
public BufferedReader getInput() throws IOException { return new BufferedReader(new StringReader(testString)); }
Source:
<code>public Response getWorkflowLog(String workflowId, ConsonanceUser user) throws NotFoundException { Ga4ghWesWorkflowLog log = new Ga4ghWesWorkflowLog(); log.setWorkflowId(workflowId); final String[] jobUuid = {"-1"}; List<Job> allJobs = orderResource.listWorkflowRuns(user); allJobs.stream().filter((Job t) -> String.valueOf(t.getJobId()).equals(workflowId)).forEach(s -> jobUuid[0] = s.getUuid()); Job parseJob = orderResource.getWorkflowRun(user, jobUuid[0]); Ga4ghWesWorkflowRequest request = new Ga4ghWesWorkflowRequest(); request.setWorkflowDescriptor(parseJob.getContainerImageDescriptor()); request.setWorkflowParams(parseJob.getContainerRuntimeDescriptor()); request.setWorkflowType(parseJob.getContainerImageDescriptorType()); request.setWorkflowTypeVersion("1.0"); log.setRequest(request); JobState workflowState = parseJob.getState(); log.setState(mapState(workflowState)); Ga4ghWesLog workflowLog = new Ga4ghWesLog(); workflowLog.setName("CWL|WDL Job"); workflowLog.addCmdItem("run workflow"); workflowLog.setStartTime(String.valueOf(parseJob.getCreateTimestamp())); workflowLog.setEndTime(String.valueOf(parseJob.getUpdateTimestamp())); workflowLog.setStdout(parseJob.getStdout()); workflowLog.setStderr(parseJob.getStderr()); <START> workflowLog.setExitCode(0); <END> log.addTaskLogsItem(workflowLog); Ga4ghWesParameter outputParameter = new Ga4ghWesParameter(); log.addOutputsItem(outputParameter); return Response.ok().entity(log).build(); }</code><technical_language>important exit code is defined underlying job, I guess try manage job state, setting 0 right. I need a of naming log, timestamp of request? I leave CmdItem ExitCode unset a compelling argument to</technical_language>

Target:
public Response getWorkflowLog(String workflowId, ConsonanceUser user) throws NotFoundException { Ga4ghWesWorkflowLog log = new Ga4ghWesWorkflowLog(); log.setWorkflowId(workflowId); final String[] jobUuid = {"-1"}; List<Job> allJobs = orderResource.listWorkflowRuns(user); allJobs.stream().filter((Job t) -> String.valueOf(t.getJobId()).equals(workflowId)).forEach(s -> jobUuid[0] = s.getUuid()); Job parseJob = orderResource.getWorkflowRun(user, jobUuid[0]); Ga4ghWesWorkflowRequest request = new Ga4ghWesWorkflowRequest(); request.setWorkflowDescriptor(parseJob.getContainerImageDescriptor()); request.setWorkflowParams(parseJob.getContainerRuntimeDescriptor()); request.setWorkflowType(parseJob.getContainerImageDescriptorType()); request.setWorkflowTypeVersion("1.0"); log.setRequest(request); JobState workflowState = parseJob.getState(); log.setState(mapState(workflowState)); Ga4ghWesLog workflowLog = new Ga4ghWesLog(); workflowLog.setName(parseJob.getContainerImageDescriptorType()); workflowLog.setStartTime(String.valueOf(parseJob.getCreateTimestamp())); workflowLog.setEndTime(String.valueOf(parseJob.getUpdateTimestamp())); workflowLog.setStdout(parseJob.getStdout()); workflowLog.setStderr(parseJob.getStderr()); log.addTaskLogsItem(workflowLog); Ga4ghWesParameter outputParameter = new Ga4ghWesParameter(); log.addOutputsItem(outputParameter); return Response.ok().entity(log).build(); }
Source:
<code>private void assertFilesAreOpen() { <START> Set<TextEditor> textEditors = getOpenEditorsByType(TextEditor.class); <END> assertEquals(2, textEditors.size()); Set<String> editorTitles = FluentIterable.from(textEditors).transform(new Function<TextEditor, String>() { @Override public String apply(TextEditor editor) { return editor.getTitle(); } }).toSet(); assertTrue(editorTitles.contains(fileA.getName())); assertTrue(editorTitles.contains(fileB.getName())); }</code><technical_language>replace 3 assertions assertEquals(ImmutableSet.of(fileA.getName(), fileB.getName()), editorTitles)</technical_language>

Target:
private void assertFilesAreOpen() { Set<String> editorTitles = getOpenEditorsByType(TextEditor.class, new Function<TextEditor, String>() { @Override public String apply(TextEditor editor) { return editor.getTitle(); } }); assertEquals(ImmutableSet.of(fileA.getName(), fileB.getName()), editorTitles); }
Source:
<code>public void testBool() { final Arbitrary<Boolean> arbBooleanR = arbitrary(arbBoolean.gen); final Property p = property(arbBooleanR, arbBooleanR, (m1, m2) -> bool(m1.equals(m2)) <START> .implies(new BoolTestClass(m1).getBoolean() == new BoolTestClass(m2).getBoolean())); <END> PropertyAssert.assertResult(p); }</code><technical_language>is purpose of wrapping Boolean in a class boolean out, a direct m1 == m2 expression</technical_language>

Target:
public void testBool() { final Arbitrary<Boolean> arbBooleanR = arbitrary(arbBoolean.gen); final Property p = property(arbBooleanR, arbBooleanR, (m1, m2) -> bool(m1.equals(m2)) .implies(m1 == m2)); PropertyAssert.assertResult(p); }
Source:
<code>public void storeSettings() { prefs.put(JabRefPreferences.EMAIL_SUBJECT, emailSubject.getText()); prefs.putBoolean(JabRefPreferences.OPEN_FOLDERS_OF_ATTACHED_FILES, openFoldersOfAttachedFiles.isSelected()); <START> if (pushToApplicationComboBox.getValue().getApplicationName() != JabRefPreferences.PUSH_TO_APPLICATION) { <END> prefs.put(JabRefPreferences.PUSH_TO_APPLICATION, pushToApplicationComboBox.getValue().getApplicationName()); frame.getPushToApplicationsManager().updateApplicationAction(); } prefs.put(JabRefPreferences.CITE_COMMAND, citeCommand.getText()); prefs.putBoolean(JabRefPreferences.USE_DEFAULT_CONSOLE_APPLICATION, defaultConsole.isSelected()); prefs.put(JabRefPreferences.CONSOLE_COMMAND, consoleCommand.getText()); prefs.put(JabRefPreferences.ADOBE_ACROBAT_COMMAND, adobeAcrobatReaderPath.getText()); prefs.putBoolean(JabRefPreferences.USE_DEFAULT_FILE_BROWSER_APPLICATION, defaultFileBrowser.isSelected()); if (StringUtil.isNotBlank(fileBrowserCommand.getText())) { prefs.put(JabRefPreferences.FILE_BROWSER_COMMAND, fileBrowserCommand.getText()); } else { prefs.putBoolean(JabRefPreferences.USE_DEFAULT_FILE_BROWSER_APPLICATION, true); } if (OS.WINDOWS) { prefs.put(JabRefPreferences.SUMATRA_PDF_COMMAND, sumatraReaderPath.getText()); } readerSelected(); }</code><technical_language>Similarily, I extract part of this code setActivePushToApplication(PushToApplication) method in JabRefPreferences</technical_language>

Target:
public void storeSettings() { prefs.put(JabRefPreferences.EMAIL_SUBJECT, emailSubject.getText()); prefs.putBoolean(JabRefPreferences.OPEN_FOLDERS_OF_ATTACHED_FILES, openFoldersOfAttachedFiles.isSelected()); prefs.setActivePushToApplication(pushToApplicationComboBox.getValue(), frame.getPushToApplicationsManager()); prefs.put(JabRefPreferences.CITE_COMMAND, citeCommand.getText()); prefs.putBoolean(JabRefPreferences.USE_DEFAULT_CONSOLE_APPLICATION, defaultConsole.isSelected()); prefs.put(JabRefPreferences.CONSOLE_COMMAND, consoleCommand.getText()); prefs.put(JabRefPreferences.ADOBE_ACROBAT_COMMAND, adobeAcrobatReaderPath.getText()); prefs.putBoolean(JabRefPreferences.USE_DEFAULT_FILE_BROWSER_APPLICATION, defaultFileBrowser.isSelected()); if (StringUtil.isNotBlank(fileBrowserCommand.getText())) { prefs.put(JabRefPreferences.FILE_BROWSER_COMMAND, fileBrowserCommand.getText()); } else { prefs.putBoolean(JabRefPreferences.USE_DEFAULT_FILE_BROWSER_APPLICATION, true); } if (OS.WINDOWS) { prefs.put(JabRefPreferences.SUMATRA_PDF_COMMAND, sumatraReaderPath.getText()); } readerSelected(); }
Source:
<code>private int createHashCode() { int result = interpolatedMessage != null ? interpolatedMessage.hashCode() : 0; result = 31 * result + ( propertyPath != null ? propertyPath.hashCode() : 0 ); result = 31 * result + ( constraintDescriptor != null ? constraintDescriptor.hashCode() : 0 ); result = 31 * result + ( messageTemplate != null ? messageTemplate.hashCode() : 0 ); <START> result = 31 * result + ( rootBeanClass != null ? rootBeanClass.hashCode() : 0 ); <END> result = 31 * result + ( elementType != null ? elementType.hashCode() : 0 ); return result; }</code><technical_language>try benchmark it? previous experiments, I System.identityHashCode() in profiling more of artifact</technical_language>

Target:
private int createHashCode() { int result = interpolatedMessage != null ? interpolatedMessage.hashCode() : 0; result = 31 * result + ( propertyPath != null ? propertyPath.hashCode() : 0 ); result = 31 * result + System.identityHashCode( rootBean ); result = 31 * result + System.identityHashCode( leafBeanInstance ); result = 31 * result + System.identityHashCode( value ); result = 31 * result + ( constraintDescriptor != null ? constraintDescriptor.hashCode() : 0 ); result = 31 * result + ( messageTemplate != null ? messageTemplate.hashCode() : 0 ); result = 31 * result + ( elementType != null ? elementType.hashCode() : 0 ); return result; }
Source:
<code>public static byte getFlagByPartId(final int partId) { <START> return partId == PageIdAllocator.INDEX_PARTITION ? PageStore.TYPE_IDX : PageStore.TYPE_DATA; <END> }</code><technical_language>do return page store type method return flag</technical_language>

Target:
public static byte getFlagByPartId(final int partId) { return partId == PageIdAllocator.INDEX_PARTITION ? PageIdAllocator.FLAG_IDX : PageIdAllocator.FLAG_DATA; }
Source:
<code>public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { <START> for (Pod pod : k8sEnv.getPods().values()) { <END> pod.getSpec() .getContainers() .forEach( container -> proxyEnvVars.forEach((k, v) -> container.getEnv().add(new EnvVar(k, v, null)))); } }</code><technical_language>sense check if proxyEnvVars is empty foreaching pods containers</technical_language>

Target:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { if (!proxyEnvVars.isEmpty()) { for (Pod pod : k8sEnv.getPods().values()) { pod.getSpec() .getContainers() .forEach( container -> proxyEnvVars.forEach((k, v) -> container.getEnv().add(new EnvVar(k, v, null)))); } } }
Source:
<code>private void sleep() { try { <START> Thread.sleep(30_000); <END> } catch (final InterruptedException ex) { } }</code><technical_language>30_000 sounds long here. if shutdown method fail? 30 seconds fail this test? this combination: Thread.sleep(5000) islessThan(1000). If JVM interrupt sleep thread 1s, seriously wrong</technical_language>

Target:
private void sleep() { try { Thread.sleep(5000); } catch (final InterruptedException ex) { this.isTestThreadInterrupted = true; } }
Source:
<code>public void check() { for (User user : iterateLazily((maxItems, skipCount) -> userManager.getAll(maxItems, skipCount))) { try { String owner = user.getId(); Map<String, String> preferences = preferenceManager.find(owner); String lastTimeAccess = preferences.get(LAST_ACTIVITY_TIME); String namespace = preferences.get(LAST_ACTIVE_INFRASTRUCTURE_NAMESPACE); if (isNullOrEmpty(namespace) || isNullOrEmpty(lastTimeAccess) || isAnyRuntimeInProgress(owner)) { continue; } long lastTimeAccessSec = parseLong(lastTimeAccess); <START> long epochSec = clock.instant().getEpochSecond(); <END> if (epochSec - lastTimeAccessSec >= shutdownTimeoutSec) { PodResource<Pod, DoneablePod> podDoneablePodPodResource = kubernetesClientFactory .create() .pods() .inNamespace(namespace) .withName(ASYNC_STORAGE); if (podDoneablePodPodResource.get() != null) { podDoneablePodPodResource.delete(); } } } catch (InfrastructureException | ServerException e) { LOG.error(e.getMessage(), e); } } }</code><technical_language>I shutdownTimeoutSec-> shutdownTimeoutMsec instead of clock.instant().getEpochSecond() System.currentTimeMillis()</technical_language>

Target:
public void check() { if (isAsyncStoragePodCanBeRun && shutdownTimeoutSec > 0) { for (User user : iterateLazily((maxItems, skipCount) -> userManager.getAll(maxItems, skipCount))) { try { String owner = user.getId(); Map<String, String> preferences = preferenceManager.find(owner); String lastTimeAccess = preferences.get(LAST_ACTIVITY_TIME); String namespace = preferences.get(LAST_ACTIVE_INFRASTRUCTURE_NAMESPACE); if (isNullOrEmpty(namespace) || isNullOrEmpty(lastTimeAccess) || !runtimes.getInProgress(owner).isEmpty()) { continue; } long lastTimeAccessSec = parseLong(lastTimeAccess); Instant expectedShutdownAfter = ofEpochSecond(lastTimeAccessSec).plusSeconds(shutdownTimeoutSec); if (now().isAfter(expectedShutdownAfter)) { PodResource<Pod, DoneablePod> doneablePodResource = kubernetesClientFactory .create() .pods() .inNamespace(namespace) .withName(ASYNC_STORAGE); if (doneablePodResource.get() != null) { doneablePodResource.delete(); } } } catch (InfrastructureException | ServerException e) { LOG.error(e.getMessage(), e); } } } }
Source:
<code>public static int compare(Float number, long value, OptionalInt treatNanAs) { OptionalInt infinity = InfinityNumberComparatorHelper.infinityCheck( number, treatNanAs ); if ( infinity.isPresent() ) { return infinity.getAsInt(); } <START> return Double.compare( number, value ); <END> }</code><technical_language>Is a reason Float#compare() here</technical_language>

Target:
public static int compare(Float number, long value, OptionalInt treatNanAs) { OptionalInt infinity = InfinityNumberComparatorHelper.infinityCheck( number, treatNanAs ); if ( infinity.isPresent() ) { return infinity.getAsInt(); } return Float.compare( number, value ); }
Source:
<code>public Navigate toPage(String pageName) { String host = UrlBuilder.getHostForWiki(); String cacheBuster = pageName.equals("") || pageName.equals("/") ? "" : "?cb=" + DateTime.now().getMillis(); <START> String abGroup = pageName.equals("") || pageName.equals("/") ? "" : defaultTestingGroup; <END> driver.get("http://" + host + pageName + cacheBuster + abGroup); return this; }</code><technical_language>if navigate page / get <LINK_0> add parameter end of line</technical_language>

Target:
public Navigate toPage(String pageName) { String host = UrlBuilder.getHostForWiki(); String cacheBuster = pageName.equals("") || pageName.equals("/") ? "" : "?cb=" + DateTime.now().getMillis() + defaultTestingGroup; driver.get("http://" + host + pageName + cacheBuster); return this; }
Source:
<code>public Resource createResource(PerunSession sess, Resource resource, Vo vo, Facility facility) throws InternalErrorException, FacilityNotExistsException, ResourceExistsException { try{ getResourcesManagerImpl().getResourceByName(sess, vo, facility, resource.getName()); throw new ResourceExistsException("Resource with name \"" + resource.getName() + "\" already exists in " + "facility " + facility + " in VO " + vo + "."); } catch (ResourceNotExistsException e) { <START> resource = getResourcesManagerImpl().createResource(sess, vo, resource, facility); <END> getPerunBl().getAuditer().log(sess, "{} created.", resource); } return resource; }</code><technical_language>"resourceExists" method works in checkResourceExists, returns boolean instead of raising exception</technical_language>

Target:
public Resource createResource(PerunSession sess, Resource resource, Vo vo, Facility facility) throws InternalErrorException, FacilityNotExistsException, ResourceExistsException { try{ Resource existingResource = getResourcesManagerImpl().getResourceByName(sess, vo, facility, resource.getName()); throw new ResourceExistsException(existingResource); } catch (ResourceNotExistsException e) { resource = getResourcesManagerImpl().createResource(sess, vo, resource, facility); getPerunBl().getAuditer().log(sess, "{} created.", resource); } return resource; }
Source:
<code>public Connection createConnection(RuntimeContainer container) throws IOException { Connection conn = null; SnowflakeConnectionProperties connectionProperties = getConnectionProperties(); String refComponentId = connectionProperties.getReferencedComponentId(); if (refComponentId != null) { if (container != null) { conn = (Connection) container.getComponentData(refComponentId, KEY_CONNECTION); try { if (conn != null && !conn.isClosed()) { return conn; } } catch (SQLException ex) { throw new IOException(ex); } throw new IOException(I18N_MESSAGES.getMessage("error.refComponentNotConnected", refComponentId)); } connectionProperties = connectionProperties.getReferencedConnectionProperties(); if (connectionProperties == null) { throw new IOException(I18N_MESSAGES.getMessage("error.refComponentWithoutProperties", refComponentId)); } } if (container != null) { <START> conn = (Connection) container.getComponentData(container.getCurrentComponentId(), KEY_CONNECTION); <END> try { if (conn != null && !conn.isClosed()) { return conn; } } catch (SQLException ex) { throw new IOException(ex); } connectionProperties.talendProductVersion = (String) container.getGlobalData(KEY_TALEND_PRODUCT_VERSION); } conn = DriverManagerUtils.getConnection(connectionProperties); try { conn.setAutoCommit(connectionProperties.autoCommit.getValue()); } catch (SQLException e) { throw new IOException(e); } if (container != null) { container.setComponentData(container.getCurrentComponentId(), KEY_CONNECTION, conn); container.setComponentData(container.getCurrentComponentId(), KEY_CONNECTION_PROPERTIES, connectionProperties); } return conn; }</code><technical_language>a duplicate of code, extract separate method componentId a parameter</technical_language>

Target:
public Connection createConnection(RuntimeContainer container) throws IOException { Connection conn = null; SnowflakeConnectionProperties connectionProperties = getConnectionProperties(); String refComponentId = connectionProperties.getReferencedComponentId(); if (refComponentId != null) { if (container != null) { conn = getConnection(container, refComponentId); if (isConnectionValid(conn)) { return conn; } throw new IOException(I18N_MESSAGES.getMessage("error.refComponentNotConnected", refComponentId)); } connectionProperties = connectionProperties.getReferencedConnectionProperties(); if (connectionProperties == null) { throw new IOException(I18N_MESSAGES.getMessage("error.refComponentWithoutProperties", refComponentId)); } } if (container != null) { conn = getConnection(container, container.getCurrentComponentId()); if (isConnectionValid(conn)) { return conn; } connectionProperties.talendProductVersion = (String) container.getGlobalData(KEY_TALEND_PRODUCT_VERSION); } conn = DriverManagerUtils.getConnection(connectionProperties); try { conn.setAutoCommit(connectionProperties.autoCommit.getValue()); } catch (SQLException e) { throw new IOException(e); } if (container != null) { container.setComponentData(container.getCurrentComponentId(), KEY_CONNECTION, conn); container.setComponentData(container.getCurrentComponentId(), KEY_CONNECTION_PROPERTIES, connectionProperties); } return conn; }
Source:
<code>public List<String> emptyCloudBlobDirectory(final String path) throws StorageException, URISyntaxException { List<String> deletedFiles = new ArrayList<>(); CloudBlobDirectory cloudBlobDirectory = cloudBlobContainer.getDirectoryReference(path); for (ListBlobItem blobItem : cloudBlobDirectory.listBlobs()) { <START> if (blobItem instanceof CloudBlob) { <END> CloudBlob cloudBlob = (CloudBlob) blobItem; log.info("Removing file[%s] from Azure.", cloudBlob.getName()); if (cloudBlob.deleteIfExists()) { deletedFiles.add(cloudBlob.getName()); } } } return deletedFiles; }</code><technical_language>if is not? warn throw exception</technical_language>

Target:
public List<String> emptyCloudBlobDirectory(final String path) throws StorageException, URISyntaxException { List<String> deletedFiles = new ArrayList<>(); for (ListBlobItem blobItem : cloudBlobContainer.listBlobs(path, true, null, null, null)) { CloudBlob cloudBlob = (CloudBlob) blobItem; log.info("Removing file[%s] from Azure.", cloudBlob.getName()); if (cloudBlob.deleteIfExists()) { deletedFiles.add(cloudBlob.getName()); } } if (deletedFiles.isEmpty()) { log.warn("No files were deleted on the following Azure path: [%s]", path); } return deletedFiles; }
Source:
<code>public Boolean visitScope(Scope scope) { final Provider<ScopeCleanupMarker> scopedMarkerProvider; <START> if (scope.equals(Scopes.SINGLETON) || scope.equals(LazySingletonScope.get()) || scope.equals(FineGrainedLazySingletonScope.get())) { <END> scopedMarkerProvider = Providers.of(singletonMarker); } else { scopedMarkerProvider = scope.scope(MARKER_KEY, markerProvider); } ScopeCleanupMarker marker = scopedMarkerProvider.get(); UUID markerKey = marker.getId(); synchronized (markerKey) { ManagedInstanceAction instanceAction = new ManagedInstanceAction(injectee, lifecycleActions); if (scopedCleanupActions.containsKey(markerKey)) { scopedCleanupActions.get(markerKey).add(scopedMarkerProvider, instanceAction); } else { scopedCleanupActions.put(markerKey, new ScopeCleanupAction(markerKey, scopedMarkerProvider, marker, markerReferenceQueue, instanceAction)); } } return true; }</code><technical_language>ideal if scopes programmatically instead of hardcoded here</technical_language>

Target:
public Boolean visitScope(Scope scope) { final Provider<ScopeCleanupMarker> scopedMarkerProvider; if (scope.equals(Scopes.SINGLETON) || (scope instanceof AbstractScope && ((AbstractScope)scope).isSingletonScope())) { scopedMarkerProvider = Providers.of(singletonMarker); } else { scopedMarkerProvider = scope.scope(MARKER_KEY, markerProvider); } ScopeCleanupMarker marker = scopedMarkerProvider.get(); UUID markerKey = marker.getId(); synchronized (markerKey) { ManagedInstanceAction instanceAction = new ManagedInstanceAction(injectee, lifecycleActions); if (scopedCleanupActions.containsKey(markerKey)) { scopedCleanupActions.get(markerKey).add(scopedMarkerProvider, instanceAction); } else { scopedCleanupActions.put(markerKey, new ScopeCleanupAction(markerKey, scopedMarkerProvider, marker, markerReferenceQueue, instanceAction)); } } return true; }
Source:
<code>public FastIgnoreRule(String pattern) { if (pattern == null) <START> throw new IllegalArgumentException("Pattern must be not null!"); END> if (pattern.length() == 0) { dirOnly = false; inverse = false; this.matcher = NO_MATCH; return; } inverse = pattern.charAt(0) == '!'; if (inverse) { pattern = pattern.substring(1); if (pattern.length() == 0) { dirOnly = false; this.matcher = NO_MATCH; return; } } if (pattern.charAt(0) == '#') { this.matcher = NO_MATCH; dirOnly = false; } else { dirOnly = pattern.charAt(pattern.length() - 1) == PATH_SEPARATOR; if (dirOnly) { pattern = stripTrailing(pattern, PATH_SEPARATOR); if (pattern.length() == 0) { this.matcher = NO_MATCH; return; } } IMatcher m; try { m = PathMatcher.createPathMatcher(pattern, Character.valueOf(PATH_SEPARATOR), dirOnly); } catch (InvalidPatternException e) { m = NO_MATCH; } this.matcher = m; } }</code><technical_language>s/must null/must null/</technical_language>

Target:
public FastIgnoreRule(String pattern) { if (pattern == null) throw new IllegalArgumentException("Pattern must not be null!"); if (pattern.length() == 0) { dirOnly = false; inverse = false; this.matcher = NO_MATCH; return; } inverse = pattern.charAt(0) == '!'; if (inverse) { pattern = pattern.substring(1); if (pattern.length() == 0) { dirOnly = false; this.matcher = NO_MATCH; return; } } if (pattern.charAt(0) == '#') { this.matcher = NO_MATCH; dirOnly = false; } else { dirOnly = pattern.charAt(pattern.length() - 1) == PATH_SEPARATOR; if (dirOnly) { pattern = stripTrailing(pattern, PATH_SEPARATOR); if (pattern.length() == 0) { this.matcher = NO_MATCH; return; } } IMatcher m; try { m = PathMatcher.createPathMatcher(pattern, Character.valueOf(PATH_SEPARATOR), dirOnly); } catch (InvalidPatternException e) { m = NO_MATCH; } this.matcher = m; } }
Source:
<code>public void selectProviderById(Guid providerId) { if (getNetworkProviders().getItems() != null) { Provider provider = getNetworkProviders().getItems().stream() .filter(candidate -> Objects.equals(candidate.getId(), providerId)) <START> .findFirst().orElse(null); <END> getNetworkProviders().setSelectedItem(provider); } }</code><technical_language>this 'NoExternaNetworkProvider' obj</technical_language>

Target:
public void selectProviderById(Guid providerId) { if (getNetworkProviders().getItems() != null) { Provider provider = getNetworkProviders().getItems().stream() .filter(candidate -> Objects.equals(candidate.getId(), providerId)) .findFirst().orElse(getNoExternalNetworkProvider()); getNetworkProviders().setSelectedItem(provider); } }
Source:
<code>public void registerSonarQubeVersion_publishes_version_on_first_call() { ClusterProperties clusterProperties = new ClusterProperties(newClusterSettings()); try (HazelcastCluster hzCluster = HazelcastCluster.builder(clusterProperties).build()) { hzCluster.registerSonarQubeVersion("1.0.0.0"); HazelcastInstance hzInstance = createHazelcastClient(hzCluster); assertThat(hzInstance.getAtomicReference(SONARQUBE_VERSION).get()) .isNotNull() .isInstanceOf(String.class) <START> .isEqualTo("1.0.0.0"); <END> } }</code><technical_language>need for isNotNull isInstanceOf(String.class). implicit .isEqualTo("1.0.0.0")</technical_language>

Target:
public void registerSonarQubeVersion_publishes_version_on_first_call() { ClusterProperties clusterProperties = new ClusterProperties(newClusterSettings()); try (HazelcastCluster hzCluster = HazelcastCluster.create(clusterProperties)) { hzCluster.registerSonarQubeVersion("1.0.0.0"); HazelcastInstance hzInstance = createHazelcastClient(hzCluster); assertThat(hzInstance.getAtomicReference(SONARQUBE_VERSION).get()).isEqualTo("1.0.0.0"); } }
Source:
<code>public synchronized void seek(long pos) throws IOException { checkNotClosed(); if (pos < 0 || pos >= length) { if (pos == 0) { return; } throw new EOFException( "EOF encountered at pos: " + pos + " for key: " + key); } Preconditions.assertTrue(blockIndex >= 0); if (blockIndex >= blockStreams.size()) { blockIndex = Arrays.binarySearch(blockOffsets, pos); } else if (pos < blockOffsets[blockIndex]) { blockIndex = Arrays.binarySearch(blockOffsets, 0, blockIndex, pos); } else if (pos >= blockOffsets[blockIndex] + blockStreams .get(blockIndex).getLength()) { blockIndex = Arrays <START> .binarySearch(blockOffsets, blockIndex + 1, <END> blockStreams.size(), pos); } if (blockIndex < 0) { blockIndex = -blockIndex - 2; } blockStreams.get(blockIndexOfPrevPosition).resetPosition(); blockStreams.get(blockIndex).seek(pos - blockOffsets[blockIndex]); blockIndexOfPrevPosition = blockIndex; }</code><technical_language>is this condition added</technical_language>

Target:
public synchronized void seek(long pos) throws IOException { checkOpen(); if (pos < 0 || pos >= length) { if (pos == 0) { return; } throw new EOFException( "EOF encountered at pos: " + pos + " for key: " + key); } if (blockIndex >= blockStreams.size()) { blockIndex = Arrays.binarySearch(blockOffsets, pos); } else if (pos < blockOffsets[blockIndex]) { blockIndex = Arrays.binarySearch(blockOffsets, 0, blockIndex, pos); } else if (pos >= blockOffsets[blockIndex] + blockStreams .get(blockIndex).getLength()) { blockIndex = Arrays .binarySearch(blockOffsets, blockIndex + 1, blockStreams.size(), pos); } if (blockIndex < 0) { blockIndex = -blockIndex - 2; } blockStreams.get(blockIndexOfPrevPosition).resetPosition(); blockStreams.get(blockIndex).seek(pos - blockOffsets[blockIndex]); blockIndexOfPrevPosition = blockIndex; }
Source:
<code>public void verifySlotExpanded(String slotName) { By slotById = By.id(slotName); WebElement slot = driver.findElement(slotById); wait.forElementVisible(slotById); scrollToSlotOnMobile(slotName); if (checkIfSlotExpanded(slot)) { Log.log("AdInSlot", <START> "Slot (" + slotName + ") expanded as expecting", <END> true ); } else { throw new NoSuchElementException("Slot (" + slotName + ") is collapsed - should be expanded"); } }</code><technical_language>![MINOR](<LINK_1> 'Severity: MINOR') Define a constant instead of duplicating this literal "Slot (" 3 times. [![rule](<LINK_0>](http://sonar-s4/coding_rules#rule_key=squid%3AS1192)</technical_language>

Target:
public void verifySlotExpanded(String slotName) { By slotById = By.id(slotName); WebElement slot = driver.findElement(slotById); scrollToSlotOnMobile(slotName); wait.forElementVisible(slotById); if (checkIfSlotExpanded(slot)) { Log.log("AdInSlot", "Slot (" + slotName + ") expanded as expecting", true ); } else { throw new NoSuchElementException("Slot (" + slotName + ") is collapsed - should be expanded"); } }
Source:
<code>public String addPages() { for (String page : this.allPagesSelection) { int aktuelleID = Integer.parseInt(page.split(":")[0]); boolean schonEnthalten = false; if (this.docStruct.getAllToReferences("logical_physical") != null) { <START> for (ReferenceInterface referenceInterface : this.docStruct.getAllToReferences("logical_physical")) { <END> if (referenceInterface.getTarget() == this.allPagesNew[aktuelleID - 1].getMd().getDocStruct()) { schonEnthalten = true; break; } } } if (!schonEnthalten) { this.docStruct.addReferenceTo(this.allPagesNew[aktuelleID - 1].getMd().getDocStruct(), "logical_physical"); } } determinePagesStructure(this.docStruct); this.allPagesSelection = null; if (!updateBlocked()) { return "SperrungAbgelaufen"; } return null; }</code><technical_language>Interface appended variable name</technical_language>

Target:
public String addPages() { for (String page : this.allPagesSelection) { int aktuelleID = Integer.parseInt(page.split(":")[0]); boolean schonEnthalten = false; if (this.docStruct.getAllToReferences("logical_physical") != null) { for (ReferenceInterface reference : this.docStruct.getAllToReferences("logical_physical")) { if (reference.getTarget() == this.allPagesNew[aktuelleID - 1].getMd().getDocStruct()) { schonEnthalten = true; break; } } } if (!schonEnthalten) { this.docStruct.addReferenceTo(this.allPagesNew[aktuelleID - 1].getMd().getDocStruct(), "logical_physical"); } } determinePagesStructure(this.docStruct); this.allPagesSelection = null; if (!updateBlocked()) { return "SperrungAbgelaufen"; } return null; }
Source:
<code>public long getExpectedCompactedFileSize(Iterable<SSTableReader> sstables, OperationType operation) { if (operation != OperationType.CLEANUP || isIndex()) { return SSTableReader.getTotalBytes(sstables); } long expectedFileSize = 0; <START> Collection<Range<Token>> ranges = StorageService.instance.getLocalReplicas(keyspace.getName()).asRangeSet(); <END> for (SSTableReader sstable : sstables) { List<SSTableReader.PartitionPositionBounds> positions = sstable.getPositionsForRanges(ranges); for (SSTableReader.PartitionPositionBounds position : positions) expectedFileSize += position.upperPosition - position.lowerPosition; } double compressionRatio = metric.compressionRatio.getValue(); if (compressionRatio > 0d) expectedFileSize *= compressionRatio; return expectedFileSize; }</code><technical_language>this is a collection Collections2.transform instead of materializing a set</technical_language>

Target:
public long getExpectedCompactedFileSize(Iterable<SSTableReader> sstables, OperationType operation) { if (operation != OperationType.CLEANUP || isIndex()) { return SSTableReader.getTotalBytes(sstables); } long expectedFileSize = 0; Collection<Range<Token>> ranges = StorageService.instance.getLocalReplicas(keyspace.getName()).asUnmodifiableRangeCollection(); for (SSTableReader sstable : sstables) { List<SSTableReader.PartitionPositionBounds> positions = sstable.getPositionsForRanges(ranges); for (SSTableReader.PartitionPositionBounds position : positions) expectedFileSize += position.upperPosition - position.lowerPosition; } double compressionRatio = metric.compressionRatio.getValue(); if (compressionRatio > 0d) expectedFileSize *= compressionRatio; return expectedFileSize; }
Source:
<code>public Object visit(ASTFieldDeclaration node, Object data) { if (!node.isStatic()) { return data; } ASTClassOrInterfaceType cit = node.getFirstDescendantOfType(ASTClassOrInterfaceType.class); if (cit == null || !TypeHelper.isA(cit, formatterClassToCheck)) { return data; } ASTVariableDeclaratorId var = node.getFirstDescendantOfType(ASTVariableDeclaratorId.class); for (String formatter: THREAD_SAFE_FORMATTER) { if (TypeHelper.isA(var, formatter)) { return data; } } for (NameOccurrence occ : var.getUsages()) { Node n = occ.getLocation(); if (n.getFirstParentOfType(ASTSynchronizedStatement.class) != null) { continue; } if (!n.getImage().contains(".")) { continue; } <START> ASTMethodDeclaration method = n.getFirstParentOfType(ASTMethodDeclaration.class); <END> if (method != null && (!method.isSynchronized() || !method.isStatic())) { addViolation(data, n); } } return data; }</code><technical_language>IMHO, I raise a violation in this rule, if synchronized expression is field. rule starts fields of type "*Format". if a field, I a reason, a method get field... synchronized (getFormat()) valid, if formatter is defined (e.g. a subclass), e.g. java void bar() { SimpleDateFormat sdf = getFormat(); synchronized (sdf) { sdf.format("s"); } } protected abstract SimpleDateFormat getFormat(); Note: need a temporary local variable, get result objects getFormat() - in this case, synchronize a object on...</technical_language>

Target:
public Object visit(ASTFieldDeclaration node, Object data) { if (!node.isStatic()) { return data; } ASTClassOrInterfaceType cit = node.getFirstDescendantOfType(ASTClassOrInterfaceType.class); if (cit == null || !TypeHelper.isA(cit, formatterClassToCheck)) { return data; } ASTVariableDeclaratorId var = node.getFirstDescendantOfType(ASTVariableDeclaratorId.class); for (String formatter: THREAD_SAFE_FORMATTER) { if (TypeHelper.isA(var, formatter)) { return data; } } for (NameOccurrence occ : var.getUsages()) { Node n = occ.getLocation(); if (!n.getImage().contains(".")) { continue; } if (getProperty(ALLOW_METHOD_LEVEL_SYNC)) { ASTMethodDeclaration method = n.getFirstParentOfType(ASTMethodDeclaration.class); if (method != null && (!method.isSynchronized() || !method.isStatic())) { addViolation(data, node); } continue; } ASTSynchronizedStatement syncStatement = n.getFirstParentOfType(ASTSynchronizedStatement.class); if (syncStatement != null) { ASTExpression expression = syncStatement.getFirstChildOfType(ASTExpression.class); if (expression != null) { ASTName name = expression.getFirstDescendantOfType(ASTName.class); if (name != null && name.hasImageEqualTo(var.getVariableName())) { continue; } } } addViolation(data, n); } return data; }
Source:
<code>protected boolean doProcess(Record record) { for (Object value : record.get(inputFieldName)) { InetAddress addr; if (value instanceof InetAddress) { addr = (InetAddress) value; } else { try { addr = InetAddresses.forString(value.toString()); } catch (IllegalArgumentException e) { LOG.debug("Invalid IP string literal: {}", value); return false; } } JsonNode json; try { json = databaseReader.get(addr); } catch (IOException e) { throw new MorphlineRuntimeException("Cannot perform GeoIP lookup for IP: " + addr, e); } if (json != null) { ObjectNode location = (ObjectNode) json.get("location"); if (location != null) { JsonNode jlatitude = location.get("latitude"); JsonNode jlongitude = location.get("longitude"); if (jlatitude != null && jlongitude != null) { String latitude = jlatitude.toString(); String longitude = jlongitude.toString(); location.put("latitude_longitude", latitude + "," + longitude); location.put("longitude_latitude", longitude + "," + latitude); } } } else { <START> json = objectMapper.createObjectNode(); <END> } record.put(Fields.ATTACHMENT_BODY, json); } return super.doProcess(record); }</code><technical_language>doProcess() do "return false" continue empty json object. This enclosing tryRules command (or "if" command) react handle case desired. This is similar how, say, extractURIParameters command handles invalid data. Thoughts</technical_language>

Target:
protected boolean doProcess(Record record) { final List values = record.get(inputFieldName); if (values.isEmpty()) { LOG.debug("No values found for field {}", inputFieldName); return false; } for (Object value : values) { InetAddress addr; if (value instanceof InetAddress) { addr = (InetAddress) value; } else { try { addr = InetAddresses.forString(value.toString()); } catch (IllegalArgumentException e) { LOG.debug("Invalid IP string literal: {}", value); return false; } } JsonNode json; try { json = databaseReader.get(addr); } catch (IOException e) { throw new MorphlineRuntimeException("Cannot perform GeoIP lookup for IP: " + addr, e); } if (json == null) { LOG.debug("No GeoIP record found for: {}", value); return false; } ObjectNode location = (ObjectNode) json.get("location"); if (location != null) { JsonNode jlatitude = location.get("latitude"); JsonNode jlongitude = location.get("longitude"); if (jlatitude != null && jlongitude != null) { String latitude = jlatitude.toString(); String longitude = jlongitude.toString(); location.put("latitude_longitude", latitude + "," + longitude); location.put("longitude_latitude", longitude + "," + latitude); } } record.put(Fields.ATTACHMENT_BODY, json); } return super.doProcess(record); }