auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String retrieveArtifact(String APIId, String gatewayLabel, String gatewayInstruction) throws ArtifactSynchronizerException { try { String baseURL = APIConstants.HTTPS_PROTOCOL_URL_PREFIX + System.getProperty(APIConstants.KEYMANAGER_HOSTNAME) + ":" + System.getProperty(APIConstants.KEYMANAGER_PORT) + APIConstants.INTERNAL_WEB_APP_EP; String endcodedgatewayLabel= URLEncoder.encode(gatewayLabel, APIConstants.DigestAuthConstants.CHARSET); String path = APIConstants.GatewayArtifactSynchronizer.SYNAPSE_ARTIFACTS + "?apiId=" + APIId + <START> "&gatewayInstruction=" + gatewayInstruction +"&gatewayLabel="+ endcodedgatewayLabel; <END> String endpoint = baseURL + path; HttpResponse httpResponse = invokeService(endpoint); return EntityUtils.toString(httpResponse.getEntity(), APIConstants.DigestAuthConstants.CHARSET); } catch (IOException e) { String msg = "Error while executing the http client " ; log.error(msg, e); throw new ArtifactSynchronizerException(msg, e); } }</code><technical_language>Formatting issues</technical_language>

Target:
public String retrieveArtifact(String APIId, String gatewayLabel, String gatewayInstruction) throws ArtifactSynchronizerException { CloseableHttpResponse httpResponse = null; try { String baseURL = eventHubConfigurationDto.getServiceUrl(); String endcodedgatewayLabel= URLEncoder.encode(gatewayLabel, APIConstants.DigestAuthConstants.CHARSET); String path = APIConstants.GatewayArtifactSynchronizer.SYNAPSE_ARTIFACTS + "?apiId=" + APIId + "&gatewayInstruction=" + gatewayInstruction + "&gatewayLabel="+ endcodedgatewayLabel; String endpoint = baseURL + path; httpResponse = invokeService(endpoint); String gatewayRuntimeArtifact = null; if (httpResponse.getEntity() != null ) { gatewayRuntimeArtifact = EntityUtils.toString(httpResponse.getEntity(), APIConstants.DigestAuthConstants.CHARSET); httpResponse.close(); } else { throw new ArtifactSynchronizerException("HTTP response is empty"); } return gatewayRuntimeArtifact; } catch (IOException e) { String msg = "Error while executing the http client"; log.error(msg, e); throw new ArtifactSynchronizerException(msg, e); } }
Source:
<code>public static String resourceTypeNameByRemovingProfileSuffix(String resourceTypeName) { <START> if (resourceTypeName.length() > PROFILE_SUFFIX.length() && resourceTypeName <END> .substring(resourceTypeName.length() - PROFILE_SUFFIX.length(), resourceTypeName.length()) .equals(PROFILE_SUFFIX)) { resourceTypeName = resourceTypeName.substring(0, resourceTypeName.length() - PROFILE_SUFFIX.length()); } return resourceTypeName; }</code><technical_language>resourceTypeName.indexOf(PROFILE_SUFFIX) != -1</technical_language>

Target:
public static String resourceTypeNameByRemovingProfileSuffix(String resourceTypeName) { if (resourceTypeName.endsWith(PROFILE_SUFFIX)) { resourceTypeName = resourceTypeName.substring(0, resourceTypeName.length() - PROFILE_SUFFIX.length()); } return resourceTypeName; }
Source:
<code>@Override protected String getDescription(MBeanOperationInfo info) { String str = super.getDescription(info); try { Method m = getMethod(info); MXBeanDescription desc = m.getAnnotation(MXBeanDescription.class); if (desc != null) { str = desc.value(); assert str != null; assert !str.trim().isEmpty(); <START> assert Character.isUpperCase(str.charAt(0)) : str; <END> assert str.charAt(str.length() - 1) == '.' : str; } } catch (SecurityException | ClassNotFoundException ignored) { } return str; }</code><technical_language>please add clear message for case assert failed</technical_language>

Target:
@Override protected String getDescription(MBeanOperationInfo info) { String str = super.getDescription(info); try { Method m = getMethod(info); MXBeanDescription desc = m.getAnnotation(MXBeanDescription.class); if (desc != null) { str = desc.value(); assert str != null; assert !str.trim().isEmpty(); assert Character.isUpperCase(str.charAt(0)) : DESC_MUST_START_WITH_UPP_CASE + str; assert str.charAt(str.length() - 1) == '.' : DESC_MUST_END_WITH_PERIOD + str; } } catch (SecurityException | ClassNotFoundException ignored) { } return str; }
Source:
<code>private void checkStateOfWsAgent(WsAgentHealthStateDto agentHealthStateDto) { final int statusCode = agentHealthStateDto.getCode(); final String infoWindowTitle = "Workspace Agent Not Responding"; final ConfirmCallback restartCallback = new StopCallback(); if (statusCode == 200) { dialogFactory.createMessageDialog(infoWindowTitle, <START> "Our workspace agent is no longer responding. To fix the problem, verify you have a" + <END> " good network connection and restart the workspace.", restartCallback).show(); } else { dialogFactory.createMessageDialog(infoWindowTitle, "Our workspace agent is no longer responding. To fix the problem, restart the workspace.", restartCallback).show(); } }</code><technical_language>revert code? This revert changes <LINK_0></technical_language>

Target:
private void checkStateOfWsAgent(WsAgentHealthStateDto agentHealthStateDto) { final int statusCode = agentHealthStateDto.getCode(); final String infoWindowTitle = "Workspace Agent Not Responding"; final ConfirmCallback stopCallback = new StopCallback(); if (statusCode == 200) { dialogFactory.createMessageDialog(infoWindowTitle, "Workspace agent is no longer responding. To fix the problem, verify you have a" + " good network connection and restart the workspace.", stopCallback).show(); } else { dialogFactory.createMessageDialog(infoWindowTitle, "Workspace agent is no longer responding. To fix the problem, restart the workspace.", stopCallback).show(); } }
Source:
<code>private boolean isSupportedByAnyResourceType(Path path) { org.uberfire.backend.vfs.Path convertedPath = convertPath(path); <START> return this.getResourceTypeDefinitionList() <END> .stream() .anyMatch(resourceTypeDefinition -> resourceTypeDefinition.accept(convertedPath)); }</code><technical_language>here? If here, @adrielparedes question this assets mandatory @ApplicationScoped? I so, I ensure avoid a memory leak for instance.get(). wdyt</technical_language>

