auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void doAuthenticate(ExtMap input, ExtMap output) { if (!(input.get(Authn.InvokeKeys.USER).equals(adminUser) && input.get(Authn.InvokeKeys.CREDENTIALS) .equals(adminPassword))) { output.put(Authn.InvokeKeys.RESULT, Authn.AuthResult.CREDENTIALS_INVALID); } else { output.put(Authn.InvokeKeys.AUTH_RECORD, new ExtMap().mput( Authn.AuthRecord.PRINCIPAL, adminUser ).mput( <START> Authn.AuthRecord.VALID_TO, <END> new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").format( DateUtils.addMinutes( new Date(System.currentTimeMillis()), Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval) ) ) ) ); output.put(Authn.InvokeKeys.RESULT, Authn.AuthResult.SUCCESS); } }</code><technical_language>this is required here... do set VALID_TO if restriction for this user, core set config value</technical_language>

Target:
private void doAuthenticate(ExtMap input, ExtMap output) { if (!(input.get(Authn.InvokeKeys.USER).equals(adminUser) && input.get(Authn.InvokeKeys.CREDENTIALS) .equals(adminPassword))) { output.put(Authn.InvokeKeys.RESULT, Authn.AuthResult.CREDENTIALS_INVALID); } else { output.put(Authn.InvokeKeys.AUTH_RECORD, new ExtMap().mput( Authn.AuthRecord.PRINCIPAL, adminUser ) ); output.put(Authn.InvokeKeys.RESULT, Authn.AuthResult.SUCCESS); } }
Source:
<code>static void replaceOperationException(AtomicReference<Exception> operationExceptionRef, RouterException exception, ToIntFunction<RouterErrorCode> precedenceLevelFn) { RouterErrorCode routerErrorCode = exception.getErrorCode(); Exception currentException; Exception newException; do { currentException = operationExceptionRef.get(); if (currentException == null) { newException = exception; } else { int currentPrecedence = precedenceLevelFn.applyAsInt( currentException instanceof RouterException ? ((RouterException) currentException).getErrorCode() : RouterErrorCode.UnexpectedInternalError); <START> newException = precedenceLevelFn.applyAsInt(routerErrorCode) < currentPrecedence ? exception : currentException; <END> } } while (!operationExceptionRef.compareAndSet(currentException, newException)); }</code><technical_language>I suggest replacing routerErrorCode exception.getErrorCode() in this loop</technical_language>

Target:
static void replaceOperationException(AtomicReference<Exception> operationExceptionRef, RouterException exception, ToIntFunction<RouterErrorCode> precedenceLevelFn) { Exception currentException; Exception newException; do { currentException = operationExceptionRef.get(); if (currentException == null) { newException = exception; } else { int currentPrecedence = precedenceLevelFn.applyAsInt( currentException instanceof RouterException ? ((RouterException) currentException).getErrorCode() : RouterErrorCode.UnexpectedInternalError); newException = precedenceLevelFn.applyAsInt(exception.getErrorCode()) < currentPrecedence ? exception : currentException; } } while (!operationExceptionRef.compareAndSet(currentException, newException)); }
Source:
<code>protected void validateDeleteRespPayloadAndExchangeType( List<IkePayload> respPayloads, @ExchangeType int exchangeType) throws IkeProtocolException { if (exchangeType != EXCHANGE_TYPE_INFORMATIONAL) { throw new InvalidSyntaxException( "Unexpected exchange type in Delete Child response: " + exchangeType); } for (IkePayload payload : respPayloads) { handlePayload: switch (payload.payloadType) { case PAYLOAD_TYPE_DELETE: break handlePayload; case PAYLOAD_TYPE_NOTIFY: IkeNotifyPayload notify = (IkeNotifyPayload) payload; if (!notify.isErrorNotify()) { logw( "Unexpected or unknown status notification in Delete Child" + " response: " + notify.notifyType); break handlePayload; } <START> IkeProtocolException exception = <END> notify.validateAndBuildIkeException(); throw exception; default: logw( "Unexpected payload type in Delete Child response: " + payload.payloadType); } } }</code><technical_language>If this after, suggest inlining</technical_language>

Target:
protected void validateDeleteRespPayloadAndExchangeType( List<IkePayload> respPayloads, @ExchangeType int exchangeType) throws IkeProtocolException { if (exchangeType != EXCHANGE_TYPE_INFORMATIONAL) { throw new InvalidSyntaxException( "Unexpected exchange type in Delete Child response: " + exchangeType); } for (IkePayload payload : respPayloads) { handlePayload: switch (payload.payloadType) { case PAYLOAD_TYPE_DELETE: break handlePayload; case PAYLOAD_TYPE_NOTIFY: IkeNotifyPayload notify = (IkeNotifyPayload) payload; if (!notify.isErrorNotify()) { logw( "Unexpected or unknown status notification in Delete Child" + " response: " + notify.notifyType); break handlePayload; } throw notify.validateAndBuildIkeException(); default: logw( "Unexpected payload type in Delete Child response: " + payload.payloadType); } } }
Source:
<code>public ChannelPipelineFactory newChannelPipelineFactory(final int maxFrameSize) { return new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline cp = Channels.pipeline(); cp.addLast("frameEncoder", new LengthFieldPrepender(4)); cp.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, <START> 0, 4, 0, 4)); <END> return cp; } }; }</code><technical_language>magic numbers. Some explanation good</technical_language>

Target:
public ChannelPipelineFactory newChannelPipelineFactory(final int maxFrameSize) { return new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline cp = Channels.pipeline(); cp.addLast("frameEncoder", new LengthFieldPrepender(LENGTH_FIELD_LENGTH)); cp.addLast( "frameDecoder", new LengthFieldBasedFrameDecoder( maxFrameSize, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP)); return cp; } }; }
Source:
<code>public List<UnregisteredDisk> getByDiskIdAndStorageDomainId(Guid diskId, Guid storageDomainId) { List<UnregisteredDisk> unregisteredDisks = getCallsHandler().executeReadList("GetDiskByDiskIdAndStorageDomainId", unregisteredDiskRowMapper, <START> getCustomMapSqlParameterSource() .addValue("disk_id", diskId) .addValue("storage_domain_id", storageDomainId)); <END> for (UnregisteredDisk unregDisk : unregisteredDisks) { List<VmBase> vms = getCallsHandler().executeReadList("GetEntitiesByDiskId", vmsForUnregisteredDiskRowMapper, getCustomMapSqlParameterSource().addValue("disk_id", unregDisk.getId().getDiskId())); unregDisk.getVms().addAll(vms); } return unregisteredDisks; }</code><technical_language>Replace id storage id mapper added</technical_language>

