auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public int makeCube(Vector pos, Pattern block, int length, int height, int width, boolean filled) throws MaxChangedBlocksException { int affected = 0; length--; width--; height--; <START> filled=(filled || length == 0 || height == 0 || width == 0); <END> pos=pos.subtract(length/2, height/2, width/2); for(int x = 0; x <= length; ++x) for(int y = 0; y <= height; ++y) for(int z = 0; z <= width; ++z) if((filled || ( x%length == 0 || y%height == 0 || z%width == 0)) && setBlock(pos.add(x,y,z),block)) affected++; return affected; }</code><technical_language>assignment operators this java var = val; in this case: java filled = (filled || length == 0 || height == 0 || width == 0);</technical_language>

Target:
public int makeCube(Vector pos, Pattern block, int length, int height, int width, boolean filled) throws MaxChangedBlocksException { int affected = 0; length--; width--; height--; filled = (filled || length == 0 || height == 0 || width == 0); pos=pos.subtract(length/2, height/2, width/2); for(int x = 0; x <= length; ++x) { for (int y = 0; y <= height; ++y) { for (int z = 0; z <= width; ++z) { if ((filled || (x % length == 0 || y % height == 0 || z % width == 0)) && setBlock(pos.add(x, y, z), block)) { affected++; } } } } return affected; }
Source:
<code>public void selectAnnotation(RCTMGLPointAnnotation annotation) { final long id = annotation.getMapboxID(); if (id != mActiveMarkerID) { final MarkerView markerView = annotation.getMarker(); String title = annotation.getTitle(); String snippet = annotation.getSnippet(); annotation.onSelect(true); mActiveMarkerID = id; RCTMGLCallout calloutView = annotation.getCalloutView(); <START> if (title != null || snippet !== null || (!markerView.isInfoWindowShown() && calloutView != null)) { <END> mMap.selectMarker(markerView); } if (!markerView.isInfoWindowShown() && calloutView != null) { markerView.showInfoWindow(mMap, this); } } }</code><technical_language>I instead of this annotation.getCalloutView return null if a title. do think</technical_language>

Target:
public void selectAnnotation(RCTMGLPointAnnotation annotation) { final long id = annotation.getMapboxID(); if (id != mActiveMarkerID) { final MarkerView markerView = annotation.getMarker(); annotation.onSelect(true); mActiveMarkerID = id; if (!markerView.isInfoWindowShown() && annotation.hasInfoWindow()) { mMap.selectMarker(markerView); } } }
Source:
<code>public boolean isEmailValid(String email) { if (StringUtils.isBlank(email)) { return true; } <START> <END> Matcher matcher = EMAIL_PATTERN.matcher(email); return matcher.matches(); }</code><technical_language>combine 2 lines 1</technical_language>

Target:
private boolean isEmailValid(String email) { return EmailValidator.getInstance().isValid(email); }
Source:
<code>public static Properties defaultProperties() { System.setProperty(TTL_MIN_IN_SEC, "60"); System.setProperty(TTL_MAX_IN_SEC, "1209600"); System.setProperty(MESSAGE_MAX, "20"); <START> System.setProperty(MESSAGE_BODY_MAX_IN_BYTES, "262144"); <END> Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(SERVICE_TYPE, ServiceType.QUEUES); properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS); return properties; }</code><technical_language>Do do this else? reason in System</technical_language>

Target:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(SERVICE_TYPE, ServiceType.QUEUES); properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS); return properties; }
Source:
<code>@Test public void shouldHandleSchemeInsensitiveCase() { String[] schemes = { "http", "https", "HTTP", "HTTPS", "HTtP", }; for (String scheme : schemes) { final Uri uri = URI_1.buildUpon().scheme(scheme).build(); final Boolean shouldHandle = networkHandler.canHandleRequest( <START> TestUtils.mockRequest(uri) <END> ); assertThat(shouldHandle).isTrue(); } }</code><technical_language>inline mockRequest for tests, opinionated here</technical_language>

Target:
@Test public void shouldHandleSchemeInsensitiveCase() { String[] schemes = { "http", "https", "HTTP", "HTTPS", "HTtP", }; for (String scheme : schemes) { Uri uri = URI_1.buildUpon().scheme(scheme).build(); assertThat(networkHandler.canHandleRequest(TestUtils.mockRequest(uri))).isTrue(); } }
Source:
<code>public void should_handle_set_tracing_without_args() { NullStatementBuilder builder = new NullStatementBuilder(); <START> assertFalse(builder.tracing); <END> builder.setTracing(); assertTrue(builder.tracing); }</code><technical_language>Nit: prefer AssertJ for assertions. import static com.datastax.oss.driver.Assertions.assertThat; ... assertThat(builder.tracing).isFalse() a huge difference for a simple boolean, for more complex types collections more expressive</technical_language>

Target:
public void should_handle_set_tracing_without_args() { NullStatementBuilder builder = new NullStatementBuilder(); assertThat(builder.tracing).isFalse(); builder.setTracing(); assertThat(builder.tracing).isTrue(); }
Source:
<code>private QueryStatus getQueryStatus(MetricSpecification query, Buckets<IHasShortcut> buckets) { MetricKey key = MetricKey.fromValue(query); QueryStatus result = buckets.getQueryStatus(key); if (null == result) { <START> result = new QueryStatus(QueryStatus.QueryStatusEnum.UNKNOWN, String.format("Query status lookup failed for query %s", query.toString())); <END> } return result; }</code><technical_language>query status string friendlier</technical_language>

Target:
private QueryStatus getQueryStatus(MetricSpecification query, Buckets<IHasShortcut> buckets) { MetricKey key = MetricKey.fromValue(query); QueryStatus result = buckets.getQueryStatus(key); if (null == result) { result = new QueryStatus(QueryStatus.QueryStatusEnum.UNKNOWN, String.format("Unknown query status for query %s", query.toString())); } return result; }
Source:
<code>private void checkRepMigrationEffect(DAnalysis analysis) { DRepresentation dView = analysis.getOwnedViews().get(0).getOwnedRepresentations().get(0); <START> if (dView instanceof DDiagram) { <END> DDiagram diagram = (DDiagram) dView; FilterVariableHistory filterVariableHistory = diagram.getFilterVariableHistory(); EList<VariableValue> ownedValues = filterVariableHistory.getOwnedValues(); VariableValue variableValue = ownedValues.get(0); assertTrue("FilterVariableHistory.ownedValues should be of type EObjectVariableValue", variableValue instanceof EObjectVariableValue); EObjectVariableValue objectValue = (EObjectVariableValue) variableValue; EObject modelElement = objectValue.getModelElement(); assertNotNull("EObjectVariableValue.modelElement is not set", modelElement); SelectModelElementVariable variableDefinition = objectValue.getVariableDefinition(); assertNotNull("EObjectVariableValue.variableDefinition is not set", variableDefinition); } }</code><technical_language>assertTrue(dView instanceof DDiagram); instead asserts checked</technical_language>