Target:
private boolean isSupportedByAnyResourceType(Path path) { org.uberfire.backend.vfs.Path convertedPath = convertPath(path); return this.getVisibleResourceTypes() .stream() .anyMatch(resourceTypeDefinition -> resourceTypeDefinition.accept(convertedPath)); }
Source:
<code>protected void showAssets() { busyIndicatorView.showBusyIndicator(ts.getTranslation(LibraryConstants.LoadingAssets)); libraryService.call((Boolean hasAssets) -> { <START> if (hasAssets) { <END> this.view.setContent(populatedAssetsScreen.getView().getElement()); } else { this.view.setContent(emptyAssetsScreen.getView().getElement()); } busyIndicatorView.hideBusyIndicator(); }).hasAssets(this.projectInfo.getProject()); }</code><technical_language>showing "busy indicator" good practice pass explicit ErrorCallback ensure "busy indicator" is closed in event of exception happening. Otherwise, in event of exception thrown, User is left "Loading..." modal "on top" unable do other refresh browser. HasBusyIndicatorDefaultErrorCallback</technical_language>

Target:
protected void showAssets() { busyIndicatorView.showBusyIndicator(ts.getTranslation(LibraryConstants.LoadingAssets)); libraryService.call((Boolean hasAssets) -> { if (hasAssets) { this.view.setContent(populatedAssetsScreen.getView().getElement()); } else { this.view.setContent(emptyAssetsScreen.getView().getElement()); } busyIndicatorView.hideBusyIndicator(); }, new HasBusyIndicatorDefaultErrorCallback(busyIndicatorView)).hasAssets(this.projectInfo); }
Source:
<code>AllTypesColumnInfo(String path, Table table) { final Map<String, Long> indicesMap = new HashMap<String, Long>(9); this.columnStringIndex = getValidColumnIndex(path, table, "AllTypes", "columnString"); indicesMap.put("columnString", this.columnStringIndex); this.columnLongIndex = getValidColumnIndex(path, table, "AllTypes", "columnLong"); indicesMap.put("columnLong", this.columnLongIndex); this.columnFloatIndex = getValidColumnIndex(path, table, "AllTypes", "columnFloat"); indicesMap.put("columnFloat", this.columnFloatIndex); this.columnDoubleIndex = getValidColumnIndex(path, table, "AllTypes", "columnDouble"); indicesMap.put("columnDouble", this.columnDoubleIndex); this.columnBooleanIndex = getValidColumnIndex(path, table, "AllTypes", "columnBoolean"); indicesMap.put("columnBoolean", this.columnBooleanIndex); this.columnDateIndex = getValidColumnIndex(path, table, "AllTypes", "columnDate"); indicesMap.put("columnDate", this.columnDateIndex); this.columnBinaryIndex = getValidColumnIndex(path, table, "AllTypes", "columnBinary"); indicesMap.put("columnBinary", this.columnBinaryIndex); this.columnObjectIndex = getValidColumnIndex(path, table, "AllTypes", "columnObject"); indicesMap.put("columnObject", this.columnObjectIndex); this.columnRealmListIndex = getValidColumnIndex(path, table, "AllTypes", "columnRealmList"); indicesMap.put("columnRealmList", this.columnRealmListIndex); <START> setIndicesMap(Collections.unmodifiableMap(indicesMap)); <END> }</code><technical_language>reason unmodifiable? extra overhead need</technical_language>

Target:
AllTypesColumnInfo(String path, Table table) { final Map<String, Long> indicesMap = new HashMap<String, Long>(9); this.columnStringIndex = getValidColumnIndex(path, table, "AllTypes", "columnString"); indicesMap.put("columnString", this.columnStringIndex); this.columnLongIndex = getValidColumnIndex(path, table, "AllTypes", "columnLong"); indicesMap.put("columnLong", this.columnLongIndex); this.columnFloatIndex = getValidColumnIndex(path, table, "AllTypes", "columnFloat"); indicesMap.put("columnFloat", this.columnFloatIndex); this.columnDoubleIndex = getValidColumnIndex(path, table, "AllTypes", "columnDouble"); indicesMap.put("columnDouble", this.columnDoubleIndex); this.columnBooleanIndex = getValidColumnIndex(path, table, "AllTypes", "columnBoolean"); indicesMap.put("columnBoolean", this.columnBooleanIndex); this.columnDateIndex = getValidColumnIndex(path, table, "AllTypes", "columnDate"); indicesMap.put("columnDate", this.columnDateIndex); this.columnBinaryIndex = getValidColumnIndex(path, table, "AllTypes", "columnBinary"); indicesMap.put("columnBinary", this.columnBinaryIndex); this.columnObjectIndex = getValidColumnIndex(path, table, "AllTypes", "columnObject"); indicesMap.put("columnObject", this.columnObjectIndex); this.columnRealmListIndex = getValidColumnIndex(path, table, "AllTypes", "columnRealmList"); indicesMap.put("columnRealmList", this.columnRealmListIndex); setIndicesMap(indicesMap); }
Source:
<code>private void updateGroup(final TupleBatch tb, final int row, final Object[] curAggStates) throws DbException { for (int agg = 0; agg < aggregators.length; ++agg) { if (!(aggregators[agg] .getClass() .getName() <START> .equals(StatefulUserDefinedAggregator.class.getName()))) { <END> aggregators[agg].addRow(tb, row, curAggStates[agg]); } } }</code><technical_language>instanceof</technical_language>