Target:
public List<UnregisteredDisk> getByDiskIdAndStorageDomainId(Guid diskId, Guid storageDomainId) { List<UnregisteredDisk> unregisteredDisks = getCallsHandler().executeReadList("GetDiskByDiskIdAndStorageDomainId", unregisteredDiskRowMapper, createIdParameterMapper(new UnregisteredDiskId(diskId, storageDomainId))); for (UnregisteredDisk unregDisk : unregisteredDisks) { List<VmBase> vms = getCallsHandler().executeReadList("GetEntitiesByDiskId", vmsForUnregisteredDiskRowMapper, getCustomMapSqlParameterSource().addValue("disk_id", unregDisk.getId().getDiskId())); unregDisk.getVms().addAll(vms); } return unregisteredDisks; }
Source:
<code>private List<Artifact> readArtifactList(ObjectMapper mapper, String hydratedTemplate) { try { return mapper.readValue(hydratedTemplate, artifactListReference); } catch (IOException ioe) { <START> log.error("Unable to parse artifact from {}", hydratedTemplate); <END> } return null; }</code><technical_language>Is this more a log.warn</technical_language>

Target:
private List<Artifact> readArtifactList(ObjectMapper mapper, String hydratedTemplate) { try { return mapper.readValue(hydratedTemplate, artifactListReference); } catch (IOException ioe) { log.warn("Unable to parse artifact from {}", hydratedTemplate); } return null; }
Source:
<code><START> public long getOneKB() { <END> return oneKb; }</code><technical_language>public method need VisibleForTesting annotation</technical_language>

Target:
long getOneKB() { return oneKb; }
Source:
<code>public static Slice stGeometryN(@SqlType(GEOMETRY_TYPE_NAME) Slice input, <START> @SqlType(INTEGER) long index) <END> { OGCGeometry geometry = deserialize(input); GeometryType type = GeometryType.getForEsriGeometryType(geometry.geometryType()); if (!type.isMultitype()) { if (index == 1) { return input; } return null; } if (index < 1 || index > ((OGCGeometryCollection) geometry).numGeometries()) { return null; } return serialize(((OGCGeometryCollection) geometry).geometryN((int) index - 1)); }</code><technical_language>move this previous line</technical_language>

Target:
public static Slice stGeometryN(@SqlType(GEOMETRY_TYPE_NAME) Slice input, @SqlType(INTEGER) long index) { OGCGeometry geometry = deserialize(input); if (geometry.isEmpty()) { return null; } GeometryType type = GeometryType.getForEsriGeometryType(geometry.geometryType()); if (!type.isMultitype()) { if (index == 1) { return input; } return null; } OGCGeometryCollection geometryCollection = ((OGCGeometryCollection) geometry); if (index < 1 || index > geometryCollection.numGeometries()) { return null; } OGCGeometry ogcGeometry = geometryCollection.geometryN((int) index - 1); return serialize(ogcGeometry); }
Source:
<code>public void beforeClass() { embeddedCacheManager = TestCacheManagerFactory.createCacheManager(); hotrodServer = HotRodTestingUtil.startHotRodServer(embeddedCacheManager, 19723); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("localhost").port(hotrodServer.getPort()) .marshaller(new JavaSerializationMarshaller()) <START> .addJavaSerialWhiteList("java.time.*", "org.springframework.session.MapSession", "org.infinispan.spring.remote.*"); <END> remoteCacheManager = new RemoteCacheManager(builder.build()); }</code><technical_language>need this time work</technical_language>

Target:
public void beforeClass() { embeddedCacheManager = TestCacheManagerFactory.createCacheManager(); hotrodServer = HotRodTestingUtil.startHotRodServer(embeddedCacheManager, 19723); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("localhost").port(hotrodServer.getPort()) .marshaller(new JavaSerializationMarshaller()) .addJavaSerialWhiteList(SPRING_JAVA_SERIAL_WHITELIST.split(",")); remoteCacheManager = new RemoteCacheManager(builder.build()); }
Source:
<code>public <E> CacheQuery<E> buildCacheQuery(QueryDefinition queryDefinition, IndexedQueryMode indexedQueryMode, KeyTransformationHandler keyTransformationHandler, TimeoutExceptionFactory timeoutExceptionFactory, ExecutorService asyncExecutor, IndexedTypeMap<CustomTypeMetadata> indexedTypeMap) { if (!isIndexed) { throw log.cannotRunLuceneQueriesIfNotIndexed(cache.getName()); } if (indexedQueryMode == IndexedQueryMode.BROADCAST) { return new ClusteredCacheQueryImpl<>(queryDefinition, asyncExecutor, cache, keyTransformationHandler, indexedTypeMap); } else { queryDefinition.initialize(cache); HSQuery hsQuery = queryDefinition.getHsQuery(); <START> CacheQuery cacheQuery = new CacheQueryImpl<>(hsQuery, cache, keyTransformationHandler); <END> return (CacheQuery<E>) cacheQuery; } }</code><technical_language>line return new CacheQueryImpl<E>(hsQuery, cache, keyTransformationHandler); avoid warning</technical_language>