Target:
private void checkRepMigrationEffect(DAnalysis analysis) { DRepresentation dView = analysis.getOwnedViews().get(0).getOwnedRepresentations().get(0); assertTrue("DRepresentation " + dView.getName() + " is not a DDiagram", dView instanceof DDiagram); if (dView instanceof DDiagram) { DDiagram diagram = (DDiagram) dView; FilterVariableHistory filterVariableHistory = diagram.getFilterVariableHistory(); EList<VariableValue> ownedValues = filterVariableHistory.getOwnedValues(); VariableValue variableValue = ownedValues.get(0); assertTrue("FilterVariableHistory.ownedValues should be of type EObjectVariableValue", variableValue instanceof EObjectVariableValue); EObjectVariableValue objectValue = (EObjectVariableValue) variableValue; EObject modelElement = objectValue.getModelElement(); assertNotNull("EObjectVariableValue.modelElement is not set", modelElement); SelectModelElementVariable variableDefinition = objectValue.getVariableDefinition(); assertNotNull("EObjectVariableValue.variableDefinition is not set", variableDefinition); } }
Source:
<code>public long[] findJoinAddresses(int probePosition, Page probe, int probeGeometryChannel) { Block probeGeometryBlock = probe.getBlock(probeGeometryChannel); if (probeGeometryBlock.isNull(probePosition)) { return EMPTY_ADDRESSES; <START> } <END> Slice slice = probeGeometryBlock.getSlice(probePosition, 0, probeGeometryBlock.getSliceLength(probePosition)); OGCGeometry probeGeometry = deserialize(slice); if (probeGeometry.isEmpty()) { return EMPTY_ADDRESSES; } LongArrayList matchingAddresses = new LongArrayList(); Envelope envelope = getEnvelope(probeGeometry); rtree.query(envelope, o -> { GeometryWithAddress geometryWithAddress = (GeometryWithAddress) o; if (spatialRelationshipTest.test(geometryWithAddress.getOgcGeometry(), probeGeometry)) { matchingAddresses.add(geometryWithAddress.address); } }); return matchingAddresses.toLongArray(null); }</code><technical_language>I deserialize return null. probeGeometry null all? If no, want verify it</technical_language>

Target:
public long[] findJoinAddresses(int probePosition, Page probe, int probeGeometryChannel) { Block probeGeometryBlock = probe.getBlock(probeGeometryChannel); if (probeGeometryBlock.isNull(probePosition)) { return EMPTY_ADDRESSES; } Slice slice = probeGeometryBlock.getSlice(probePosition, 0, probeGeometryBlock.getSliceLength(probePosition)); OGCGeometry probeGeometry = deserialize(slice); verify(probeGeometry != null); if (probeGeometry.isEmpty()) { return EMPTY_ADDRESSES; } LongArrayList matchingAddresses = new LongArrayList(); Envelope envelope = getEnvelope(probeGeometry); rtree.query(envelope, item -> { GeometryWithAddress geometryWithAddress = (GeometryWithAddress) item; if (spatialRelationshipTest.test(geometryWithAddress.ogcGeometry, probeGeometry)) { matchingAddresses.add(geometryWithAddress.address); } }); return matchingAddresses.toLongArray(null); }
Source:
<code>protected void doInitialize() { final Flow flow = getLoginFlow(); if (flow != null) { createClientActionActionState(flow); createStopWebflowViewState(flow); createSaml2ClientLogoutAction(); <START> createAuthnFailureAction(flow); <END> } }</code><technical_language>createAuthnFailureActionState</technical_language>

Target:
protected void doInitialize() { final Flow flow = getLoginFlow(); if (flow != null) { createClientActionActionState(flow); createStopWebflowViewState(flow); createSaml2ClientLogoutAction(); createAuthnFailureActionState(flow); } }
Source:
<code>private static boolean isConfirmedKeyword(String userInput, int keywordIndex) { <START> return !(keywordIndex == userInput.split("\\s+").length - 1 && !userInput.endsWith(" ")); <END> }</code><technical_language>I return keywordIndex != userInput.split("\\s+").length - 1 || userInput.endsWith(" "); easier for read code is doing</technical_language>

Target:
private static boolean isConfirmedKeyword(String userInput, int keywordIndex) { return keywordIndex != userInput.split("\\s+").length - 1 || userInput.endsWith(" "); }
Source:
<code>private void checkJunit4AndAboveTestClass(IdentifierTree className, JavaSymbol.TypeJavaSymbol symbol, Iterable<Symbol> members) { <START> if (symbol.name().endsWith("Test") && !runWithRunner(symbol)) { <END> checkMethods(className, members, true); } }</code><technical_language>@m-g-sonar runWithRunner this name is a bit funny :)</technical_language>

Target:
private void checkJunit4AndAboveTestClass(IdentifierTree className, JavaSymbol.TypeJavaSymbol symbol, Iterable<Symbol> members) { if (symbol.name().endsWith("Test") && !runWithEnclosedOrCucumberRunner(symbol)) { checkMethods(className, members, true); } }
Source:
<code>@Test public void ContainsNonComparableKeyReturnsFalse() { LinkedHashTreeMap<String, String> map = new LinkedHashTreeMap<>(); map.put("a", "android"); <START> assertThat(map.containsKey(new Object())).isFalse(); <END> }</code><technical_language>assertThat(map).doesNotContainKey(new Object());</technical_language>

Target:
@Test public void ContainsNonComparableKeyReturnsFalse() { LinkedHashTreeMap<Object, String> map = new LinkedHashTreeMap<>(); map.put("a", "android"); assertThat(map).doesNotContainKey(new Object()); }
Source:
<code>public static boolean isWater(final BlockData data) { <START> return (data instanceof Waterlogged) ? ((Waterlogged) data).isWaterlogged() : false; <END> }</code><technical_language>In opinion, type check well. change false isWater(data.getType())</technical_language>