Target:
private void updateGroup(final TupleBatch tb, final int row, final Object[] curAggStates) throws DbException { for (int agg = 0; agg < aggregators.length; ++agg) { if (!(aggregators[agg] instanceof StatefulUserDefinedAggregator)) { aggregators[agg].addRow(tb, row, curAggStates[agg]); } } }
Source:
<code>boolean isVisibleTo(Account account) throws OrmException; } @Override public List<SuggestReviewerInfo> apply(final ChangeResource rsrc) throws BadRequestException, OrmException, IOException { if (query == null) { throw new BadRequestException("missing query field"); } if (!suggestAccounts || query.length() < suggestFrom) { return Collections.emptyList(); } VisibilityControl visibilityControl = getVisibility(rsrc); List<AccountInfo> suggestedAccounts = suggestAccount(visibilityControl); accountLoaderFactory.create(true).fill(suggestedAccounts); <START> final List<SuggestReviewerInfo> <END> reviewer = new ArrayList<SuggestReviewerInfo>(suggestedAccounts.size()); for (final AccountInfo a : suggestedAccounts) { reviewer.add(new SuggestReviewerInfo(a)); } final List<GroupReference> suggestedAccountGroups = suggestAccountGroup(rsrc.getControl().getProjectControl()); for (final GroupReference g : suggestedAccountGroups) { if (suggestGroupAsReviewer(rsrc.getControl().getProject(), g, visibilityControl)) { GroupBaseInfo info = new GroupBaseInfo(); info.id = Url.encode(g.getUUID().get()); info.name = g.getName(); reviewer.add(new SuggestReviewerInfo(info)); } } Collections.sort(reviewer); if (reviewer.size() <= limit) { return reviewer; } else { return reviewer.subList(0, limit); } }</code><technical_language>I final unnecessary, I meant for of locals. code days final for values need anonymous class, parameters methods/constructors ambiguous if a field vs. parameter is assigned. final parameter compiler complain assignment parameter field</technical_language>

Target:
boolean isVisibleTo(Account account) throws OrmException; } @Override public List<SuggestReviewerInfo> apply(ChangeResource rsrc) throws BadRequestException, OrmException, IOException { if (Strings.isNullOrEmpty(query)) { throw new BadRequestException("missing query field"); } if (!suggestAccounts || query.length() < suggestFrom) { return Collections.emptyList(); } VisibilityControl visibilityControl = getVisibility(rsrc); List<AccountInfo> suggestedAccounts = suggestAccount(visibilityControl); accountLoaderFactory.create(true).fill(suggestedAccounts); List<SuggestReviewerInfo> reviewer = Lists.newArrayList(); for (AccountInfo a : suggestedAccounts) { reviewer.add(new SuggestReviewerInfo(a)); } Project p = rsrc.getControl().getProject(); for (GroupReference g : suggestAccountGroup( rsrc.getControl().getProjectControl())) { if (suggestGroupAsReviewer(p, g, visibilityControl)) { GroupBaseInfo info = new GroupBaseInfo(); info.id = Url.encode(g.getUUID().get()); info.name = g.getName(); reviewer.add(new SuggestReviewerInfo(info)); } } Collections.sort(reviewer); if (reviewer.size() <= limit) { return reviewer; } else { return reviewer.subList(0, limit); } }
Source:
<code>private String toAscii(String unicodeString) throws IllegalArgumentException { String asciiString = ""; int start = 0; int index = getBreakingIndex( unicodeString, ASCII_MAX_LABEL_LENGTH ); <START> int end = unicodeString.length() <= index ? unicodeString.length() : index; <END> while ( true ) { asciiString += IDN.toASCII( unicodeString.substring( start, end ) ); if ( end == unicodeString.length() ) { break; } start = end; index = getBreakingIndex( unicodeString, start + ASCII_MAX_LABEL_LENGTH ); end = index > unicodeString.length() ? unicodeString.length() : index; } return asciiString; }</code><technical_language>2 lines a single method instead of 2 parts repeating below? getIDNToASCIIPartEnd(String unicodeString, int start)</technical_language>

Target:
private String toAscii(String unicodeString) throws IllegalArgumentException { String asciiString = ""; int start = 0; int end = getIDNToASCIIPartEnd( unicodeString, IDN_TO_ASCII_MAX_LABEL_LENGTH); while ( true ) { asciiString += IDN.toASCII( unicodeString.substring( start, end ) ); if ( end == unicodeString.length() ) { break; } start = end; end = getIDNToASCIIPartEnd( unicodeString, start + IDN_TO_ASCII_MAX_LABEL_LENGTH); } return asciiString; }
Source:
<code><START> private JsonObject createHierarchicalJson(Schema schema, IndexedRecord record, int idPos){ <END> JsonObject jsonObject = JsonObject.create(); for (int i = 0; i < schema.getFields().size(); i++){ if (i == idPos) continue; Object value = record.get(i); String fieldName = schema.getFields().get(i).name(); try { JsonObject innerJson = JsonObject.fromJson(value.toString()); jsonObject.put(fieldName, innerJson); } catch (Exception e) { jsonObject.put(fieldName, value); } } return jsonObject; }</code><technical_language>method is core for new json string input, advice do some real test method scope for cases in current jira</technical_language>

Target:
public JsonObject createHierarchicalJson(Schema schema, IndexedRecord record, int idPos){ JsonObject jsonObject = JsonObject.create(); for (int i = 0; i < schema.getFields().size(); i++){ if (i == idPos) continue; Object value = record.get(i); String fieldName = schema.getFields().get(i).name(); try { JsonObject innerJson = JsonObject.fromJson(value.toString()); jsonObject.put(fieldName, innerJson); } catch (Exception e) { jsonObject.put(fieldName, value); } } return jsonObject; }
Source:
<code>static void write(Node node, Map<String, String> map, File file, String lang) throws FileNotFoundException { FileOutputStream fos = null; BufferedOutputStream bos = null; <START> try { <END> fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); write(node, map, bos, lang); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { } } if (fos != null) { try { fos.close(); } catch (IOException e) { } } } }</code><technical_language>Please for closeable objects a try-with-resources statement. code cleaner read maintain</technical_language>

Target:
static void write(Node node, Map<String, String> map, File file, String lang) throws IOException { try (FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos);) { write(node, map, bos, lang); } }
Source:
<code>protected MavenArtifactCoordinates getArtifactCoordinates(RepositoryPath repositoryPath) throws IOException { MavenArtifact artifact = MavenArtifactUtils.convertPathToArtifact(repositoryPath); <START> return artifact != null ? new MavenArtifactCoordinates(artifact) : null; <END> }</code><technical_language>@fuss86 previous implementation assumed return null, is reasons do now</technical_language>