Target:
public <E> CacheQuery<E> buildCacheQuery(QueryDefinition queryDefinition, IndexedQueryMode indexedQueryMode, KeyTransformationHandler keyTransformationHandler, TimeoutExceptionFactory timeoutExceptionFactory, ExecutorService asyncExecutor, IndexedTypeMap<CustomTypeMetadata> indexedTypeMap) { if (!isIndexed) { throw log.cannotRunLuceneQueriesIfNotIndexed(cache.getName()); } if (indexedQueryMode == IndexedQueryMode.BROADCAST) { return new ClusteredCacheQueryImpl<>(queryDefinition, asyncExecutor, cache, keyTransformationHandler, indexedTypeMap); } else { queryDefinition.initialize(cache); HSQuery hsQuery = queryDefinition.getHsQuery(); return new CacheQueryImpl<>(hsQuery, cache, keyTransformationHandler); } }
Source:
<code>private String marshallAuditMessage(AuditMessageType mess) { if (mess != null) { try { JAXBContextHandler oHandler = new JAXBContextHandler(); JAXBContext jc = oHandler.getJAXBContext(AUDIT_MESSAGE_NAMESPACE); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); <START> ByteArrayOutputStream baOutStrm = new ByteArrayOutputStream(); <END> baOutStrm.reset(); ObjectFactory factory = new ObjectFactory(); JAXBElement<AuditMessageType> oJaxbElement = factory.createAuditMessage(mess); baOutStrm.close(); marshaller.marshal(oJaxbElement, baOutStrm); return baOutStrm.toString(); } catch (JAXBException | IOException e) { LOG.error("Exception during Blob conversion {}", e.getLocalizedMessage(), e); } } return null; }</code><technical_language>If exception happens, ByteArrayOutputstream close it. Please move final block</technical_language>

Target:
private String marshallAuditMessage(AuditMessageType mess) { if (mess != null) { ByteArrayOutputStream baOutStrm = null; try { JAXBContext jc = new JAXBContextHandler().getJAXBContext(AUDIT_MESSAGE_NAMESPACE); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); baOutStrm = new ByteArrayOutputStream(); baOutStrm.reset(); ObjectFactory factory = new ObjectFactory(); JAXBElement<AuditMessageType> oJaxbElement = factory.createAuditMessage(mess); marshaller.marshal(oJaxbElement, baOutStrm); return baOutStrm.toString(); } catch (JAXBException e) { LOG.error("Exception during Blob conversion {}", e.getLocalizedMessage(), e); } finally { if (baOutStrm != null) { try { baOutStrm.close(); } catch (IOException ex) { LOG.error("Unable to close OutputStream {}", ex.getLocalizedMessage(), ex); } } } } return null; }
Source:
<code><START> private static String expectedTypeInsteadOfOptional(Type type) { <END> if (type.is(JAVA_UTIL_OPTIONAL) && ((JavaType) type).isParameterized()) { ParametrizedTypeJavaType parametrizedTypeJavaType = (ParametrizedTypeJavaType) type; return parametrizedTypeJavaType.substitution(parametrizedTypeJavaType.typeParameters().get(0)).erasure().name(); } Optional<String> primitiveOptional = PRIMITIVE_OPTIONALS.stream().filter(type::is).findFirst(); if (primitiveOptional.isPresent()) { return primitiveOptional.get().substring(JAVA_UTIL_OPTIONAL.length()).toLowerCase(); } return null; }</code><technical_language>This return optional instead of null optional unwrapped in calling method</technical_language>

Target:
private static Optional<String> expectedTypeInsteadOfOptional(Type type) { if (type.is(JAVA_UTIL_OPTIONAL)) { String msg; if (((JavaType) type).isParameterized()) { ParametrizedTypeJavaType ptjt = (ParametrizedTypeJavaType) type; String parameterTypeName = ptjt.substitution(ptjt.typeParameters().get(0)).erasure().name(); msg = formatMsg(parameterTypeName); } else { msg = "Specify a type instead."; } return Optional.of(msg); } return PRIMITIVE_OPTIONALS.stream() .filter(type::is) .findFirst() .map(optional -> formatMsg(optional.substring(JAVA_UTIL_OPTIONAL.length()).toLowerCase())); }
Source:
<code><START> public synchronized void load() throws IOException { <END> COL result = create(); if (exists()) { try (LinesStream stream = lines()) { for (String line : stream) { if (line.startsWith("#")) continue; T r = parse(line); if (r != null) result.add(r); } } } parsed = readOnly(result); }</code><technical_language>breaks source compatibility IIUC. I introduce a new deprecate load()</technical_language>