Target:
public static boolean isWater(final BlockData data) { return (data instanceof Waterlogged) ? ((Waterlogged) data).isWaterlogged() : isWater(data.getMaterial()); }
Source:
<code><START> public String placeMarketOrder(MarketOrder marketOrder) throws IOException { <END> try { LgoUnencryptedOrder lgoOrder = LgoAdapters.adaptUnencryptedMarketOrder(marketOrder); return placeLgoUnencryptedOrder(lgoOrder); } catch (LgoException e) { throw LgoErrorAdapter.adapt(e); } }</code><technical_language>is sending unencrypted order default better</technical_language>

Target:
public String placeMarketOrder(MarketOrder marketOrder) throws IOException { if (shouldEncryptOrders) { return placeEncryptedMarketOrder(marketOrder); } return placeUnencryptedMarketOrder(marketOrder); }
Source:
<code>private String encodedPayload(String payload, String payloadId, ClaimSet claimSet) throws Exception { ObjectNode _claimSet = JsonNodeFactory.instance.objectNode(); <START> ObjectNode _payload = JsonNodeFactory.instance.objectNode();; <END> _payload.put(payloadId, payload); if(claimSet != null) { if(claimSet.getExp() > 0) { _claimSet.put("exp", claimSet.getExp()); } _payload.putAll(_claimSet); } return base64UrlEncode(_payload.toString().getBytes()); }</code><technical_language>remove additional ;. Also, remove local variables starting _. Thanks</technical_language>

Target:
private String encodedPayload(String payload, String payloadId, ClaimSet claimSet) throws Exception { ObjectNode localClaimSet = JsonNodeFactory.instance.objectNode(); ObjectNode localPayload = JsonNodeFactory.instance.objectNode(); localPayload.put(payloadId, payload); if(claimSet != null) { if(claimSet.getExp() > 0) { localClaimSet.put("exp", claimSet.getExp()); } localPayload.putAll(localClaimSet); } return base64UrlEncode(localPayload.toString().getBytes()); }
Source:
<code>public void readData(ObjectDataInput in) throws IOException { port = in.readInt(); type = in.readByte(); host = in.readUTF(); <START> socketAddr = new InetSocketAddress(InetAddress.getByName(host), port); <END> }</code><technical_language>affect performance if do frequent DNS requests here. frequent in fact</technical_language>

Target:
public void readData(ObjectDataInput in) throws IOException { port = in.readInt(); type = in.readByte(); host = in.readUTF(); inetAddress = InetAddress.getByAddress(in.readByteArray()); }
Source:
<code>public String getInput(String input) { <START> String content = HttpUtil.executeUrl(GET, createURL() <END> + "/" + XML_PATH + "?" + SUFFIX_PASSWORD + getPassword(), this.timeOut); content = XmlUtils.getContentOfElement(content, input); int status = Integer.parseInt(XmlUtils.getContentOfElement(content, "Value")); if(status == 1) { return "OPEN"; } else { return "CLOSED"; } }</code><technical_language>Please extrace generated url a variable calling HttpUtil.executeUrl(), this debugging easier</technical_language>

Target:
public String getInput(String input) { String URL = createURL() + "/" + XML_PATH + "?" + SUFFIX_PASSWORD + getPassword(); String content = HttpUtil.executeUrl(GET, URL, this.timeOut); content = XmlUtils.getContentOfElement(content, input); int status = Integer.parseInt(XmlUtils.getContentOfElement(content, "Value")); if(status == 1) { return "OPEN"; } else { return "CLOSED"; } }
Source:
<code>protected Optional<SecretSeries> getSecretSeriesFor(Client client, String name) { Record r = dslContext .select(SECRETS.ID, SECRETS.NAME, SECRETS.DESCRIPTION, SECRETS.CREATEDAT, SECRETS.CREATEDBY, SECRETS.UPDATEDAT, SECRETS.UPDATEDBY, SECRETS.TYPE, SECRETS.OPTIONS) .from(SECRETS) .join(SECRETS_CONTENT).on(SECRETS.ID.eq(SECRETS_CONTENT.SECRETID)) .join(ACCESSGRANTS).on(SECRETS.ID.eq(ACCESSGRANTS.SECRETID)) .join(MEMBERSHIPS).on(ACCESSGRANTS.GROUPID.eq(MEMBERSHIPS.GROUPID)) .join(CLIENTS).on(CLIENTS.ID.eq(MEMBERSHIPS.CLIENTID)) .where(SECRETS.NAME.eq(name).and(CLIENTS.NAME.eq(client.getName()))) .fetchOne(); <START> if (r != null) { <END> return Optional.of(r.map(new SecretSeriesJooqMapper())); } return Optional.empty(); }</code><technical_language>do return Optional.ofNullable(r) .map((rec) -> rec.map(new SecretSeriesJooqMapper()));</technical_language>

Target:
protected Optional<SecretSeries> getSecretSeriesFor(Client client, String name) { Record r = dslContext .select(SECRETS.ID, SECRETS.NAME, SECRETS.DESCRIPTION, SECRETS.CREATEDAT, SECRETS.CREATEDBY, SECRETS.UPDATEDAT, SECRETS.UPDATEDBY, SECRETS.TYPE, SECRETS.OPTIONS) .from(SECRETS) .join(SECRETS_CONTENT).on(SECRETS.ID.eq(SECRETS_CONTENT.SECRETID)) .join(ACCESSGRANTS).on(SECRETS.ID.eq(ACCESSGRANTS.SECRETID)) .join(MEMBERSHIPS).on(ACCESSGRANTS.GROUPID.eq(MEMBERSHIPS.GROUPID)) .join(CLIENTS).on(CLIENTS.ID.eq(MEMBERSHIPS.CLIENTID)) .where(SECRETS.NAME.eq(name).and(CLIENTS.NAME.eq(client.getName()))) .fetchOne(); return Optional.ofNullable(r).map( (rec) -> rec.map(new SecretSeriesJooqMapper())); }
Source:
<code>protected Set<Value.Immutable<?>> api$getVanillaValues() { final Set<Value.Immutable<?>> vanillaValues = super.api$getVanillaValues(); <START> if (this.closestEnderCrystal != null) { <END> this.healingCrystal().map(Value::asImmutable).ifPresent(vanillaValues::add); } return vanillaValues; }</code><technical_language>eliminate if statement ifPresent redundantly add this</technical_language>