Target:
protected MavenArtifactCoordinates getArtifactCoordinates(RepositoryPath repositoryPath) throws IOException { MavenArtifact artifact = MavenArtifactUtils.convertPathToArtifact(repositoryPath); return new MavenArtifactCoordinates(artifact); }
Source:
<code>protected boolean checkNamespaceExists(String namespaceName) throws InfrastructureException { <START> return clientFactory.createOC().projects().withName(namespaceName).get() != null; <END> }</code><technical_language>is null. OpenShift returns forbidden if project exist. ![Screenshot_20191010_115105](<LINK_0></technical_language>

Target:
protected boolean checkNamespaceExists(String namespaceName) throws InfrastructureException { return fetchNamespaceObject(namespaceName).isPresent(); }
Source:
<code>public static AbstractJwsSigner createJwsSigner(JwsSignerObject jwsSignerObject, OpenIdConfigurationResponse discoveryResponse) { final String algorithm = jwsSignerObject.getIdToken().getHeader().getClaimAsString(JwtHeaderName.ALGORITHM); final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm); <START> final String kid = jwsSignerObject.getIdToken().getHeader().getClaimAsString(JwtHeaderName.KEY_ID); <END> final String jwkUrl = discoveryResponse.getJwksUri(); if (signatureAlgorithm.getFamily() == AlgorithmFamily.RSA) { final RSAPublicKey publicKey = jwsSignerObject.getKeyService().getRSAPublicKey(jwkUrl, kid); return jwsSignerObject.getOpClientFactory().createRSASigner(signatureAlgorithm, publicKey); } else if (signatureAlgorithm.getFamily() == AlgorithmFamily.HMAC) { return new HMACSigner(signatureAlgorithm, jwsSignerObject.getSite().getClientSecret()); } else if (signatureAlgorithm.getFamily() == AlgorithmFamily.EC) { ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(jwkUrl, kid); return new ECDSASigner(signatureAlgorithm, publicKey); } return null; }</code><technical_language>if (sigatureAlgorithm == null) throw new HttpException(ErrorResponseCode.INVALID_ALGORITHM);</technical_language>

Target:
public static AbstractJwsSigner createJwsSigner(JwsSignerObject jwsSignerObject, OpenIdConfigurationResponse discoveryResponse) { final String algorithm = jwsSignerObject.getIdToken().getHeader().getClaimAsString(JwtHeaderName.ALGORITHM); final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm); final String kid = jwsSignerObject.getIdToken().getHeader().getClaimAsString(JwtHeaderName.KEY_ID); final String jwkUrl = discoveryResponse.getJwksUri(); if (signatureAlgorithm == null) throw new HttpException(ErrorResponseCode.INVALID_ALGORITHM); if (signatureAlgorithm.getFamily() == AlgorithmFamily.RSA) { final RSAPublicKey publicKey = jwsSignerObject.getKeyService().getRSAPublicKey(jwkUrl, kid); return jwsSignerObject.getOpClientFactory().createRSASigner(signatureAlgorithm, publicKey); } else if (signatureAlgorithm.getFamily() == AlgorithmFamily.HMAC) { return new HMACSigner(signatureAlgorithm, jwsSignerObject.getRp().getClientSecret()); } else if (signatureAlgorithm.getFamily() == AlgorithmFamily.EC) { ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(jwkUrl, kid); return new ECDSASigner(signatureAlgorithm, publicKey); } throw new HttpException(ErrorResponseCode.ALGORITHM_NOT_SUPPORTED); }
Source:
<code>private void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.reset(); String pathInfo = req.getPathInfo(); String[] pathParts = pathInfo.split("/"); if (pathParts.length < 3) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } String assetPath = Arrays.stream(pathParts).skip(1).collect(joining(File.separator)); logger.debug("Retrieving component asset {}", assetPath); <START> <END> try (InputStream assetStream = assetProvider.openAsset(assetPath)) { int size = IOUtils.copy(assetStream, resp.getOutputStream()); String mimeType = mimetypesFileTypeMap.getContentType(pathInfo); resp.setContentType(mimeType); resp.setContentLength(size); resp.setHeader("Cache-Control", cacheControlHeaderValue); } catch (Exception e) { logger.info("Not able to find component asset {}", assetPath); logger.debug("Error opening external component asset", e); resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }</code><technical_language>in mind getPathInfo return null</technical_language>

Target:
private void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.reset(); if (!loader.isEnabled()) { logger.debug("Ignoring request because External Components API is disabled."); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String pathInfo = req.getPathInfo(); if (pathInfo == null) { badRequest(resp); return; } String[] pathParts = pathInfo.split("/"); if (pathParts.length < 3) { badRequest(resp); return; } String assetPath = Arrays.stream(pathParts).skip(1).collect(joining(File.separator)); logger.debug("Retrieving component asset {}", assetPath); try (InputStream assetStream = assetProvider.openAsset(assetPath)) { int size = IOUtils.copy(assetStream, resp.getOutputStream()); String mimeType = mimetypesFileTypeMap.getContentType(pathInfo); resp.setContentType(mimeType); resp.setContentLength(size); resp.setHeader(CACHE_CONTROL_PARAM, cacheControlHeaderValue); } catch (Exception e) { logger.info("Not able to find component asset {}", assetPath); logger.debug("Error opening external component asset", e); resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Source:
<code>public Message receive(final String queueName, final long timeoutMillis) { Message message = execute(channel -> { CompletableFuture<Delivery> future = new CompletableFuture<>(); Delivery delivery = getDeliveryAndCancelConsumer(channel, future, <START> createConsumer(queueName, channel, future), timeoutMillis); <END> if (delivery == null) { return null; } else { if (isChannelLocallyTransacted(channel)) { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); channel.txCommit(); } else if (isChannelTransacted()) { ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, delivery.getEnvelope().getDeliveryTag()); } else { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } return buildMessageFromDelivery(delivery); } }); logReceived(message); return message; }</code><technical_language>future variable createConsumer() logic hide in getDeliveryAndCancelConsumer()</technical_language>