Target:
public void load() { try { load2(); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>public void addLocalizedTitle(LocalizedTitle localizedTitle) { <START> this.localizedTitles = ImmutableSet.<LocalizedTitle> builder() <END> .add(localizedTitle) .addAll(localizedTitles) .build(); }</code><technical_language>Check out useful MoreSets.add()</technical_language>

Target:
public void addLocalizedTitle(LocalizedTitle localizedTitle) { this.localizedTitles = MoreSets.add(localizedTitles, localizedTitle); }
Source:
<code>private Chain dropLastElement(Chain chain) { List<Element> elements = StreamSupport.stream(chain.spliterator(), false) .collect(Collectors.toList()); <START> if (!elements.isEmpty()) { <END> elements.remove(elements.size() - 1); } return Util.getChain(elements); }</code><technical_language>do a chain.isEmpty. StreamSupport.stream(chain.spliterator(), false).limit(chain.length() -1) possibly. leave for for collecting create chain is sad... a Util.getChain(Stream stream)</technical_language>

Target:
private Chain dropLastElement(Chain chain) { if (!chain.isEmpty()) { List<Element> elements = StreamSupport.stream(chain.spliterator(), false) .collect(Collectors.toList()); elements.remove(elements.size() - 1); return Util.getChain(elements); } else { return chain; } }
Source:
<code>@Test public void testMissingFileInitializes() throws Exception { testFile = File.createTempFile(FRESH_SERIALIZED_QUEUE, "test"); assertTrue(testFile.delete()); assertFalse(testFile.exists()); QueueFile queue = new QueueFile.Builder(testFile).build(); try { assertEquals(0, queue.size()); assertTrue(testFile.exists()); } finally { <START> queue.close(); <END> } }</code><technical_language>do of need try-finally blocks (instead of closing afterwards)? if exception in tests, matter if file is closed</technical_language>

Target:
@Test public void testMissingFileInitializes() throws Exception { testFile = File.createTempFile(FRESH_SERIALIZED_QUEUE, "test"); assertTrue(testFile.delete()); assertFalse(testFile.exists()); QueueFile queue = new QueueFile.Builder(testFile).build(); assertEquals(0, queue.size()); assertTrue(testFile.exists()); queue.close(); }
Source:
<code>public void processEvent(CloudTrailEvent event) { List<String> instances = getInstances(event); for (String instance : instances) { DateTime eventDate = getLifecycleDate(event, instance); LifecycleEntity lifecycleEntity = new LifecycleEntity(); lifecycleEntity.setEventType(event.getEventData().getEventName()); lifecycleEntity.setEventDate(eventDate); ApplicationEntity applicationEntity; VersionEntity versionEntity; try { String versionName = getVersionName(event, instance); versionEntity = new VersionEntity(versionName); String applicationName = getApplicationName(event, instance); applicationEntity = new ApplicationEntity(applicationName); } catch (AmazonServiceException e) { <START> LOG.warn("Lifecycle: {}", e.getMessage()); <END> return; } applicationLifecycleService.saveLifecycle(applicationEntity, versionEntity, lifecycleEntity); } }</code><technical_language>nice a more speaking error message: "Could get version/application for lifecycle event." I personally prefer e.toString() e.getMessage() contains exception name well. slf4j api here: LOG.warn(String msg, Throwable t) prints stack trace. This useful</technical_language>

Target:
public void processEvent(CloudTrailEvent event) { List<String> instances = getInstances(event); String region = getRegionAsString(event); for (String instance : instances) { DateTime eventDate = getLifecycleDate(event, instance); LifecycleEntity lifecycleEntity = new LifecycleEntity(); lifecycleEntity.setEventType(event.getEventData().getEventName()); lifecycleEntity.setEventDate(eventDate); lifecycleEntity.setRegion(region); lifecycleEntity.setInstanceId(getSingleInstance(instance)); ApplicationEntity applicationEntity; VersionEntity versionEntity; try { String versionName = getVersionName(event, instance); versionEntity = new VersionEntity(versionName); String applicationName = getApplicationName(event, instance); applicationEntity = new ApplicationEntity(applicationName); } catch (AmazonServiceException e) { LOG.warn("Could not get version/application for lifecycle event.", e); return; } applicationLifecycleService.saveLifecycle(applicationEntity, versionEntity, lifecycleEntity); } }
Source:
<code><START> public TimelineResult(ImmutableList<Timeline> timelines, TimelineLog log) { <END> this.timelines = timelines; this.log = log; }</code><technical_language>a static create method, constructor private? (that create a TimelineResult)</technical_language>

Target:
private TimelineResult(ImmutableList<Timeline> timelines, TimelineLog log) { this.timelines = timelines; this.log = log; }
Source:
<code>public void run() throws Exception { List<String> argsList = (List <String>)args.get("__other__"); <START> Runnable action = actions.get(argsList.remove(0)); <END> if(action == null) { throw new IllegalArgumentException( String.format("No such action '%1$s' exists for module '%2$s'", action, getName()) ); } action.run(); }</code><technical_language>is good modify args provided, action ignore if likes, removing allow reusing class</technical_language>

Target:
public void run() throws Exception { List<String> argsList = (List <String>)args.get("__other__"); Runnable action = actions.get(argsList.get(0)); if(action == null) { throw new IllegalArgumentException( String.format("No such action '%1$s' exists for module '%2$s'", action, getName()) ); } action.run(); }
Source:
<code>public SSLSocketFactory( String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final HostNameResolver nameResolver) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(); if (algorithm == null) { algorithm = TLS; } KeyManager[] keymanagers = null; if (keystore != null) { keymanagers = createKeyManagers(keystore, keystorePassword); } TrustManager[] trustmanagers = null; if (truststore != null) { trustmanagers = createTrustManagers(truststore); } sslcontext = SSLContext.getInstance(algorithm); sslcontext.init(keymanagers, trustmanagers, random); <START> socketfactory = (SSLCertificateSocketFactory) sslcontext.getSocketFactory(); <END> this.nameResolver = nameResolver; }</code><technical_language>This blow ClassCastException SSLContext.getSocketFactory is highly return instance of SSLCertificateSocketFactory. proper obtain SSLCertificateSocketFactory is of getDefault methods</technical_language>

Target:
public SSLSocketFactory( String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final HostNameResolver nameResolver) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(); if (algorithm == null) { algorithm = TLS; } KeyManager[] keymanagers = null; if (keystore != null) { keymanagers = createKeyManagers(keystore, keystorePassword); } TrustManager[] trustmanagers = null; if (truststore != null) { trustmanagers = createTrustManagers(truststore); } sslcontext = SSLContext.getInstance(algorithm); sslcontext.init(keymanagers, trustmanagers, random); socketfactory = sslcontext.getSocketFactory(); this.nameResolver = nameResolver; }
Source:
<code>public void destroyNode(String id) { api.getRemoteApi().stopContainer(id); <START> api.getRemoteApi().removeContainer(id); <END> }</code><technical_language>container removed if stop operation fails</technical_language>

Target:
public void destroyNode(String id) { api.getRemoteApi().removeContainer(id, RemoveContainerOptions.Builder.force(true)); }
Source:
<code>public void setFluoTableSplits(SortedSet<Text> splits) { final String table = fluoConfig.getAccumuloTable(); <START> if (conn.tableOperations().exists(table)) { <END> try { conn.tableOperations().addSplits(table, splits); } catch (AccumuloException | AccumuloSecurityException | TableNotFoundException e) { throw new IllegalStateException("Failed to add splits to Fluo's Accumulo table " + table, e); } } else { log.error("Fluo's Accumulo table does not exist. No splits will be added", table); } }</code><technical_language>check is needed. Split throw TableNotFound if exists</technical_language>