Target:
protected Set<Value.Immutable<?>> api$getVanillaValues() { final Set<Value.Immutable<?>> values = super.api$getVanillaValues(); values.add(this.bossBar().asImmutable()); this.healingCrystal().map(Value::asImmutable).ifPresent(values::add); return values; }
Source:
<code>public String toString() { return String.format( "%s %d @ %d for %s located at %s", <START> props.getCheckpointType(), <END> checkpointID, timestamp, job, externalPointer); }</code><technical_language>Currently display: "CHECKPOINT" "SAVEPOINT" "SYNC_SAVEPOINT" proposing translate "Checkpoint" "Savepoint" reduce technicality. However, strong feelings, convince leave is</technical_language>

Target:
public String toString() { return String.format( "%s %d @ %d for %s located at %s", props.getCheckpointType().getName(), checkpointID, timestamp, job, externalPointer); }
Source:
<code>AllProjectsCreator( GitRepositoryManager mgr, AllProjectsName allProjectsName, @GerritPersonIdent PersonIdent serverUser) { this.mgr = mgr; this.allProjectsName = allProjectsName; this.serverUser = serverUser; this.anonymous = new GroupReference( AccountGroup.ANONYMOUS_USERS, <START> "Anonymous Users"); <END> this.anonymous = new GroupReference( AccountGroup.REGISTERED_USERS, "Registered Users"); this.owners = new GroupReference( AccountGroup.PROJECT_OWNERS, "Project Owners"); }</code><technical_language>This is bug. I overwrite anonymous Registered Users</technical_language>

Target:
AllProjectsCreator( GitRepositoryManager mgr, AllProjectsName allProjectsName, @GerritPersonIdent PersonIdent serverUser) { this.mgr = mgr; this.allProjectsName = allProjectsName; this.serverUser = serverUser; this.anonymous = new GroupReference( AccountGroup.ANONYMOUS_USERS, "Anonymous Users"); this.registered = new GroupReference( AccountGroup.REGISTERED_USERS, "Registered Users"); this.owners = new GroupReference( AccountGroup.PROJECT_OWNERS, "Project Owners"); }
Source:
<code>public void beginTree(DetailAST rootAST) { classes = new ArrayDeque<>(); <START> superClasses = new HashSet<>(); <END> packageName = ""; }</code><technical_language>Please move new instances field's declaration. Change 2 lines clear</technical_language>

Target:
public void beginTree(DetailAST rootAST) { classes.clear(); superClasses.clear(); packageName = ""; }
Source:
<code>public List<VDS> filter(List<VDS> hosts, VM vm, Map<String, String> parameters, List<String> messages) { List<VDS> toRemoveHostList = new ArrayList<VDS>(); List<VmNetworkInterface> vmNICs; List<Network> clusterNetworks; Map<String, Network> networksByName; if (hosts != null && hosts.size() > 0) { clusterNetworks = getNetworkDAO().getAllForCluster(hosts.get(0).getVdsGroupId()); networksByName = Entities.entitiesByName(clusterNetworks); vmNICs = getVmNetworkInterfaceDao().getAllForVm(vm.getId()); } else { return null; } Map<Guid, List<String>> hostNics = <START> getInterfaceDAO().getHostNetworksByCluster(hosts.get(0).getVdsGroupId()); <END> for (VDS host : hosts) { VdcBllMessages returnValue = validateRequiredNetworksAvailable(host, vm, vmNICs, clusterNetworks, networksByName, hostNics.get(host.getId())); if (VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_NETWORKS == returnValue) { StringBuilder sbBuilder = new StringBuilder(); sbBuilder.append(Entities.vmInterfacesByNetworkName(vmNICs).keySet()); log.debugFormat("host {0} is missing networks required by VM nics {1}", host.getName(), sbBuilder.toString()); } else if (VdcBllMessages.ACTION_TYPE_FAILED_MISSING_DISPLAY_NETWORK == returnValue) { log.debugFormat("host {0} is missing the cluster's display network", host.getName()); } if (returnValue != null) { messages.add(returnValue.toString()); toRemoveHostList.add(host); } } hosts.removeAll(toRemoveHostList); return hosts; }</code><technical_language>hosts.get(0).getVdsGroupId() is called couple of times, i extracting local parameter "clusterId" ease understanding code</technical_language>

Target:
public List<VDS> filter(List<VDS> hosts, VM vm, Map<String, String> parameters, List<String> messages) { List<VDS> toRemoveHostList = new ArrayList<VDS>(); List<VmNetworkInterface> vmNICs; List<Network> clusterNetworks; Map<String, Network> networksByName; Guid clusterId = null; if (hosts != null && hosts.size() > 0) { clusterId = hosts.get(0).getVdsGroupId(); clusterNetworks = getNetworkDAO().getAllForCluster(clusterId); networksByName = Entities.entitiesByName(clusterNetworks); vmNICs = getVmNetworkInterfaceDao().getAllForVm(vm.getId()); } else { return null; } Map<Guid, List<String>> hostNics = getInterfaceDAO().getHostNetworksByCluster(clusterId); for (VDS host : hosts) { VdcBllMessages returnValue = validateRequiredNetworksAvailable(host, vm, vmNICs, clusterNetworks, networksByName, hostNics.get(host.getId())); if (VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_NETWORKS == returnValue) { StringBuilder sbBuilder = new StringBuilder(); sbBuilder.append(Entities.vmInterfacesByNetworkName(vmNICs).keySet()); log.debugFormat("host {0} is missing networks required by VM nics {1}", host.getName(), sbBuilder.toString()); } else if (VdcBllMessages.ACTION_TYPE_FAILED_MISSING_DISPLAY_NETWORK == returnValue) { log.debugFormat("host {0} is missing the cluster's display network", host.getName()); } if (returnValue != null) { messages.add(returnValue.toString()); toRemoveHostList.add(host); } } hosts.removeAll(toRemoveHostList); return hosts; }
Source:
<code>public Fragment getItem(int position) { <START> return fragments[position]; <END> }</code><technical_language>Please create new fragments instead of array. Fragments created deleted system. Maintaining a list of fragments next developer access list (which result in invalid state)</technical_language>