Target:
public Message receive(final String queueName, final long timeoutMillis) { Message message = execute(channel -> { Delivery delivery = consumeDelivery(channel, queueName, timeoutMillis); if (delivery == null) { return null; } else { if (isChannelLocallyTransacted(channel)) { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); channel.txCommit(); } else if (isChannelTransacted()) { ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, delivery.getEnvelope().getDeliveryTag()); } else { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } return buildMessageFromDelivery(delivery); } }); logReceived(message); return message; }
Source:
<code>public void testExtractItem() { BloombergDataRow row = BloombergDataRow.builder() .withDate("2014-01-01") .withDescription("description") .withDuration("0:01:01") .withId("id") .withKeywords(ImmutableList.of("key")) .withSource("Bloomberg") .withTitle("title") <START> .withKeywords(ImmutableList.of("key")) <END> .build(); Content content = extractor.extract(row); Item item = (Item) content; assertThat(item.getCanonicalUri(), endsWith("id")); assertThat(item.getCurie(), endsWith("id")); assertEquals(item.getPublisher(), Publisher.BLOOMBERG); assertEquals("description", item.getDescription()); assertEquals("title", item.getTitle()); assertEquals(MediaType.VIDEO, item.getMediaType()); assertEquals(Integer.valueOf(61), Iterables.getOnlyElement(item.getVersions()).getDuration()); assertEquals(new KeyPhrase("key", Publisher.BLOOMBERG), Iterables.getOnlyElement(item.getKeyPhrases())); }</code><technical_language>keywords added twice</technical_language>

Target:
public void testExtractItem() { BloombergDataRow row = BloombergDataRow.builder() .withDate("2014-01-01") .withDescription("description") .withDuration("0:01:01") .withId("id") .withKeywords(ImmutableList.of("key")) .withSource("Bloomberg") .withTitle("title") .build(); Content content = extractor.extract(row); Item item = (Item) content; assertThat(item.getCanonicalUri(), endsWith("id")); assertThat(item.getCurie(), endsWith("id")); assertEquals(item.getPublisher(), Publisher.BLOOMBERG); assertEquals("description", item.getDescription()); assertEquals("title", item.getTitle()); assertEquals(MediaType.VIDEO, item.getMediaType()); assertEquals(Integer.valueOf(61), Iterables.getOnlyElement(item.getVersions()).getDuration()); assertEquals(new KeyPhrase("key", Publisher.BLOOMBERG), Iterables.getOnlyElement(item.getKeyPhrases())); }
Source:
<code>Set<WritableFulltext> writableNodeIndices() { <START> return nodeIndices.values().stream().map( WritableFulltext::new ).collect( Collectors.toSet() ); <END> }</code><technical_language>do for commit, if move forming of sets current register update new index soon added do touch anymore</technical_language>