Target:
public void setFluoTableSplits(SortedSet<Text> splits) { final String table = fluoConfig.getAccumuloTable(); try { conn.tableOperations().addSplits(table, splits); } catch (AccumuloException | AccumuloSecurityException | TableNotFoundException e) { throw new IllegalStateException("Failed to add splits to Fluo's Accumulo table " + table, e); } }
Source:
<code>protected void updateSearchField() { if (!isNew() && !forceUpdateSearchPrefixes <START> && getDescriptor().isFetched(this, <END> getDescriptor().getProperty(SEARCH_PREFIXES)) && !isAnyMappingChanged()) { return; } getSearchPrefixes().clear(); this.getDescriptor() .getProperties() .stream() .filter(p -> p.getAnnotation(PrefixSearchContent.class).isPresent()) .map(p -> p.getValue(this)) .filter(Strings::isFilled) .forEach(this::addContent); }</code><technical_language>why</technical_language>

Target:
protected void updateSearchField() { if (!isNew() && !forceUpdateSearchPrefixes && !isAnyMappingChanged()) { return; } getSearchPrefixes().clear(); this.getDescriptor() .getProperties() .stream() .filter(p -> p.getAnnotation(PrefixSearchContent.class).isPresent()) .map(p -> p.getValue(this)) .filter(Strings::isFilled) .forEach(this::addContent); }
Source:
<code>public boolean equals(Object o) { <START> throw new UnsupportedOperationException("equals:ImmutableDruidDataSource shouldn't be used as the key in containers"); <END> }</code><technical_language>equals:ImmutableDruidDataSource is Java convention. familiar it. this convention from</technical_language>

Target:
public boolean equals(Object o) { throw new UnsupportedOperationException("ImmutableDruidDataSource shouldn't be used as the key in containers"); }
Source:
<code>public void cannotDropTables() { assertThrowsAtlasDbDependencyExceptionAndDoesNotChangeCassandraSchema(() -> <START> getTestKvs().truncateTable(TABLE_TO_DROP_2)); <END> }</code><technical_language>Is this intentional? tests call drop - especially tables truncated in other tests</technical_language>

Target:
public void cannotDropTables() { assertThrowsAtlasDbDependencyExceptionAndDoesNotChangeCassandraSchema(() -> getTestKvs().dropTables(ImmutableSet.of(TABLE_TO_DROP_2))); }
Source:
<code>public void testBytes() { assertQueryUsingH2Cte("SELECT byte_col1 FROM lineitem_ex"); <START> assertQueryUsingH2Cte("SELECT byte_col1 FROM lineitem_ex WHERE byte_col1 < 0"); <END> assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE byte_col1 > 0"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE byte_col1 is null"); assertQueryUsingH2Cte("SELECT byte_col1, byte_col2 FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT byte_col1, byte_col2 FROM lineitem_ex WHERE byte_col1 = 0"); assertQueryUsingH2Cte("SELECT byte_col1, byte_col2 FROM lineitem_ex WHERE byte_col1 = 0 AND byte_col2 = 0"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE byte_col1 is null"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE byte_col1 is not null AND byte_col2 = 1"); assertQueryUsingH2Cte("SELECT byte_col1, byte_col2 FROM lineitem_ex WHERE byte_col1 > 0 and byte_col2 < 0 and (byte_col1 + byte_col2) = 0"); }</code><technical_language>This query returns data. Is this intentional? If so, perhaps, assertQueryReturnsEmptyResult</technical_language>