Target:
public Fragment getItem(int position) { if (position == 0) { return new PlaybackStatisticsFragment(); } else { return new DownloadStatisticsFragment(); } }
Source:
<code>private void getQueryQuotaEnabledFlagFromInstanceConfig() { Map<String, String> instanceConfigsMap = HelixHelper.getInstanceConfigsMapFor(_instanceId, _helixManager.getClusterName(), _helixManager.getClusterManagmentTool()); String queryQuotaEnabled = instanceConfigsMap.getOrDefault(CommonConstants.Helix.QUERY_QUOTA_STATE_ENABLED, "true"); _enabled = Boolean.parseBoolean(queryQuotaEnabled); <START> LOGGER.info("Set query quota state to: for tables in the current broker.", _enabled ? "ENABLE" : "DISABLE", <END> _rateLimiterMap.size()); }</code><technical_language>suggestion LOGGER.info("Set query rate limiting to: for tables in this broker.", _enabled ? "ENABLED" : "DISABLED",</technical_language>

Target:
private void getQueryQuotaEnabledFlagFromInstanceConfig() { try { Map<String, String> instanceConfigsMap = HelixHelper.getInstanceConfigsMapFor(_instanceId, _helixManager.getClusterName(), _helixManager.getClusterManagmentTool()); String queryRateLimitDisabled = instanceConfigsMap.getOrDefault(CommonConstants.Helix.QUERY_RATE_LIMIT_DISABLED, "false"); _queryRateLimitDisabled = Boolean.parseBoolean(queryRateLimitDisabled); LOGGER.info("Set query rate limiting to: for all tables in this broker.", _queryRateLimitDisabled ? "DISABLED" : "ENABLED", _rateLimiterMap.size()); } catch (ZkNoNodeException e) { _queryRateLimitDisabled = false; } _brokerMetrics.setValueOfGlobalGauge(BrokerGauge.QUERY_RATE_LIMIT_DISABLED, _queryRateLimitDisabled ? 1L : 0L); }
Source:
<code>public Reply<?> assignServiceProviders(@Named("id")Object id, Request request) { <START> List<Object> dtos = request.read(new TypeLiteral<List<Object>>() {}).as(Json.class); <END> List<ID> spIDs = adaptToIDs(dtos); repository.assignServiceProviders(new ID(id), spIDs); return Reply.saying().ok(); }</code><technical_language>TypeLiteral is unnecessary a simple List</technical_language>

Target:
public Reply<?> assignServiceProviders(@Named("id")Object id, Request request) { List dtos = request.read(List.class).as(Json.class); List<ID> spIDs = adaptToIDs(dtos); repository.assignServiceProviders(new ID(id), spIDs); return Reply.saying().ok(); }
Source:
<code>private static void execute(WorkCenter workCenter, TaskSet taskSet) throws InterruptedException { List<Worker> workers = workCenter.getWorkers(); var exec = Executors.newFixedThreadPool(workers.size()); <START> for (var worker : workers) { exec.submit(worker); } <END> Thread.sleep(1000); addTasks(taskSet); exec.awaitTermination(2, TimeUnit.SECONDS); exec.shutdownNow(); }</code><technical_language>streams instead of for loop</technical_language>

Target:
private static void execute(WorkCenter workCenter, TaskSet taskSet) throws InterruptedException { var workers = workCenter.getWorkers(); var exec = Executors.newFixedThreadPool(workers.size()); workers.forEach(exec::submit); Thread.sleep(1000); addTasks(taskSet); exec.awaitTermination(2, TimeUnit.SECONDS); exec.shutdownNow(); }
Source:
<code>public boolean preFinish(TaskRepository repository) { <START> TaskRepository newRepository = createTaskRepository(); <END> boolean propertiesUnchanged = false; if (validatedTaskRepository != null) { propertiesUnchanged = equalsProperties(validatedTaskRepository.getProperties(), newRepository.getProperties()); if (propertiesUnchanged) { for (AuthenticationType authenticationType : AuthenticationType.values()) { AuthenticationCredentials credentialsOld = validatedAuthenticationCredentials.get(authenticationType); AuthenticationCredentials credentialsNew = newRepository.getCredentials(authenticationType); if (credentialsOld != null) { propertiesUnchanged = credentialsOld.equals(credentialsNew); if (!propertiesUnchanged) { break; } } else if (credentialsNew != null) { propertiesUnchanged = false; break; } } } } if (validateOnFinishButton != null && validateOnFinishButton.getSelection() && !propertiesUnchanged) { isValid = false; validateSettings(); } else { isValid = true; } if (isValid) { isValid = super.preFinish(repository); } return isValid; }</code><technical_language>comparison in a separate protected method overridden subclasses</technical_language>

Target:
public boolean preFinish(TaskRepository repository) { if (validateOnFinishButton != null && validateOnFinishButton.getSelection() && !propertiesUnchanged()) { isValid = false; validateSettings(); } else { isValid = true; } if (isValid) { isValid = super.preFinish(repository); } return isValid; }
Source:
<code>private void createChildren() { DetailAST currentChild = detailAst.getFirstChild(); while (currentChild != null) { <START> final ElementNode child = new ElementNode(root, this, currentChild); <END> addChild(child); currentChild = currentChild.getNextSibling(); } }</code><technical_language>AbstractNode instead of ElementNode? need iterfaces abstract classes possible</technical_language>

Target:
private void createChildren() { DetailAST currentChild = detailAst.getFirstChild(); while (currentChild != null) { final AbstractNode child = new ElementNode(root, this, currentChild); addChild(child); currentChild = currentChild.getNextSibling(); } }
Source:
<code>public void onDone() { <START> if (ReadText.getmQuestionAnswer() == Sound.SOUNDS_QUESTION) { <END> long delay = mWaitAnswerSecond * 1000; if (delay > 0) { mTimeoutHandler.postDelayed(mShowAnswerTask, delay); } } else if (ReadText.getmQuestionAnswer() == Sound.SOUNDS_ANSWER) { long delay = mWaitQuestionSecond * 1000; if (delay > 0) { mTimeoutHandler.postDelayed(mShowQuestionTask, delay); } } }</code><technical_language>perform early return if mUseTimer is false</technical_language>

Target:
public void onDone() { if(!mUseTimer) { return; } if (ReadText.getmQuestionAnswer() == Sound.SOUNDS_QUESTION) { long delay = mWaitAnswerSecond * 1000; if (delay > 0) { mTimeoutHandler.postDelayed(mShowAnswerTask, delay); } } else if (ReadText.getmQuestionAnswer() == Sound.SOUNDS_ANSWER) { long delay = mWaitQuestionSecond * 1000; if (delay > 0) { mTimeoutHandler.postDelayed(mShowQuestionTask, delay); } } }
Source:
<code>public static void validateResourcePools(Collection<? extends ResourcePool> pools) { List<SizedResourcePool> ordered = new ArrayList<SizedResourcePool>(pools.size()); for(ResourcePool pool : pools) { if (pool instanceof SizedResourcePool) { ordered.add((SizedResourcePool)pool); } } Collections.sort(ordered, new Comparator<SizedResourcePool>() { @Override public int compare(final SizedResourcePool o1, final SizedResourcePool o2) { int retVal = o2.getType().getTierHeight() - o1.getType().getTierHeight(); <START> if(retVal == 0) { <END> String s1 = o1.toString(); String s2 = o2.toString(); if(s1.compareToIgnoreCase(s2) < 1) { throw new IllegalArgumentException("Tiering Ambiguity: '" + s1 + "' has tier height equal to '" + s2 + "'"); } else { throw new IllegalArgumentException("Tiering Ambiguity: '" + s2 + "' has tier height equal to '" + s1 + "'"); } } else { return retVal; } } }); for (int i = 0; i < ordered.size(); i++) { for (int j = 0; j < i; j++) { SizedResourcePool upper = ordered.get(j); SizedResourcePool lower = ordered.get(i); boolean inversion; try { inversion = (upper.getUnit().compareTo(upper.getSize(), lower.getSize(), lower.getUnit()) >= 0) || (lower.getUnit().compareTo(lower.getSize(), upper.getSize(), upper.getUnit()) <= 0); } catch (IllegalArgumentException e) { inversion = false; } if (inversion) { throw new IllegalArgumentException("Tiering Inversion: '" + upper + "' is not smaller than '" + lower + "'"); } } } }</code><technical_language>This checking for duplicate tier height. I find weird do inline sorting. I do walk sorted list assess tier inversion</technical_language>

Target:
public static void validateResourcePools(Collection<? extends ResourcePool> pools) { List<SizedResourcePool> ordered = new ArrayList<SizedResourcePool>(pools.size()); for(ResourcePool pool : pools) { if (pool instanceof SizedResourcePool) { ordered.add((SizedResourcePool)pool); } } Collections.sort(ordered, new Comparator<SizedResourcePool>() { @Override public int compare(final SizedResourcePool o1, final SizedResourcePool o2) { int retVal = o2.getType().getTierHeight() - o1.getType().getTierHeight(); if(retVal == 0) { return o1.toString().compareTo(o2.toString()); } else { return retVal; } } }); for (int i = 0; i < ordered.size(); i++) { for (int j = 0; j < i; j++) { SizedResourcePool upper = ordered.get(j); SizedResourcePool lower = ordered.get(i); boolean inversion; boolean ambiguity; try { ambiguity = upper.getType().getTierHeight() == lower.getType().getTierHeight(); inversion = (upper.getUnit().compareTo(upper.getSize(), lower.getSize(), lower.getUnit()) >= 0) || (lower.getUnit().compareTo(lower.getSize(), upper.getSize(), upper.getUnit()) <= 0); } catch (IllegalArgumentException e) { ambiguity = false; inversion = false; } if (ambiguity) { throw new IllegalArgumentException("Tiering Ambiguity: '" + upper + "' has the same tier height as '" + lower + "'"); } if (inversion) { throw new IllegalArgumentException("Tiering Inversion: '" + upper + "' is not smaller than '" + lower + "'"); } } } }
Source:
<code>private Integer getMemory(Plan plan) { <START> if (plan.specs() == null || plan.specs().drives() == null) return -1; <END> String total = plan.specs().memory().total(); if (total.endsWith("GB")) { return Integer.valueOf(total.substring(0, total.length() - 2)) * 1024; } else { throw new IllegalArgumentException("Cannot parse memory: " + plan.specs().memory()); } }</code><technical_language>return 0</technical_language>

Target:
private Integer getMemory(Plan plan) { if (plan.specs() == null || plan.specs().drives() == null) return 0; String total = plan.specs().memory().total(); if (total.endsWith("GB")) { return Integer.valueOf(total.substring(0, total.length() - 2)) * 1024; } else { throw new IllegalArgumentException("Cannot parse memory: " + plan.specs().memory()); } }
Source:
<code>private synchronized void initContext(ClientContext ctx, MasterInquireClient masterInquireClient) { mClosed.set(false); mMasterClientContext = MasterClientContext.newBuilder(ctx) .setMasterInquireClient(masterInquireClient).build(); try { InetSocketAddress masterAddr = masterInquireClient.getPrimaryRpcAddress(); mMasterClientContext.loadConf(masterAddr, true, true); } catch (UnavailableException e) { LOG.error("Failed to get master address during initialization", e); } catch (AlluxioStatusException ae) { LOG.error("Failed to load configuration from " + "meta master during initialization", ae); <START> } <END> mFileSystemMasterClientPool = new FileSystemMasterClientPool(mMasterClientContext); mBlockMasterClientPool = new BlockMasterClientPool(mMasterClientContext); mWorkerGroup = NettyUtils.createEventLoop(NettyUtils.getUserChannel(getClusterConf()), getClusterConf().getInt(PropertyKey.USER_NETWORK_NETTY_WORKER_THREADS), String.format("alluxio-client-nettyPool-%s-%%d", mId), true); mMetricsEnabled = getClusterConf().getBoolean(PropertyKey.USER_METRICS_COLLECTION_ENABLED); if (mMetricsEnabled) { MetricsSystem.startSinks(getClusterConf().get(PropertyKey.METRICS_CONF_FILE)); MetricsHeartbeatContext.addHeartbeat(getClientContext(), masterInquireClient); } mUriValidationEnabled = ctx.getUriValidationEnabled(); }</code><technical_language>do this if metrics enabled</technical_language>

Target:
private synchronized void initContext(ClientContext ctx, MasterInquireClient masterInquireClient) { mClosed.set(false); mMasterClientContext = MasterClientContext.newBuilder(ctx) .setMasterInquireClient(masterInquireClient).build(); mMetricsEnabled = getClusterConf().getBoolean(PropertyKey.USER_METRICS_COLLECTION_ENABLED); if (mMetricsEnabled) { try { InetSocketAddress masterAddr = masterInquireClient.getPrimaryRpcAddress(); mMasterClientContext.loadConf(masterAddr, true, true); } catch (UnavailableException e) { LOG.error("Failed to get master address during initialization", e); } catch (AlluxioStatusException ae) { LOG.error("Failed to load configuration from " + "meta master during initialization", ae); } MetricsSystem.startSinks(getClusterConf().get(PropertyKey.METRICS_CONF_FILE)); MetricsHeartbeatContext.addHeartbeat(getClientContext(), masterInquireClient); } mFileSystemMasterClientPool = new FileSystemMasterClientPool(mMasterClientContext); mBlockMasterClientPool = new BlockMasterClientPool(mMasterClientContext); mWorkerGroup = NettyUtils.createEventLoop(NettyUtils.getUserChannel(getClusterConf()), getClusterConf().getInt(PropertyKey.USER_NETWORK_NETTY_WORKER_THREADS), String.format("alluxio-client-nettyPool-%s-%%d", mId), true); mUriValidationEnabled = ctx.getUriValidationEnabled(); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.actionSettings: Intent i = new Intent(this, SettingsActivity.class); startActivity(i); return true; case R.id.actionSearchLocal: return true; case R.id.actionLogout: this.showLogoutDialog(); return true; case R.id.syncbutton: boolean syncState = OpenMRS.getInstance().getSyncState(); if (syncState) { OpenMRS.getInstance().setSyncState(false); setSyncButtonState(false); } else if(NetworkUtils.hasNetwork()){ OpenMRS.getInstance().setSyncState(true); setSyncButtonState(true); Intent intent = new Intent("org.openmrs.mobile.intent.action.SYNC_PATIENTS"); getApplicationContext().sendBroadcast(intent); } else { showNoInternetConnectionSnackbar(); } return true; case R.id.actionLocation: ArrayList<Location> list = (ArrayList<Location>) new LocationDAO().getLocationList(); <START> String[] items = new String[list.size()]; <END> String selected = mOpenMRS.getLocation(); int checkedItem = -1; for (int j = 0; j < list.size(); j++) { items[j] = list.get(j).getName(); if (items[j].equals(selected)) checkedItem = j; } new AlertDialog.Builder(this) .setSingleChoiceItems(items, checkedItem, (dialog, which) -> { mOpenMRS.setLocation(list.get(which).getName()); dialog.dismiss(); }) .show(); return true; default: return super.onOptionsItemSelected(item); } }</code><technical_language>is of this list String[] items</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.actionSettings: Intent i = new Intent(this, SettingsActivity.class); startActivity(i); return true; case R.id.actionSearchLocal: return true; case R.id.actionLogout: this.showLogoutDialog(); return true; case R.id.syncbutton: boolean syncState = OpenMRS.getInstance().getSyncState(); if (syncState) { OpenMRS.getInstance().setSyncState(false); setSyncButtonState(false); } else if(NetworkUtils.hasNetwork()){ OpenMRS.getInstance().setSyncState(true); setSyncButtonState(true); Intent intent = new Intent("org.openmrs.mobile.intent.action.SYNC_PATIENTS"); getApplicationContext().sendBroadcast(intent); } else { showNoInternetConnectionSnackbar(); } return true; case R.id.actionLocation: List<String> list = new LocationDAO().getLocationList(); new AlertDialog.Builder(this) .setSingleChoiceItems( new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, list), list.indexOf(mOpenMRS.getLocation()), (dialog, which) -> { mOpenMRS.setLocation(list.get(which)); dialog.dismiss(); }) .show(); return true; default: return super.onOptionsItemSelected(item); } }
Source:
<code>public void setIdentifiers(List<Identifier> identifiers) { <START> Identifiers = identifiers; <END> }</code><technical_language>this this.variableName. This is a Potential Null pointer Exception</technical_language>