Target:
Set<WritableFulltext> writableNodeIndices() { return Collections.unmodifiableSet( writableNodeIndices ); }
Source:
<code>public void testRunningTaskDoesNotImpactScriptExecution(boolean withSelectionScript) throws Exception { FileLock fileLock = new FileLock(); Path fileLockPath = fileLock.lock(); String scriptCode = "org.ow2.proactive.scheduler.util.FileLock.waitUntilUnlocked(\"" + fileLockPath.toString().replace("\\", "\\\\") + "\")"; log("Submit script (handled asynchronously by the resource manager)"); List<ScriptResult<Object>> resultsFuture = schedulerHelper.getResourceManager() .executeScript(scriptCode, "groovy", TargetType.NODE_URL.name(), Sets.newSet(testNode.getNodeURL())); log("Submit job"); final JobId jobId = schedulerHelper.submitJob(createNonBlockingJob(withSelectionScript)); Thread.sleep(3000); log("Unlock the script"); fileLock.unlock(); log("Wait when job finish"); schedulerHelper.waitForEventJobFinished(jobId, TIMEOUT); Assert.assertEquals(1, resultsFuture.size()); ScriptResult result = resultsFuture.get(0); if (result.errorOccured()) { result.getException().printStackTrace(); Assert.fail("Script execution failed"); } <START> <END> schedulerHelper.waitUntilState(testNode.getNodeURL(), NodeState.FREE, TIMEOUT); log("Check job result"); checkJobResult(schedulerHelper.getSchedulerInterface(), jobId); Assert.assertEquals("After the node is freed, no active object should remain", 0, testNode.getNode().getNumberOfActiveObjects()); }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Remove this of "Thread.sleep()". [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public void testRunningTaskDoesNotImpactScriptExecution(boolean withSelectionScript) throws Exception { FileLock fileLock = new FileLock(); Path fileLockPath = fileLock.lock(); String scriptCode = "org.ow2.proactive.scheduler.util.FileLock.waitUntilUnlocked(\"" + fileLockPath.toString().replace("\\", "\\\\") + "\")"; log("Submit script (handled asynchronously by the resource manager)"); List<ScriptResult<Object>> resultsFuture = schedulerHelper.getResourceManager() .executeScript(scriptCode, "groovy", TargetType.NODE_URL.name(), Sets.newSet(testNode.getNodeURL())); log("Submit job"); final JobId jobId = schedulerHelper.submitJob(createNonBlockingJob(withSelectionScript)); Thread.sleep(3000); log("Unlock the script"); fileLock.unlock(); log("Wait when job finish"); schedulerHelper.waitForEventJobFinished(jobId, TIMEOUT); Assert.assertEquals(1, resultsFuture.size()); ScriptResult result = resultsFuture.get(0); if (result.errorOccured()) { result.getException().printStackTrace(); Assert.fail("Script execution failed"); } schedulerHelper.waitUntilState(testNode.getNodeURL(), NodeState.FREE, TIMEOUT); log("Check job result"); checkJobResult(schedulerHelper.getSchedulerInterface(), jobId); checkActiveObjects(); }
Source:
<code>private static void checkNotAdvertisedWants(RevWalk walk, List<ObjectId> notAdvertisedWants, Set<ObjectId> reachableFrom) throws MissingObjectException, IncorrectObjectTypeException, IOException { AsyncRevObjectQueue q = walk.parseAny(notAdvertisedWants, true); RevObject obj; <START> while ((obj = q.next()) != null) { <END> if (!(obj instanceof RevCommit)) throw new PackProtocolException(MessageFormat.format( JGitText.get().wantNotValid, obj.name())); walk.markStart((RevCommit) obj); } for (ObjectId id : reachableFrom) { try { walk.markUninteresting(walk.parseCommit(id)); } catch (IncorrectObjectTypeException notCommit) { continue; } } RevCommit bad = walk.next(); if (bad != null) { throw new PackProtocolException(MessageFormat.format( JGitText.get().wantNotValid, bad.name())); } walk.reset(); }</code><technical_language>This moved of a try/finally block: try { .. loop } finally { q.release(); } usage of walk.parseAny</technical_language>

Target:
private static void checkNotAdvertisedWants(RevWalk walk, List<ObjectId> notAdvertisedWants, Set<ObjectId> reachableFrom) throws MissingObjectException, IncorrectObjectTypeException, IOException { AsyncRevObjectQueue q = walk.parseAny(notAdvertisedWants, true); try { RevObject obj; while ((obj = q.next()) != null) { if (!(obj instanceof RevCommit)) throw new PackProtocolException(MessageFormat.format( JGitText.get().wantNotValid, obj.name())); walk.markStart((RevCommit) obj); } } catch (MissingObjectException notFound) { ObjectId id = notFound.getObjectId(); throw new PackProtocolException(MessageFormat.format( JGitText.get().wantNotValid, id.name()), notFound); } finally { q.release(); } for (ObjectId id : reachableFrom) { try { walk.markUninteresting(walk.parseCommit(id)); } catch (IncorrectObjectTypeException notCommit) { continue; } } RevCommit bad = walk.next(); if (bad != null) { throw new PackProtocolException(MessageFormat.format( JGitText.get().wantNotValid, bad.name())); } walk.reset(); }
Source:
<code><START> public <T> T build(Class<T> serviceClass, String userAgent, List<String> uris) { <END> Preconditions.checkArgument(!uris.isEmpty()); List<String> sanitizedUris = sanitizeUris(uris); okhttp3.OkHttpClient client = createOkHttpClient(userAgent, sanitizedUris); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(sanitizedUris.get(0)) .addConverterFactory(JacksonConverterFactory.create()) .build(); return retrofit.create(serviceClass); }</code><technical_language>This change default behavior expect if a service created Retrofit, kind of sucks. **On other hand Retrofit accept URL throw some exception, right?** In case is a big deal accept more URLs</technical_language>

Target:
public <T> T build(Class<T> serviceClass, String userAgent, List<String> uris) { Preconditions.checkArgument(!uris.isEmpty()); List<String> sanitizedUris = addTrailingSlashes(uris); okhttp3.OkHttpClient client = createOkHttpClient(userAgent, sanitizedUris); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(sanitizedUris.get(0)) .addConverterFactory(JacksonConverterFactory.create()) .build(); return retrofit.create(serviceClass); }
Source:
<code>public void shouldGetNotFoundFor_markChargeAsCaptureApproved_whenNoChargeExists() { connectorRestApiClient .withAccountId(accountId) .withChargeId("i-do-not-exist") .postMarkChargeAsCaptureApproved() .statusCode(NOT_FOUND.getStatusCode()) .contentType(JSON) .body(JSON_MESSAGE_KEY, contains("Charge with id [i-do-not-exist] not found.")) <START> .body("error_identifier", Matchers.is(ErrorIdentifier.GENERIC.toString())); <END> }</code><technical_language>this</technical_language>

Target:
public void shouldGetNotFoundFor_markChargeAsCaptureApproved_whenNoChargeExists() { connectorRestApiClient .withAccountId(accountId) .withChargeId("i-do-not-exist") .postMarkChargeAsCaptureApproved() .statusCode(NOT_FOUND.getStatusCode()) .contentType(JSON) .body(JSON_MESSAGE_KEY, contains("Charge with id [i-do-not-exist] not found.")) .body("error_identifier", is(ErrorIdentifier.GENERIC.toString())); }
Source:
<code>public static Configuration loadConfig(File configFile) { Configuration config = new BaseConfiguration(); ListDelimiterHandler delimiter = new DefaultListDelimiterHandler(','); PropertiesBuilderParameters propertyParameters = new Parameters().properties(); propertyParameters.setFile(configFile); propertyParameters.setThrowExceptionOnMissing(true); propertyParameters.setListDelimiterHandler(delimiter); FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class); builder.configure(propertyParameters); try { config = builder.getConfiguration(); } catch (ConfigurationException cex) { <START> LOGGER.error("loading of IAM configuration failed"); <END> } return config; }</code><technical_language>do throw exception</technical_language>

Target:
public static Configuration loadConfig(File configFile) throws ConfigurationException { Configuration config; ListDelimiterHandler delimiter = new DefaultListDelimiterHandler(','); PropertiesBuilderParameters propertyParameters = new Parameters().properties(); propertyParameters.setFile(configFile); propertyParameters.setThrowExceptionOnMissing(true); propertyParameters.setListDelimiterHandler(delimiter); FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class); builder.configure(propertyParameters); config = builder.getConfiguration(); LOGGER.debug("IAM configuration loaded"); return config; }
Source:
<code><START> public static boolean isJavaName(String name) { <END> return isJavaIdentifier(name) && isNotRestrictedKeyword(name); }</code><technical_language>_package private_</technical_language>

Target:
static boolean isJavaName(String name) { return isNotRestrictedKeyword(name) && isJavaIdentifier(name); }
Source:
<code>public boolean postOldXmlFormat(String message) { boolean error = false; if (StringUtils.isEmpty(message)) { return error; } String[] msgs = message.split("[\\n]", -1); if (msgs.length > 1) { for (String msg : msgs) { error = postOldXmlFormat(msg) || error; } return error; } if (StringUtils.isNotEmpty(message)) { if (message.charAt(0) == '<') { try { error = _internalPostOldXmlFormat(message); } catch (RuntimeException e) { error = true; log.error( "Installation of Host. Received illegal XML from Host. Message: {}", message); <START> log.error("Exception", e); <END> } } else { log.info("VDS message: {}", message); } } return error; }</code><technical_language>debug</technical_language>