Target:
public void testBytes() { assertQueryUsingH2Cte("SELECT ship_day FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_day FROM lineitem_ex WHERE ship_day < 15"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day > 15"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day is null"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_month = 1"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_day = 1 AND ship_month = 1"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE ship_month is null"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE ship_day is not null AND ship_month = 1"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_day > 15 AND ship_month < 5 AND (ship_day + ship_month) < 20"); }
Source:
<code>public PatchList get(PatchListKey key) { try { return fileCache.get(key); } catch (ExecutionException e) { PatchListLoader.log.warn("Error computing " + key, e); <START> return null; END> } }</code><technical_language>want put this off</technical_language>

Target:
public PatchList get(PatchListKey key) throws PatchListNotAvailableException { try { return fileCache.get(key); } catch (ExecutionException e) { PatchListLoader.log.warn("Error computing " + key, e); throw new PatchListNotAvailableException(e.getCause()); } }
Source:
<code>public static Function<Resource, Long> toLongResourceValue() { return new Function<Resource, Long>() { @Override <START> public Long apply(@Nullable Resource resource) { <END> return resourceValueLong(Optional.fromNullable(resource)).or(0l); } }; }</code><technical_language>Please mark resource parameter final</technical_language>

Target:
public static Function<Resource, Long> toLongResourceValue() { return ToLongResourceValue.INSTANCE; }
Source:
<code>public PolymorphicScalarFunctionChoice build() { if (argumentProperties.isEmpty()) { <START> argumentProperties = Collections.nCopies(signature.getArgumentTypes().size(), valueTypeArgumentProperty(RETURN_NULL_ON_NULL)); <END> } return new PolymorphicScalarFunctionChoice(nullableResult, argumentProperties, methodsGroups); }</code><technical_language>static import nCopies</technical_language>

Target:
public PolymorphicScalarFunctionChoice build() { return new PolymorphicScalarFunctionChoice(nullableResult, argumentProperties, methodsGroups.build()); }
Source:
<code>public AuditLogType getAuditLogTypeValue() { <START> addCustomValue("UserName", String.format("%s", getUserName())); <END> return getSucceeded() ? AuditLogType.USER_REBOOT_VM : AuditLogType.USER_FAILED_REBOOT_VM; }</code><technical_language>This line needed. 'UserName' automatically replaced calling getUserName()</technical_language>

Target:
public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.USER_REBOOT_VM : AuditLogType.USER_FAILED_REBOOT_VM; }
Source:
<code>private float getChargingPercent(ItemStack stack) { if (stack != null && stack.getItem() instanceof ItemExosuitArmor) { if (!stack.hasTagCompound()) { stack.setTagCompound(new NBTTagCompound()); } if (!stack.stackTagCompound.hasKey("steamFill")) { stack.stackTagCompound.setInteger("steamFill", 0); } if (!stack.stackTagCompound.hasKey("maxFill")) { stack.stackTagCompound.setInteger("maxFill", 0); } int maxFill = stack.stackTagCompound.getInteger("maxFill"); int steamFill = stack.stackTagCompound.getInteger("steamFill"); return ((float) steamFill / (float) maxFill); <START> } else if (stack != null) { <END> return 1.0f - ((float) stack.getItemDamage() / (float) stack.getMaxDamage()); } return 0.0f; }</code><technical_language>I this kind of confusing. I change this method more like: java if (stack == null) { return 0F; } if (stack.getItem() instanceof ItemExosuitArmor) { // ... stuff return ((float) steamFill / (float) maxFill); } return 1F - ((float) stack.getItemDamage() / (float) stack.getMaxDamage());</technical_language>

Target:
private float getChargingPercent(ItemStack stack) { if (stack == null) { return 0F; } if (stack.getItem() instanceof ItemExosuitArmor) { if (!stack.hasTagCompound()) { stack.setTagCompound(new NBTTagCompound()); } if (!stack.stackTagCompound.hasKey("steamFill")) { stack.stackTagCompound.setInteger("steamFill", 0); } if (!stack.stackTagCompound.hasKey("maxFill")) { stack.stackTagCompound.setInteger("maxFill", 0); } int maxFill = stack.stackTagCompound.getInteger("maxFill"); int steamFill = stack.stackTagCompound.getInteger("steamFill"); return ((float) steamFill / (float) maxFill); } return 1.0f - ((float) stack.getItemDamage() / (float) stack.getMaxDamage()); }
Source:
<code>public void createsCorrectRefundPayload() { String payload = stripeRefundRequest.getGatewayOrder().getPayload(); assertThat(payload, containsString("charge=" + stripeChargeId)); assertThat(payload, containsString("amount=" + refundAmount)); <START> assertThat(payload, containsString("refund_application_fee=true")); <END> }</code><technical_language>add reverse_transfer</technical_language>

Target:
public void createsCorrectRefundPayload() { String payload = stripeRefundRequest.getGatewayOrder().getPayload(); assertThat(payload, containsString("charge=" + stripeChargeId)); assertThat(payload, containsString("amount=" + refundAmount)); assertThat(payload, containsString("refund_application_fee=true")); assertThat(payload, containsString("reverse_transfer=true")); }
Source:
<code><START> public List<Guid> getHostIdsForClusterAndStatus(Guid clusterId, VDSStatus hostStatus) { <END> final String sql = "select vds_static.vds_id \n" + "from vds_static \n" + "join vds_dynamic on vds_static.vds_id = vds_dynamic.vds_id \n" + "where vds_static.cluster_id = :v_clusterId \n" + "and vds_dynamic.status = :v_status"; final MapSqlParameterSource customMapSqlParameterSource = getCustomMapSqlParameterSource() .addValue("clusterId", clusterId) .addValue("status", hostStatus); final NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate()); return namedParameterJdbcTemplate.query(sql, customMapSqlParameterSource, GUID_MAPPER); }</code><technical_language>1. a stored procedure? 2. In case infra team ok a stored procedure, consider implementing SearchDao</technical_language>

Target:
public List<Guid> getHostIdsForClusterAndStatus(Guid clusterId, VDSStatus hostStatus) { final String sql = "select vds_static.vds_id \n" + "from vds_static \n" + "join vds_dynamic on vds_static.vds_id = vds_dynamic.vds_id \n" + "where vds_static.cluster_id = :v_clusterId \n" + "and vds_dynamic.status = :v_status"; final MapSqlParameterSource customMapSqlParameterSource = getCustomMapSqlParameterSource() .addValue("clusterId", clusterId) .addValue("status", hostStatus); final NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate()); return namedParameterJdbcTemplate.query(sql, customMapSqlParameterSource, createGuidMapper()); }
Source:
<code>private void doFullTextSearch(final String searchTerm, final Map<String, String> continueOffset, final boolean clearOnSuccess) { final long startTime = System.nanoTime(); updateProgressBar(true); disposables.add(ServiceFactory.get(WikiSite.forLanguageCode(getSearchLanguageCode())).fullTextSearch(searchTerm, BATCH_SIZE, continueOffset != null ? continueOffset.get("continue") : null, continueOffset != null ? continueOffset.get("gsroffset") : null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(response -> { if (response.query() != null) { return new SearchResults(response.query().pages(), WikiSite.forLanguageCode(getSearchLanguageCode()), response.continuation(), null); } return new SearchResults(); }) .flatMap(results -> { List<SearchResult> resultList = results.getResults(); cache(resultList, searchTerm); log(resultList, startTime); if (clearOnSuccess) { clearResults(false); } searchErrorView.setVisibility(View.GONE); SearchResultsFragment.this.lastFullTextResults = results; if (!resultList.isEmpty()) { displayResults(resultList); } return resultList.isEmpty() ? doFullTextSearchResultsCountObservable(searchTerm) : Observable.empty(); }) .toList() <START> .doAfterTerminate(() -> updateProgressBar(false)) <END> .subscribe(list -> { if (!list.isEmpty()) { searchResultsCountCache.put(getSearchLanguageCode() + "-" + searchTerm, list); displayResultsCount(list); } }, throwable -> { logError(true, startTime); })); }</code><technical_language>return empty() observable, this part is called, progress bar spinning forever</technical_language>

Target:
private void doFullTextSearch(final String searchTerm, final Map<String, String> continueOffset, final boolean clearOnSuccess) { final long startTime = System.nanoTime(); updateProgressBar(true); disposables.add(ServiceFactory.get(WikiSite.forLanguageCode(getSearchLanguageCode())).fullTextSearch(searchTerm, BATCH_SIZE, continueOffset != null ? continueOffset.get("continue") : null, continueOffset != null ? continueOffset.get("gsroffset") : null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(response -> { if (response.query() != null) { return new SearchResults(response.query().pages(), WikiSite.forLanguageCode(getSearchLanguageCode()), response.continuation(), null); } return new SearchResults(); }) .flatMap(results -> { List<SearchResult> resultList = results.getResults(); cache(resultList, searchTerm); log(resultList, startTime); if (clearOnSuccess) { clearResults(false); } searchErrorView.setVisibility(View.GONE); SearchResultsFragment.this.lastFullTextResults = results; if (!resultList.isEmpty()) { displayResults(resultList); } else { updateProgressBar(true); } return resultList.isEmpty() ? doFullTextSearchResultsCountObservable(searchTerm) : Observable.empty(); }) .toList() .doAfterTerminate(() -> updateProgressBar(false)) .subscribe(list -> { if (!list.isEmpty()) { searchResultsCountCache.put(getSearchLanguageCode() + "-" + searchTerm, list); displayResultsCount(list); } }, throwable -> { logError(true, startTime); })); }
Source:
<code>public <T> NavigableMap<String, T> getMostRecentValues(String family) throws IOException { Preconditions.checkState(mTableLayout.getFamilyMap().get(family).isMapType(), <START> new IllegalStateException(String.format("getMostRecentValues(String family) is only enabled" <END> + " on map type column families. The column family [%s], is a group type column family." + " Please use the getMostRecentValues(String family, String qualifier) method.", family))); final NavigableMap<String, T> result = Maps.newTreeMap(); for (String qualifier : getQualifiers(family)) { final T value = getMostRecentValue(family, qualifier); result.put(qualifier, value); } return result; }</code><technical_language>Preconditions takes a boolean expression a string. need wrap exception, created if Preconditions fails</technical_language>

Target:
public <T> NavigableMap<String, T> getMostRecentValues(String family) throws IOException { Preconditions.checkState(mTableLayout.getFamilyMap().get(family).isMapType(), String.format("getMostRecentValues(String family) is only enabled" + " on map type column families. The column family [%s], is a group type column family." + " Please use the getMostRecentValues(String family, String qualifier) method.", family)); final NavigableMap<String, T> result = Maps.newTreeMap(); for (String qualifier : getQualifiers(family)) { final T value = getMostRecentValue(family, qualifier); result.put(qualifier, value); } return result; }
Source:
<code>private void openSocket() { try { socket = new DatagramSocket(); } catch (SocketException e) { <START> log.error("Cannot reopen socket", e); <END> throw Throwables.propagate(e); } }</code><technical_language>reopen -> open</technical_language>

Target:
private void openSocket() { try { socket = new DatagramSocket(); } catch (SocketException e) { log.error("Cannot open socket", e); throw Throwables.propagate(e); } }
Source:
<code>public JobInstance() { String jobInstIdSuffix = System.getProperty(PARAM_JOB_INST_ID); <START> if (jobInstIdSuffix == null) { <END> jobInstIdSuffix = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; } jobInstanceId = IpUtils.getIp() + DELIMITER + jobInstIdSuffix; }</code><technical_language>Constant is left. suggestion if (null == jobInstIdSuffix) {</technical_language>

Target:
public JobInstance() { String jobInstanceIdSuffix = System.getProperty(PROPERTY_JOB_INSTANCE_ID); if (null == jobInstanceIdSuffix) { jobInstanceIdSuffix = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; } jobInstanceId = IpUtils.getIp() + DELIMITER + jobInstanceIdSuffix; }
Source:
<code>public static void parse(String path) { try { <START> FileInputStream inputStream = new FileInputStream(path); <END> OsInfoParser parser = new OsInfoParser(inputStream); parser.parse(); } catch (FileNotFoundException e) { throw new RuntimeException("osinfo properties file cannot be found"); } catch (ParseException e) { int line = e.currentToken.beginLine; int charPositionInLine = e.currentToken.beginColumn; String msg = e.getMessage(); throw new RuntimeException("osinfo properties syntax error: " + ("line " + line + ":" + charPositionInLine + " " + msg)); } }</code><technical_language>please try-with-resources notation</technical_language>

Target:
public static void parse(String path) { try (FileInputStream inputStream = new FileInputStream(path)) { OsInfoParser parser = new OsInfoParser(inputStream); parser.parse(); } catch (FileNotFoundException e) { throw new RuntimeException("osinfo properties file cannot be found"); } catch (IOException e) { throw new RuntimeException("error while reading osinfo properties file"); } catch (ParseException e) { throw new RuntimeException( String.format( "osinfo properties syntax error: %s: %d, %d: error: %s", path, e.currentToken.beginLine, e.currentToken.beginColumn, e.getMessage() ), e ); } }
Source:
<code>public DataType getDataTypeByName(String name) { <START> if (name.toLowerCase().equals(COMPLEX_DATA_TYPE_NAME)) { <END> return complexDataType; } return null; }</code><technical_language>need a toLowerCase(ENGLISH) locale-safe</technical_language>

Target:
public DataType getDataTypeByName(String name) { if (name.toLowerCase(Locale.ENGLISH).equals(COMPLEX_DATA_TYPE_NAME)) { return complexDataType; } return null; }
Source:
<code>public static OutputStream checkAndWrap(HttpServletRequest httpRequest, HttpServletResponse httpResponse, boolean requireWantsHeader) throws IOException { OutputStream outputStream = httpResponse.getOutputStream(); boolean acceptsGzip = Collections.list(httpRequest.getHeaders(ACCEPT_ENCODING)).stream().anyMatch(STRING_MATCH); boolean wantGzip = httpResponse.getHeaders(CONTENT_ENCODING).contains(GZIP); if (acceptsGzip) { if (wantGzip || !requireWantsHeader) { <START> outputStream = new GZIPOutputStream(outputStream, true); <END> } } return outputStream; }</code><technical_language>Name</technical_language>

Target:
public static OutputStream checkAndWrap(HttpServletRequest httpRequest, HttpServletResponse httpResponse, boolean requireWantsHeader) throws IOException { OutputStream responseStream = httpResponse.getOutputStream(); boolean acceptsGzip = Collections.list(httpRequest.getHeaders(ACCEPT_ENCODING)).stream().anyMatch(STRING_MATCH); boolean wantGzip = httpResponse.getHeaders(CONTENT_ENCODING).contains(GZIP); if (acceptsGzip) { if (!requireWantsHeader || wantGzip) { responseStream = new GZIPOutputStream(responseStream, true); } } return responseStream; }
Source:
<code>public VariableMappingExpressionEvaluatorWrapper(IExpressionEvaluator wrapped, Map<PVariable, PVariable> variableMapping) { this.wrapped = wrapped; <START> <END> this.variableMapping = Maps.newLinkedHashMap(); Map<String, PVariable> names = Maps.newHashMap(); for (PVariable originalVar : variableMapping.keySet()) { names.put(originalVar.getName(), originalVar); } for (String inputParameterName : wrapped.getInputParameterNames()) { PVariable original = names.get(inputParameterName); if (original != null){ PVariable mapped = variableMapping.get(original); if (mapped != null){ this.variableMapping.put(inputParameterName, mapped.getName()); } } } }</code><technical_language>Performance improvement idea: If wrapped instanceof VariableMappingExpressionEvaluatorWrapper, squash layers making this.wrapped = wrapped.wrapped composing variable mapping computed wrapped.variableMapping. point if apply copier (creating a copy of a copy of a copy etc.), end a cascade of wrappers, coming (admittedly small) performance penalty felt time evaluator is called compute result for a tuple. suggestion bring a huge improvement, again, is pretty simple do, I prefer that. is critical</technical_language>

Target:
public VariableMappingExpressionEvaluatorWrapper(IExpressionEvaluator wrapped, Map<PVariable, PVariable> variableMapping) { boolean rewrap = wrapped instanceof VariableMappingExpressionEvaluatorWrapper; this.wrapped = rewrap ? ((VariableMappingExpressionEvaluatorWrapper)wrapped).wrapped : wrapped; this.variableMapping = Maps.newLinkedHashMap(); Map<String, PVariable> names = Maps.newHashMap(); for (PVariable originalVar : variableMapping.keySet()) { names.put(originalVar.getName(), originalVar); } Map<String, String> previousMapping = null; if (rewrap){ previousMapping = ((VariableMappingExpressionEvaluatorWrapper)wrapped).variableMapping; } for (String inputParameterName : this.wrapped.getInputParameterNames()) { String parameterName = rewrap ? previousMapping.get(inputParameterName) : inputParameterName; Preconditions.checkArgument(parameterName != null); PVariable original = names.get(parameterName); Preconditions.checkArgument(original != null); PVariable mapped = variableMapping.get(original); if (mapped != null){ this.variableMapping.put(inputParameterName, mapped.getName()); } } }
Source:
<code>public ItemsFilter(SearchPattern searchPattern) { patternMatcher = searchPattern; String stringPattern = ""; <START> if (pattern != null && !pattern.getText().equals("*")) { END> stringPattern = pattern.getText(); } if (stringPattern.indexOf("*") != 0 && stringPattern.indexOf("?") != 0 && stringPattern.indexOf(".") != 0) { stringPattern = "*" + stringPattern; } patternMatcher.setPattern(stringPattern); }</code><technical_language>do check "*" twice, a lines below</technical_language>

Target:
public ItemsFilter(SearchPattern searchPattern) { patternMatcher = searchPattern; String stringPattern = ""; if (pattern != null) { stringPattern = pattern.getText(); } if (!stringPattern.startsWith("*") && !stringPattern.startsWith("?") && !stringPattern.startsWith(".")) { stringPattern = "*" + stringPattern; } patternMatcher.setPattern(stringPattern); }
Source:
<code>public DiagnosticsReportSource heapDump() { return new DiagnosticsReportSource() { @Override public String destinationPath() { return "heapdump.hprof"; } @Override public void addToArchive( Path archiveDestination, DiagnosticsReporterProgressInteractions progress ) throws IOException { progress.info( "dumping..." ); Path tempFile = Files.createTempFile("neo4j-heapdump", ".hprof"); Files.deleteIfExists( tempFile ); heapDump( tempFile.toAbsolutePath().toString() ); progress.info( "archiving..." ); long size = Files.size( tempFile ); InputStream in = Files.newInputStream( tempFile ); try ( ProgressAwareInputStream inStream = new ProgressAwareInputStream( in, size, progress::percentChanged ) ) { Files.copy( inStream, archiveDestination ); } Files.delete( tempFile ); } @Override public long estimatedSize( DiagnosticsReporterProgressInteractions progress ) { try { MemoryMXBean bean = ManagementFactory.getPlatformMXBean( mBeanServer, MemoryMXBean.class ); long totalMemory = bean.getHeapMemoryUsage().getCommitted() + bean.getNonHeapMemoryUsage().getCommitted(); return (long) (totalMemory * 1.2); } catch ( IOException e ) { <START> progress.error( "Unable to determine size of neo4j instance memory", e ); <END> } return 0; } }; }</code><technical_language>note: throw exception instead</technical_language>

Target:
public DiagnosticsReportSource heapDump() { return new DiagnosticsReportSource() { @Override public String destinationPath() { return "heapdump.hprof"; } @Override public void addToArchive( Path archiveDestination, DiagnosticsReporterProgress progress ) throws IOException { progress.info( "dumping..." ); Path tempFile = Files.createTempFile("neo4j-heapdump", ".hprof"); Files.deleteIfExists( tempFile ); heapDump( tempFile.toAbsolutePath().toString() ); progress.info( "archiving..." ); long size = Files.size( tempFile ); InputStream in = Files.newInputStream( tempFile ); try ( ProgressAwareInputStream inStream = new ProgressAwareInputStream( in, size, progress::percentChanged ) ) { Files.copy( inStream, archiveDestination ); } Files.delete( tempFile ); } @Override public long estimatedSize( DiagnosticsReporterProgress progress ) throws IOException { MemoryMXBean bean = ManagementFactory.getPlatformMXBean( mBeanServer, MemoryMXBean.class ); long totalMemory = bean.getHeapMemoryUsage().getCommitted() + bean.getNonHeapMemoryUsage().getCommitted(); return (long) (totalMemory * 1.2); } }; }