Target:
public void setIdentifiers(List<Identifier> identifiers) { this.identifiers = identifiers; }
Source:
<code>private void executeOperation(final DataOperation operation) { final long dataKey = operation.getDataKey(); final Pair<Boolean, String> routingResult = router.route(dataKey); <START> if (routingResult.getFirst()) { <END> executeLocalOperation(operation); } else { final String targetEvalId = routingResult.getSecond(); remoteSender.sendOperation(targetEvalId, operation); } }</code><technical_language>This harms readability. I prefer specific a local variable isLocal</technical_language>

Target:
private void executeOperation(final DataOperation operation) { final long dataKey = operation.getDataKey(); final Pair<Boolean, String> routingResult = router.route(dataKey); final boolean isLocal = routingResult.getFirst(); if (isLocal) { executeLocalOperation(operation); } else { final String targetEvalId = routingResult.getSecond(); remoteSender.sendOperation(targetEvalId, operation); } }
Source:
<code>public static double getContrastRatio(final int rgb1, final int rgb2) { final double lumi1 = getLuminance(Color.red(rgb1), Color.green(rgb1), Color.blue(rgb1)) + 0.05; final double lumi2 = getLuminance(Color.red(rgb2), Color.green(rgb2), Color.blue(rgb2)) + 0.05; if (lumi1 > lumi2) { return lumi1 / lumi2; } <START> return lumi2 / lumi1; <END> }</code><technical_language>return Math.max(lumi1, lumi2) / Math.min(lumi1, lumi2); is shorter more readable</technical_language>