Target:
public boolean postOldXmlFormat(String message) { boolean error = false; if (StringUtils.isEmpty(message)) { return error; } String[] msgs = message.split("[\\n]", -1); if (msgs.length > 1) { for (String msg : msgs) { error = postOldXmlFormat(msg) || error; } return error; } if (StringUtils.isNotEmpty(message)) { if (message.charAt(0) == '<') { try { error = _internalPostOldXmlFormat(message); } catch (RuntimeException e) { error = true; log.error( "Installation of Host. Received illegal XML from Host. Message: {}", message); log.debug("Exception", e); } } else { log.info("VDS message: {}", message); } } return error; }
Source:
<code>private void onStandbyClusterAddRemove(TopologyDescriptor discoveredTopology) { log.debug("Standby Cluster has been added or removed from topology={}", discoveredTopology); if (localClusterDescriptor.getRole() == ClusterRole.ACTIVE) { if (replicationManager != null && isLeader.get()) { replicationManager.processStandbyChange(discoveredTopology); } <START> } <END> updateLocalTopology(discoveredTopology); updateReplicationManagerTopology(discoveredTopology); logReplicationMetadataManager.setupTopologyConfigId(topologyDescriptor.getTopologyConfigId()); log.debug("Persist new topologyConfigId {}, cluster id={}, status={}", topologyDescriptor.getTopologyConfigId(), localClusterDescriptor.getClusterId(), localClusterDescriptor.getRole()); }</code><technical_language>If topologyConfigId change, overrule processStandbyChange. processStandbyChange is called topologyConfigId change list of standbys changed. Is logic correct processStandbyChange called updating localTopology</technical_language>

Target:
private void onStandbyClusterAddRemove(TopologyDescriptor discoveredTopology) { log.debug("Standby Cluster has been added or removed from topology={}", discoveredTopology); if (localClusterDescriptor.getRole() == ClusterRole.ACTIVE) { if (replicationManager != null && isLeader.get()) { replicationManager.processStandbyChange(discoveredTopology); } } updateLocalTopology(discoveredTopology); updateReplicationManagerTopology(discoveredTopology); logReplicationMetadataManager.setupTopologyConfigId(topologyDescriptor.getTopologyConfigId()); log.debug("Persist new topologyConfigId {}, cluster id={}, role={}", topologyDescriptor.getTopologyConfigId(), localClusterDescriptor.getClusterId(), localClusterDescriptor.getRole()); }
Source:
<code>public static SubjectAlternativeNames create(final List<String> dnsNames, final List<String> emails, final List<String> upns) { <START> return new AutoValue_Certificate_SubjectAlternativeNames(dnsNames, emails, upns); <END> }</code><technical_language>Enforce immutability</technical_language>

Target:
public static SubjectAlternativeNames create(final List<String> dnsNames, final List<String> emails, final List<String> upns) { return new AutoValue_Certificate_SubjectAlternativeNames( dnsNames != null ? ImmutableList.copyOf(dnsNames) : ImmutableList.<String> of(), emails != null ? ImmutableList.copyOf(emails) : ImmutableList.<String> of(), upns != null ? ImmutableList.copyOf(upns) : ImmutableList.<String> of() ); }
Source:
<code>public List<Order> getAllOrdersByEvent(Event event) throws EventNotFoundException { <START> List<Order> orders = orderService.getAllOrders(); <END> List<Order> ordersAssociatedWithEvent = new ArrayList<>(); for (Order order : orders) { for (OrderProduct orderProduct : order.getOrderProducts()) { Product product = orderProduct.getProduct(); if (eventService.getByProduct(product).equals(event)) { ordersAssociatedWithEvent.add(order); break; } } } return ordersAssociatedWithEvent; }</code><technical_language>So, this a long get event orders. SoldProduct, thanks @martijnjanssen</technical_language>

Target:
public List<Order> getAllOrdersByEvent(Event event) { List<Order> ordersAssociatedWithEvent = new ArrayList<>(); event.getProducts().stream().forEach(product -> ordersAssociatedWithEvent.addAll(orderService.getAllByProduct(product))); return ordersAssociatedWithEvent; }
Source:
<code>public void fileTimeRotationTest() throws ConfigurationLoadingException, InterruptedException { FileTailerQueue queue = new FileTailerQueue(QUEUE_SIZE); PipeConfiguration flowConfig = TailerLogUtils.loadConfig(); LogTailer tailer = TailerLogUtils.createTailer(queue, flowConfig); String filePath = flowConfig.getSourceConfiguration().getWorkDir() + "/" + flowConfig.getSourceConfiguration().getFileName(); ch.qos.logback.classic.Logger logger = TailerLogUtils.getTimeLogger(filePath); RandomStringUtils randomUtils = new RandomStringUtils(); List<String> logList = new ArrayList<String>(ENTRY_NUMBER); List<String> queueReturnList = new ArrayList<String>(ENTRY_NUMBER); tailer.startWorker(); <START> for (int i = 0; i < ENTRY_NUMBER; i++) { <END> String currLine = randomUtils.randomAlphanumeric(LINE_SIZE); logger.debug(currLine); logList.add(currLine); Thread.sleep(WRITING_INTERVAL); } Thread.sleep(2000); for (String str:logList) { Assert.assertEquals(true, queue.take().getEventData().contains(str)); } tailer.stopWorker(); }</code><technical_language>Please fix alignment in this for-block</technical_language>

Target:
public void fileTimeRotationTest() throws ConfigurationLoadingException, InterruptedException { FileTailerQueue queue = new FileTailerQueue(QUEUE_SIZE); PipeConfiguration flowConfig = TailerLogUtils.loadConfig(); LogTailer tailer = TailerLogUtils.createTailer(queue, flowConfig); String filePath = flowConfig.getSourceConfiguration().getWorkDir().getAbsolutePath() + "/" + flowConfig.getSourceConfiguration().getFileName(); Logger logger = TailerLogUtils.getTimeLogger(filePath); RandomStringUtils randomUtils = new RandomStringUtils(); List<String> logList = new ArrayList<String>(ENTRY_NUMBER); tailer.startAsync(); for (int i = 0; i < ENTRY_NUMBER; i++) { String currLine = randomUtils.randomAlphanumeric(LINE_SIZE); logger.debug(currLine); logList.add(currLine); Thread.currentThread().sleep(WRITING_INTERVAL); } Thread.currentThread().sleep(SLEEP_TIME); tailer.stopAsync(); for (String str:logList) { Assert.assertEquals(true, queue.take().getEventData().contains(str)); } }
Source:
<code>public void innerReceive(String dataId, String group, String configInfo) { String oldValue = cacheData.get(dataId); ConfigChangeEvent event = new ConfigChangeEvent(dataId, configInfo, getChangeType(configInfo, oldValue)); <START> cacheData.put(dataId, configInfo); <END> listeners.forEach(listener -> listener.process(event)); }</code><technical_language>if configInfo is null, means a config deleted. This line throw NPE: java java.lang.NullPointerException java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011) java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006) org.apache.dubbo.configcenter.support.nacos.NacosDynamicConfiguration$NacosConfigListener.innerReceive(NacosDynamicConfiguration.java:229) com.alibaba.nacos.api.config.listener.AbstractSharedListener.receiveConfigInfo(AbstractSharedListener.java:37) com.alibaba.nacos.client.config.impl.CacheData$1.run(CacheData.java:188) com.alibaba.nacos.client.config.impl.CacheData.safeNotifyListener(CacheData.java:209) com.alibaba.nacos.client.config.impl.CacheData.checkListenerMd5(CacheData.java:160) com.alibaba.nacos.client.config.impl.ClientWorker$LongPollingRunnable.run(ClientWorker.java:505) java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) java.base/java.lang.Thread.run(Thread.java:834) In order avoid that, is necessary remove dataID cacheDate</technical_language>