Target:
public static double getContrastRatio(final int rgb1, final int rgb2) { final double lumi1 = getLuminance(Color.red(rgb1), Color.green(rgb1), Color.blue(rgb1)) + 0.05; final double lumi2 = getLuminance(Color.red(rgb2), Color.green(rgb2), Color.blue(rgb2)) + 0.05; return Math.max(lumi1, lumi2) / Math.min(lumi1, lumi2); }
Source:
<code>static String readSymlink(File path) throws IOException { Path nioPath = path.toPath(); Path target = Files.readSymbolicLink(nioPath); String targetString = target.toString(); if (SystemReader.getInstance().isWindows()) targetString = targetString.replace('\\', '/'); <START> else if (SystemReader.getInstance().isMacOS()) { <END> targetString = Normalizer.normalize(targetString, Form.NFC); } return targetString; }</code><technical_language>style nit: braces</technical_language>

Target:
static String readSymlink(File path) throws IOException { Path nioPath = path.toPath(); Path target = Files.readSymbolicLink(nioPath); String targetString = target.toString(); if (SystemReader.getInstance().isWindows()) targetString = targetString.replace('\\', '/'); else if (SystemReader.getInstance().isMacOS()) targetString = Normalizer.normalize(targetString, Form.NFC); return targetString; }
Source:
<code>public void send(DatastreamProducerRecord record, SendCallback sendCallback) { try { validateEventRecord(record); record.serializeEvents(_datastreamTask.getDestinationSerDes()); _transportProvider.send(_datastreamTask.getDatastreamDestination().getConnectionString(), record, (metadata, exception) -> onSendCallback(metadata, exception, sendCallback, record)); } catch (Exception e) { if (_skipBadMessagesEnabled) { <START> _logger.error("Skipping Message. task: ; error: {}", _datastreamTask, e.toString()); <END> _skippedBadMessagesRate.mark(); } else { String errorMessage = String.format("Failed send the event %s exception %s", record, e); _logger.warn(errorMessage, e); throw new DatastreamRuntimeException(errorMessage, e); } } if (Instant.now().isAfter(_lastFlushTime.plus(_flushInterval))) { flush(); } }</code><technical_language>_logger.error("Skipping Message. task: {};", _datastreamTask, e); log4j handle exception properly</technical_language>