Target:
public void innerReceive(String dataId, String group, String configInfo) { String oldValue = cacheData.get(dataId); ConfigChangeEvent event = new ConfigChangeEvent(dataId, configInfo, getChangeType(configInfo, oldValue)); if (configInfo == null) { cacheData.remove(dataId); } else { cacheData.put(dataId, configInfo); } listeners.forEach(listener -> listener.process(event)); }
Source:
<code>public SecureStore get() { <START> return injector.getInstance(getSecureStoreImpl()); <END> }</code><technical_language>This create a new instance time. Cache instance in a member variable</technical_language>

Target:
public SecureStore get() { if (instance == null) { instance = injector.getInstance(getSecureStoreImpl()); } return instance; }
Source:
<code>protected InPlaceCheckBoxTreeDialog createInPlaceCheckBoxTreeDialog(List<String> values) { Map<String, String> validDescriptions = getTaskAttribute().getOptions(); LinkedHashMap<String, String> validValues = new LinkedHashMap<String, String>(validDescriptions.size()); for (String value : validDescriptions.keySet()) { validValues.put(value, value); } InPlaceCheckBoxTreeDialog selectionDialog = new InPlaceCheckBoxTreeDialog(WorkbenchUtil.getShell(), getButton(), values, validValues, NLS.bind(Messages.BugzillaKeywordAttributeEditor_Select_X, getLabel()), validDescriptions); <START> return selectionDialog; <END> }</code><technical_language>inline</technical_language>

Target:
protected InPlaceCheckBoxTreeDialog createInPlaceCheckBoxTreeDialog(List<String> values) { Map<String, String> validDescriptions = getTaskAttribute().getOptions(); LinkedHashMap<String, String> validValues = new LinkedHashMap<String, String>(validDescriptions.size()); for (String value : validDescriptions.keySet()) { validValues.put(value, value); } return new InPlaceCheckBoxTreeDialog(WorkbenchUtil.getShell(), getButton(), values, validValues, NLS.bind(Messages.BugzillaKeywordAttributeEditor_Select_X, getLabel()), validDescriptions); }
Source:
<code>public void onTrackInfoChanged(@NonNull SessionPlayer player, @NonNull List<TrackInfo> trackInfos) { <START> onTracksChanged(player, trackInfos); <END> }</code><technical_language>consecutive calls of onTracksChanged due MediaPlayer L3008 in patch set</technical_language>

Target:
public void onTrackInfoChanged(@NonNull SessionPlayer player, @NonNull List<TrackInfo> trackInfos) { }
Source:
<code>public void copyPackets(long startTime, long endTime, String newTracePath) throws CTFException { CTFTrace trace = fInTrace; if (trace != null) { long adjustedStart = startTime - trace.getClock().getClockOffset(); long adjustedEnd = endTime - trace.getClock().getClockOffset(); File out = new File(newTracePath); boolean directoryExists = out.exists(); if (directoryExists && (!out.isDirectory() || out.listFiles().length != 0)) { throw new CTFIOException("Trace segment cannot be created since trace already exists: " + newTracePath); <START> } else if (!out.exists()) { <END> boolean isSuccess = out.mkdir(); if (!isSuccess) { throw new CTFIOException("Creating trace directory failed: " + newTracePath); } } Metadata metadata = new Metadata(fInTrace); try { metadata.copyTo(out); } catch (IOException e) { throw new CTFIOException("Error copying metadata: " + e.toString(), e); } for (ICTFStream stream : trace.getStreams()) { Set<CTFStreamInput> inputs = stream.getStreamInputs(); for (CTFStreamInput s : inputs) { CTFStreamOutputWriter streamOutputwriter = new CTFStreamOutputWriter(checkNotNull(s), out); streamOutputwriter.copyPackets(adjustedStart, adjustedEnd); } } } }</code><technical_language>inlined if (exists) if (...) throw else create</technical_language>

Target:
public void copyPackets(long startTime, long endTime, String newTracePath) throws CTFException { CTFTrace trace = fInTrace; if (trace != null) { long adjustedStart = startTime - trace.getClock().getClockOffset(); long adjustedEnd = endTime - trace.getClock().getClockOffset(); File out = new File(newTracePath); boolean directoryExists = out.exists(); if (directoryExists && (!out.isDirectory() || out.listFiles().length != 0)) { throw new CTFIOException("Trace segment cannot be created since trace already exists: " + newTracePath); } else if (!out.exists()) { boolean isSuccess = out.mkdirs(); if (!isSuccess) { throw new CTFIOException("Creating trace directory failed: " + newTracePath); } } Metadata metadata = new Metadata(fInTrace); try { metadata.copyTo(out); } catch (IOException e) { throw new CTFIOException("Error copying metadata: " + e.toString(), e); } for (ICTFStream stream : trace.getStreams()) { Set<CTFStreamInput> inputs = stream.getStreamInputs(); for (CTFStreamInput s : inputs) { CTFStreamOutputWriter streamOutputwriter = new CTFStreamOutputWriter(checkNotNull(s), out); streamOutputwriter.copyPackets(adjustedStart, adjustedEnd); } } } }