Target:
public void send(DatastreamProducerRecord record, SendCallback sendCallback) { try { validateEventRecord(record); record.serializeEvents(_datastreamTask.getDestinationSerDes()); _transportProvider.send(_datastreamTask.getDatastreamDestination().getConnectionString(), record, (metadata, exception) -> onSendCallback(metadata, exception, sendCallback, record)); } catch (Exception e) { if (_skipBadMessagesEnabled) { _logger.error("Skipping Message. task: ; error: {}", _datastreamTask, e); _skippedBadMessagesRate.mark(); } else { String errorMessage = String.format("Failed send the event %s exception %s", record, e); _logger.warn(errorMessage, e); throw new DatastreamRuntimeException(errorMessage, e); } } if (Instant.now().isAfter(_lastFlushTime.plus(_flushInterval))) { flush(); } }
Source:
<code>private List<Method> getAnnotateMethods(Class<T> annotationClass, Class<?> vmClass) { List<Method> methods = null; synchronized (annoMethodCache) { methods = annoMethodCache.get(vmClass); if (methods != null) return methods; methods = new ArrayList<Method>(); Class<?> curr = vmClass; String sign = null; Set<String> signs = new HashSet<String>(); while (curr != null && !curr.equals(Object.class)) { Method currm = null; T annotation = curr.getAnnotation(annotationClass); for (Method m : curr.getDeclaredMethods()) { final T i = m.getAnnotation(annotationClass); if (i == null) continue; if (annotation != null) { throw new UiException( "more than one [@" + annotationClass.getSimpleName() + "] in the class " + curr); } annotation = i; currm = m; } if (currm != null) { sign = MiscUtil.toSimpleMethodSignature(currm); if (signs.contains(sign)) { _log.warn("more than one method that has same signature '{}' " + "in the hierarchy of '{}', the method in extended class will be call " + "more than once ", annotationClass.getSimpleName(), sign, vmClass); } else { signs.add(sign); } <START> if (annotation.annotationType().getName().equals("org.zkoss.bind.annotation.Destroy")) { <END> methods.add(currm); } else { methods.add(0, currm); } } curr = (annotation != null && shouldLookupSuperclass(annotation)) ? curr.getSuperclass() : null; } methods = Collections.unmodifiableList(methods); annoMethodCache.put(vmClass, methods); } return methods; }</code><technical_language>if (annotation.annotationType() == Destroy.class) { is enough huh</technical_language>

Target:
private List<Method> getAnnotateMethods(Class<T> annotationClass, Class<?> vmClass) { List<Method> methods = null; synchronized (annoMethodCache) { methods = annoMethodCache.get(vmClass); if (methods != null) return methods; methods = new ArrayList<Method>(); Class<?> curr = vmClass; String sign = null; Set<String> signs = new HashSet<String>(); while (curr != null && !curr.equals(Object.class)) { Method currm = null; T annotation = curr.getAnnotation(annotationClass); for (Method m : curr.getDeclaredMethods()) { final T i = m.getAnnotation(annotationClass); if (i == null) continue; if (annotation != null) { throw new UiException( "more than one [@" + annotationClass.getSimpleName() + "] in the class " + curr); } annotation = i; currm = m; } if (currm != null) { sign = MiscUtil.toSimpleMethodSignature(currm); if (signs.contains(sign)) { _log.warn("more than one method that has same signature '{}' " + "in the hierarchy of '{}', the method in extended class will be call " + "more than once ", annotationClass.getSimpleName(), sign, vmClass); } else { signs.add(sign); } if (annotation.annotationType() == Destroy.class) { methods.add(currm); } else { methods.add(0, currm); } } curr = (annotation != null && shouldLookupSuperclass(annotation)) ? curr.getSuperclass() : null; } methods = Collections.unmodifiableList(methods); annoMethodCache.put(vmClass, methods); } return methods; }
Source:
<code>public void toXmlFile(File xmlFile) throws Exception { createDocument("archive"); if (!dirs.isEmpty()) { for(Map.Entry<String, String> entry : dirs.entrySet()){ Element child = doc.createElement("dir"); child.setAttribute("sourceOnDisk", entry.getKey()); child.setAttribute("targetInArchive", entry.getValue()); doc.getDocumentElement().appendChild(child); } } if (!files.isEmpty()) { for(Map.Entry<String, String> entry : files.entrySet()){ Element child = doc.createElement("file"); child.setAttribute("sourceOnDisk", entry.getKey()); child.setAttribute("targetInArchive", entry.getValue()); doc.getDocumentElement().appendChild(child); } } if (!archives.isEmpty()) { for(Map.Entry<String, String> entry : archives.entrySet()){ Element child = doc.createElement("archive"); child.setAttribute("targetInArchive", entry.getValue()); doc.getDocumentElement().appendChild(child); Element grandChild = doc.createElement("dir"); child.setAttribute("sourceOnDisk", entry.getKey()); child.setAttribute("targetInArchive", "/"); <START> doc.getDocumentElement().appendChild(grandChild); <END> } } writeXMLDocument(xmlFile); }</code><technical_language>grandChild appended "child"? i.e. child.appendChild(grandChild)? i.e, creating this hierarchy: <archive targetInArchive="/apps/jarName.jar"> <dir targetInArchive="/META-INF" sourceOnDisk="${was.server.dir}/applicationData/myApplication" /> </archive></technical_language>

Target:
public void toXmlFile(File xmlFile) throws Exception { createDocument("archive"); if (!dirs.isEmpty()) { for(Map.Entry<String, String> entry : dirs.entrySet()){ Element child = doc.createElement("dir"); addElement(doc.getDocumentElement(), child, entry.getValue(), entry.getKey()); } } if (!files.isEmpty()) { for(Map.Entry<String, String> entry : files.entrySet()){ Element child = doc.createElement("file"); addElement(doc.getDocumentElement(), child, entry.getValue(), entry.getKey()); } } if (!archives.isEmpty()) { for(Map.Entry<String, String> entry : archives.entrySet()){ Element child = doc.createElement("archive"); addElement(doc.getDocumentElement(), child, entry.getValue()); addElement(child, doc.createElement("dir"), "/", entry.getKey()); } } writeXMLDocument(xmlFile); }