auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Group query(final Connection databaseConnection) throws SQLException { String preparedStatement = "INSERT INTO 'Group' (OwnerId, Name) VALUES (?, ?)"; Group group; try (PreparedStatement statement = databaseConnection.prepareStatement(preparedStatement)) { statement.setString(1, cOwnerId); statement.setString(2, cGroupName); statement.executeUpdate(); } String preparedQuery = "SELECT G.Key AS GroupId, G.Name AS Name, G.OwnerId As OwnerId, U.Username AS Username, " + "U.Id FROM 'Group' G INNER JOIN User U ON G.OwnerId = U.Id WHERE G.Name = ? AND " + "G.OwnerId = ? LIMIT 1"; try (PreparedStatement statement = databaseConnection.prepareStatement(preparedQuery)) { statement.setString(1, cGroupName); statement.setString(2, cOwnerId); GroupData groupData; int groupId; try (ResultSet resultSet = statement.executeQuery()) { groupId = resultSet.getInt("GroupId"); groupData = new GroupData( groupId, resultSet.getString("Name"), resultSet.getString("OwnerId"), resultSet.getString("Username") ); } <START> group = new Group(Integer.toString(groupData.getGroupId()), groupData); <END> PlayerData playerData = new PlayerData(cOwnerId); playerData.setUsername(null); playerData.setGroupId(Integer.toString(groupId)); new UpdatePlayerData(playerData).query(databaseConnection); } return group; }</code><technical_language>groupData.getGroupId() replaced groupId</technical_language>

Target:
public Group query(final Connection databaseConnection) throws SQLException { String preparedStatement = "INSERT INTO 'Group' (OwnerId, Name) VALUES (?, ?)"; Group group; try (PreparedStatement statement = databaseConnection.prepareStatement(preparedStatement)) { statement.setString(1, cOwnerId); statement.setString(2, cGroupName); statement.executeUpdate(); } String preparedQuery = "SELECT G.Key AS GroupId, G.Name AS Name, G.OwnerId As OwnerId, U.Username AS Username, " + "U.Id FROM 'Group' G INNER JOIN User U ON G.OwnerId = U.Id WHERE G.Name = ? AND " + "G.OwnerId = ? LIMIT 1"; try (PreparedStatement statement = databaseConnection.prepareStatement(preparedQuery)) { statement.setString(1, cGroupName); statement.setString(2, cOwnerId); GroupData groupData; int groupId; try (ResultSet resultSet = statement.executeQuery()) { groupId = resultSet.getInt("GroupId"); groupData = new GroupData( groupId, cGroupName, cOwnerId, resultSet.getString("Username") ); } group = new Group(Integer.toString(groupId), groupData); PlayerData playerData = new PlayerData(cOwnerId); playerData.setUsername(null); playerData.setGroupId(Integer.toString(groupId)); new UpdatePlayerData(playerData).query(databaseConnection); } return group; }
Source:
<code>public void close() throws Exception { Throwable rootCause = null; <START> for (AutoCloseable closeable : closeables) { <END> try { closeable.close(); } catch (Throwable t) { if (rootCause == null) { rootCause = t; } else if (rootCause != t) { rootCause.addSuppressed(t); } } } if (rootCause != null) { throwIfUnchecked(rootCause); throwIfInstanceOf(rootCause, Exception.class); throw new Exception(rootCause); } }</code><technical_language>Guava Closer (which this class mimics) closes in reverse order. Also, close underlying resource twice, if close is called (eg concurrently)</technical_language>

Target:
public void close() throws Exception { Throwable rootCause = null; while (!stack.isEmpty()) { AutoCloseable closeable = stack.removeFirst(); try { closeable.close(); } catch (Throwable t) { if (rootCause == null) { rootCause = t; } else if (rootCause != t) { rootCause.addSuppressed(t); } } } if (rootCause != null) { propagateIfPossible(rootCause, Exception.class); throw new AssertionError(rootCause); } }
Source:
<code>public Api getSiteApi() { <START> return getAPIForSite(new Site("authmanager.wmflabs.org")); <END> }</code><technical_language>Consider reverting this longer a WIP patch</technical_language>

Target:
public Api getSiteApi() { return new Api("authmanager.wmflabs.org", false); }
Source:
<code>public String getTypeImage() { String ambiguousName = Optional.ofNullable(getAmbiguousLhs()).map(s -> s.getName() + ".").orElse(""); <START> return Optional.ofNullable(getLhsType()).map(s -> s.getTypeImage() + ".").orElse(ambiguousName) + getImage(); <END> }</code><technical_language>suggestion return Optional.ofNullable(getLhsType()).map(s -> s.getTypeImage() + ".").orElseGet(() -> Optional.ofNullable(getAmbiguousLhs()).map(s -> s.getName() + ".").orElse("")) + getImage(); avoid computing ambigousName necessary</technical_language>

Target:
public String getTypeImage() { Supplier<String> ambiguousName = () -> Optional.ofNullable(getAmbiguousLhs()).map(s -> s.getName() + ".").orElse(""); return Optional.ofNullable(getLhsType()).map(s -> s.getTypeImage() + ".").orElseGet(ambiguousName) + getImage(); }
Source:
<code>public void handleGetConfigurationObjectResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception, final GetConfigurationObjectResponseDto resultData) { LOGGER.info("handle GetConfigurationObject response for MessageType: {}", deviceMessageMetadata.getMessageType()); final GetConfigurationObjectResponse response = this.configurationMapper.map(resultData, GetConfigurationObjectResponse.class); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send( <END> ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withDataObject(response) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleGetConfigurationObjectResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception, final GetConfigurationObjectResponseDto resultData) { LOGGER.info("handle GetConfigurationObject response for MessageType: {}", deviceMessageMetadata.getMessageType()); final GetConfigurationObjectResponse response = this.configurationMapper.map(resultData, GetConfigurationObjectResponse.class); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withDataObject(response) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send( responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>public static String getHeronAuroraPath(Config config) { <START> String template = System.getenv(JOB_TEMPLATE_ENV); <END> if (template != null){ return new File(template).getPath(); } return new File(config.getStringValue(JOB_TEMPLATE_DIR, Context.heronConf(config)), config.getStringValue(JOB_TEMPLATE,"heron.aurora")).getPath(); }</code><technical_language>Instead of mixing Heron configs environment variables configs? Splitting logic configs env variables for inconsistent experience hidden features. If a config param pass command line override default: $ heron submit | grep config-property --config-property (key=value; a config key value; default: [])</technical_language>

Target:
public static String getHeronAuroraPath(Config config) { return config.getStringValue(JOB_TEMPLATE, new File(Context.heronConf(config), "heron.aurora").getPath()); }
Source:
<code>protected List<CompletableFuture<List<ICompletionProposal>>> buildCompletionFuturesOrJobs(int invocationOffset) { Set<IContentAssistProcessor> processors = null; try { processors= fContentAssistant.fProcessors.get(getTokenContentType(invocationOffset)); } catch (BadLocationException e) { <START> e.printStackTrace(); <END> } if (processors == null) { return Collections.emptyList(); } List<CompletableFuture<List<ICompletionProposal>>> futures = new ArrayList<>(processors.size()); for (IContentAssistProcessor processor : processors) { futures.add(CompletableFuture.supplyAsync(() -> Arrays.asList(processor.computeCompletionProposals(fViewer, invocationOffset)) )); } return futures; }</code><technical_language>This cleaned up</technical_language>

Target:
protected List<CompletableFuture<List<ICompletionProposal>>> buildCompletionFuturesOrJobs(int invocationOffset) { Set<IContentAssistProcessor> processors = null; try { processors= fContentAssistant.getContentAssistProcessors(getTokenContentType(invocationOffset)); } catch (BadLocationException e) { e.printStackTrace(); } if (processors == null) { return Collections.emptyList(); } List<CompletableFuture<List<ICompletionProposal>>> futures = new ArrayList<>(processors.size()); for (IContentAssistProcessor processor : processors) { futures.add(CompletableFuture.supplyAsync(() -> Arrays.asList(processor.computeCompletionProposals(fViewer, invocationOffset)) )); } return futures; }
Source:
<code>synchronized void initialize() throws IOException { if (initialized) { return; } final boolean traceLogging = log.isLoggable(Level.FINEST); final boolean entryExitLogging = log.isLoggable(Level.FINER); final String methodName = "initialize"; if (entryExitLogging) { log.entering(DependencyList.class.getName(), methodName); } long stamp = aggr.getDependencies().getLastModified(); <START> System.out.println("stamp init " + stamp); <END> try { explicitDeps = new ModuleDeps(); expandedDeps = new ModuleDeps(); if (traceLogging) { log.finest("dependent features = " + dependentFeatures); } for (String name : names) { processDep(name, explicitDeps, null, new HashSet<String>(), null); } resolveAliases = true; for (Map.Entry<String, ModuleDepInfo> entry : explicitDeps.entrySet()) { expandDependencies(entry.getKey(), entry.getValue(), expandedDeps); } expandedDeps.keySet().removeAll(IDependencies.excludes); explicitDeps.resolveWith(features); expandedDeps.resolveWith(features); if (traceLogging) { log.finest("explicitDeps after applying features: " + explicitDeps); log.finest("expandedDeps after applying features: " + expandedDeps); } System.out.println("stamp next " + aggr.getDependencies().getLastModified()); } finally { initialized = true; } if (entryExitLogging) { log.exiting(DependencyList.class.getName(), methodName); } }</code><technical_language>Please remove this</technical_language>

Target:
synchronized void initialize() throws IOException { if (initialized) { return; } final boolean traceLogging = log.isLoggable(Level.FINEST); final boolean entryExitLogging = log.isLoggable(Level.FINER); final String methodName = "initialize"; if (entryExitLogging) { log.entering(DependencyList.class.getName(), methodName); } long stamp = aggr.getDependencies().getLastModified(); try { explicitDeps = new ModuleDeps(); expandedDeps = new ModuleDeps(); if (traceLogging) { log.finest("dependent features = " + dependentFeatures); } for (String name : names) { processDep(name, explicitDeps, null, new HashSet<String>(), null); } resolveAliases = true; for (Map.Entry<String, ModuleDepInfo> entry : explicitDeps.entrySet()) { expandDependencies(entry.getKey(), entry.getValue(), expandedDeps); } expandedDeps.keySet().removeAll(IDependencies.excludes); explicitDeps.resolveWith(features); expandedDeps.resolveWith(features); if (traceLogging) { log.finest("explicitDeps after applying features: " + explicitDeps); log.finest("expandedDeps after applying features: " + expandedDeps); } if (stamp != aggr.getDependencies().getLastModified()) { throw new IllegalStateException("" + stamp + "!=" + aggr.getDependencies().getLastModified()); } } finally { initialized = true; } if (entryExitLogging) { log.exiting(DependencyList.class.getName(), methodName); } }
Source:
<code><START> private static int isIsoVersionSupported(String isoVersion) { <END> String supported = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion); return VersionUtils.compareRpmPart(isoVersion, supported); }</code><technical_language>static, please check</technical_language>

Target:
private boolean isIsoVersionSupported(String isoVersion) { String supported = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion); return VersionUtils.compareRpmPart(isoVersion, supported) >= 0; }
Source:
<code>private String getRuleURL() throws MalformedURLException { Server server = selector.pick(); if (server == null) { log.error("No instances found for [%s]!", config.get().getCoordinatorServiceName()); return null; } <START> return new URL( <END> server.getScheme(), server.getAddress(), server.getPort(), config.get().getRulesEndpoint() ).toString(); }</code><technical_language>URI instead of URL consistent other methods. URL DNS lookups problematic</technical_language>

Target:
private String getRuleURL() throws URISyntaxException { Server server = selector.pick(); if (server == null) { log.error("No instances found for [%s]!", config.get().getCoordinatorServiceName()); return null; } return new URI( server.getScheme(), null, server.getAddress(), server.getPort(), config.get().getRulesEndpoint(), null, null ).toString(); }
Source:
<code>public AuthorizationDecision check(Supplier<Authentication> authentication, HttpServletRequest request) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Authorizing %s", request)); } for (RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> mapping : this.mappings) { RequestMatcher matcher = mapping.getMatcher(); MatchResult matchResult = matcher.matcher(request); if (matchResult.isMatch()) { AuthorizationManager<RequestAuthorizationContext> manager = mapping.getEntry(); if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Checking authorization on %s using %s", request, manager)); } return manager.check(authentication, new RequestAuthorizationContext(request, matchResult.getVariables())); } } <START> this.logger.trace("Did not find RequestMatcher that match the request returned null"); <END> return null; }</code><technical_language>rephrase to: suggestion this.logger.trace("Abstaining find matching RequestMatcher")</technical_language>

Target:
public AuthorizationDecision check(Supplier<Authentication> authentication, HttpServletRequest request) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Authorizing %s", request)); } for (Map.Entry<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> mapping : this.mappings .entrySet()) { RequestMatcher matcher = mapping.getKey(); MatchResult matchResult = matcher.matcher(request); if (matchResult.isMatch()) { AuthorizationManager<RequestAuthorizationContext> manager = mapping.getValue(); if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Checking authorization on %s using %s", request, manager)); } return manager.check(authentication, new RequestAuthorizationContext(request, matchResult.getVariables())); } } this.logger.trace("Abstaining since did not find matching RequestMatcher"); return null; }
Source:
<code>public String getFirstDescription() { <START> waitForElementByElement(firstResult); <END> return firstResultDescription.getText(); }</code><technical_language>this element is load ajax? wait for element</technical_language>

Target:
public String getFirstDescription() { return firstResultDescription.getText(); }
Source:
<code>public void testCanceledTransferDoesNotTryToGetBlobs() throws IOException { final Ds3Client ds3Client = Mockito.mock(Ds3Client.class); final CanceledBlobStrategy blobStrategy = new CanceledBlobStrategy(); final TransferStrategy transferStrategy = new TransferStrategyBuilder() .withMasterObjectList(masterObjectList()) .withBlobStrategy(blobStrategy) .withChannelBuilder(new AChannelBuilder()) .withDs3Client(ds3Client) .makePutTransferStrategy(); transferStrategy.transfer(); assertEquals(4, blobStrategy.numAttemptsToUse()); blobStrategy.reset(); new Thread(() -> { try { transferStrategy.cancel(); } catch (final Throwable t) { <START> System.out.println(); <END> } }).start(); transferStrategy.cancel(); transferStrategy.transfer(); assertEquals(0, blobStrategy.numAttemptsToUse()); }</code><technical_language>is this line meaning print throwable</technical_language>

Target:
public void testCanceledTransferDoesNotTryToGetBlobs() throws IOException { final Ds3Client ds3Client = Mockito.mock(Ds3Client.class); final CanceledBlobStrategy blobStrategy = new CanceledBlobStrategy(); final TransferStrategy transferStrategy = new TransferStrategyBuilder() .withMasterObjectList(masterObjectList()) .withBlobStrategy(blobStrategy) .withChannelBuilder(new AChannelBuilder()) .withDs3Client(ds3Client) .makePutTransferStrategy(); transferStrategy.transfer(); assertEquals(4, blobStrategy.numAttemptsToUse()); blobStrategy.reset(); new Thread(() -> { try { transferStrategy.cancel(); } catch (final IOException e) { System.out.println(e.getMessage()); assert(false); } }).start(); transferStrategy.cancel(); transferStrategy.transfer(); assertEquals(0, blobStrategy.numAttemptsToUse()); }
Source:
<code>View onCreateViewHelper(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, int fragmentResource) { super.onCreateView(inflater, container, savedInstanceState); View root = inflater.inflate(fragmentResource, container, false); recyclerView = root.findViewById(android.R.id.list); RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator(); if (animator instanceof SimpleItemAnimator) { ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false); } layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).build()); progLoading = root.findViewById(R.id.progLoading); if (!itemsLoaded) { progLoading.setVisibility(View.VISIBLE); } viewsCreated = true; if (itemsLoaded) { onFragmentLoaded(); } <START> emptyView = root.findViewById(R.id.emptyView); <END> emptyView.setVisibility(View.GONE); ((TextView)emptyView.findViewById(R.id.emptyViewTitle)).setText(R.string.no_all_episodes_head_label); ((TextView)emptyView.findViewById(R.id.emptyViewMessage)).setText(R.string.no_all_episodes_label); return root; }</code><technical_language>Please do add unrelated changes this git history harder understand</technical_language>

Target:
View onCreateViewHelper(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, int fragmentResource) { super.onCreateView(inflater, container, savedInstanceState); View root = inflater.inflate(fragmentResource, container, false); recyclerView = root.findViewById(android.R.id.list); RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator(); if (animator instanceof SimpleItemAnimator) { ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false); } layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).build()); progLoading = root.findViewById(R.id.progLoading); if (!itemsLoaded) { progLoading.setVisibility(View.VISIBLE); } viewsCreated = true; if (itemsLoaded) { onFragmentLoaded(); } emptyView = new EmptyViewHandler(getContext()); emptyView.attachToRecyclerView(recyclerView); emptyView.setTitle(R.string.no_all_episodes_head_label); emptyView.setMessage(R.string.no_all_episodes_label); return root; }
Source:
<code>public void onApplicationEvent(String applicationId, String applicationName, String entityType, Map<String, String> metadata, ApplicationEvent event) { <START> getMutableEvents().add(MutableList.of("application", applicationId, applicationName, entityType, metadata, event)); <END> }</code><technical_language>insist public interface access field? curious</technical_language>

Target:
public void onApplicationEvent(String applicationId, String applicationName, String entityType, Map<String, String> metadata, ApplicationEvent event) { events.add(MutableList.of("application", applicationId, applicationName, entityType, metadata, event)); }
Source:
<code>public String getErrorMessage() { if (loadException != null) { String errorMessage = loadException.getMessage(); if (loadException instanceof XPathSyntaxException) { <START> errorMessage = Localization.get("app.menu.display.cond.bad.xpath", new String[]{xPathErrorMessage, loadException.getMessage()}); <END> loggerInterface.logError(errorMessage); } else if (loadException instanceof XPathException) { errorMessage = Localization.get("app.menu.display.cond.xpath.err", new String[]{xPathErrorMessage, loadException.getMessage()}); loggerInterface.logError(errorMessage, (XPathException)loadException); } return errorMessage; } return null; }</code><technical_language>Hey, currently assumption "universal" strings in localization engine this, wee move loggerInterface.logXPathParseError, loggerInterface.logXPathException() moving errors non-localized</technical_language>

Target:
public String getErrorMessage() { if (loadException != null) { String errorMessage = loadException.getMessage(); loggerInterface.logError(errorMessage, loadException); return errorMessage; } return null; }
Source:
<code>@Test public void configDotXmlPermission() throws Exception { <START> ApiTokenPropertyConfiguration.get().setTokenGenerationOnCreationEnabled(true); <END> j.jenkins.setCrumbIssuer(null); JenkinsRule.WebClient wc = j.createWebClient(); boolean saveEnabled = Item.EXTENDED_READ.getEnabled(); Item.EXTENDED_READ.setEnabled(true); try { wc.assertFails("job/testJob/config.xml", HttpURLConnection.HTTP_FORBIDDEN); wc.withBasicApiToken(User.getById("alice", true)); ENDED_READ permission tryConfigDotXml(wc, 500, "Both perms; should get 500"); wc.withBasicApiToken(User.getById("bob", true)); ENDED_READ) tryConfigDotXml(wc, 500, "Config perm should imply EXTENDED_READ"); wc.withBasicApiToken(User.getById("charlie", true)); ENDED_READ permission tryConfigDotXml(wc, 403, "No permission, should get 403"); } finally { Item.EXTENDED_READ.setEnabled(saveEnabled); } }</code><technical_language>NIT: a test helper method is called, TODO is done easier change test code</technical_language>

Target:
@Test public void configDotXmlPermission() throws Exception { ApiTokenTestHelper.enableLegacyBehavior(); j.jenkins.setCrumbIssuer(null); JenkinsRule.WebClient wc = j.createWebClient(); boolean saveEnabled = Item.EXTENDED_READ.getEnabled(); Item.EXTENDED_READ.setEnabled(true); try { wc.assertFails("job/testJob/config.xml", HttpURLConnection.HTTP_FORBIDDEN); wc.withBasicApiToken(User.getById("alice", true)); ENDED_READ permission tryConfigDotXml(wc, 500, "Both perms; should get 500"); wc.withBasicApiToken(User.getById("bob", true)); ENDED_READ) tryConfigDotXml(wc, 500, "Config perm should imply EXTENDED_READ"); wc.withBasicApiToken(User.getById("charlie", true)); ENDED_READ permission tryConfigDotXml(wc, 403, "No permission, should get 403"); } finally { Item.EXTENDED_READ.setEnabled(saveEnabled); } }
Source:
<code>private JobId blockUntilJobIdInitialized(Job userJob, InternalJob job, Future<?> submitting) throws JobCreationException { try { while (true) { if (submitting.isDone()) { try { submitting.get(); } catch (ExecutionException execException) { throw new JobCreationException(execException); } if (job.getId().longValue() == InternalJob.UNINITIALIZED_JOB_ID) { String errorMessage = String.format("Submission of job %s is finished, but job id is not properly initialized", userJob.getName()); logger.error(errorMessage); throw new JobCreationException(errorMessage); } else { return job.getId(); } } else { if (job.getId().longValue() != InternalJob.UNINITIALIZED_JOB_ID) { registerJobAsUnderSumbission(job.getId()); return job.getId(); } else { Thread.sleep(10); } } } } catch (InterruptedException e) { <START> logger.warn("SchedulerFrontend was interrupted", e); <END> throw new JobCreationException(e); } }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') re-interrupt this method rethrow "InterruptedException". [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private JobId blockUntilJobIdInitialized(Job userJob, InternalJob job, Future<?> submitting) throws JobCreationException { try { while (true) { if (submitting.isDone()) { if (finishedWithoutException(submitting)) { if (jobIdInitialized(job)) { return job.getId(); } else { String errorMessage = String.format("Submission of job %s is finished, but job id is not properly initialized", userJob.getName()); logger.error(errorMessage); throw new JobCreationException(errorMessage); } } } else { if (jobIdInitialized(job)) { registerJobAsUnderSumbission(job.getId()); return job.getId(); } else { Thread.sleep(10); } } } } catch (InterruptedException e) { logger.warn("SchedulerFrontend was interrupted", e); throw new JobCreationException(e); } }
Source:
<code>public PackingPlan createPackingPlan(final Config config, final Config runtime) throws PackingException { String packingClass = Context.packingClass(config); IPacking packing; try { packing = ReflectionUtils.newInstance(packingClass); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { <START> throw new PackingException("Failed to instantiate packing instance", e); <END> } try { TopologyAPI.Topology topology = com.twitter.heron.spi.utils.Runtime.topology(runtime); packing.initialize(config, topology); return packing.pack(); } finally { SysUtils.closeIgnoringExceptions(packing); } }</code><technical_language>pls include packingClass in message</technical_language>

Target:
public PackingPlan createPackingPlan(final Config config, final Config runtime) throws PackingException { String packingClass = Context.packingClass(config); IPacking packing; try { packing = ReflectionUtils.newInstance(packingClass); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new PackingException(String.format( "Failed to instantiate packing instance using packing class %s", packingClass), e); } try { TopologyAPI.Topology topology = com.twitter.heron.spi.utils.Runtime.topology(runtime); packing.initialize(config, topology); return packing.pack(); } finally { SysUtils.closeIgnoringExceptions(packing); } }
Source:
<code>private void recordNewSentEmail(String subject, List<String> addressReceiver, List<String> groupReceiver, String content) { AdminEmailAttributes newDraft = new AdminEmailAttributes(subject, addressReceiver, groupReceiver, new Text(content), new Date()); try { Date createDate = logic.createAdminEmail(newDraft); emailId = logic.getAdminEmail(subject, createDate).getEmailId(); } catch (Exception e) { isError = true; setStatusForException(e, e.getMessage()); return; } moveJobToGroupModeTaskQueue(); moveJobToAddressModeTaskQueue(); if (addressModeOn && groupModeOn) { statusToAdmin = "Email will be sent within an hour to " + addressReceiverListString + "," + groupReceiverListFileKey; statusToUser.add(new StatusMessage("Email will be sent within an hour to " + addressReceiverListString + ", " + groupReceiverListFileKey, StatusMessageColor.SUCCESS)); } else if (addressModeOn) { <START> statusToAdmin = "Email wll be sent within an hour to " + addressReceiverListString; <END> statusToUser.add(new StatusMessage("Email will be sent within an hour to " + addressReceiverListString, StatusMessageColor.SUCCESS)); } else { statusToAdmin = "Email will be sent within an hour to " + groupReceiverListFileKey; statusToUser.add(new StatusMessage("Email will be sent within an hour to " + groupReceiverListFileKey, StatusMessageColor.SUCCESS)); } }</code><technical_language>wll -></technical_language>

Target:
private void recordNewSentEmail(String subject, List<String> addressReceiver, List<String> groupReceiver, String content) { AdminEmailAttributes newDraft = new AdminEmailAttributes(subject, addressReceiver, groupReceiver, new Text(content), new Date()); try { Date createDate = logic.createAdminEmail(newDraft); emailId = logic.getAdminEmail(subject, createDate).getEmailId(); } catch (Exception e) { isError = true; setStatusForException(e, e.getMessage()); return; } statusToAdmin = "Email queued for sending."; moveJobToGroupModeTaskQueue(); moveJobToAddressModeTaskQueue(); }
Source:
<code>private String parseDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH) + 1; int day = cal.get(Calendar.DAY_OF_MONTH); return month + "/" + day; <START> } <END></code><technical_language>SimpleDateFormat this a lot simpler. <LINK_0></technical_language>

Target:
private String parseDate(Date date) { return DateFormat.getDateInstance().format(date); }
Source:
<code>public BigtableHBaseSettings(Configuration configuration) { <START> this.configuration = configuration; <END> this.projectId = getValue(PROJECT_ID_KEY, "Project ID"); this.instanceId = getValue(INSTANCE_ID_KEY, "Instance ID"); }</code><technical_language>Please create a copy of configuration new Configuration(configuration)</technical_language>

Target:
public BigtableHBaseSettings(Configuration configuration) { this.configuration = new Configuration(configuration); this.projectId = getRequiredValue(PROJECT_ID_KEY, "Project ID"); this.instanceId = getRequiredValue(INSTANCE_ID_KEY, "Instance ID"); }
Source:
<code>public static <T> T invokeSetter(String propertyName, Object object, Object valueToSet) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String methodName = "set" + StringUtils.capitalize(propertyName); Method method = null; try { method = object.getClass().getMethod(methodName, valueToSet.getClass()); } catch (NoSuchMethodException ex) { Method[] methods = object.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getParameterCount() == 1) { <START> if (methods[i].getParameters()[0].getType().isAssignableFrom(valueToSet.getClass())) { <END> method = methods[i]; break; } } } if (method == null) { throw ex; } } return (T) method.invoke(object, valueToSet); }</code><technical_language>check parameter count type: I guess missed check method name. If I this is safe</technical_language>

Target:
public static <T> T invokeSetter(String propertyName, Object object, Object valueToSet) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String methodName = "set" + StringUtils.capitalize(propertyName); Method method = null; try { method = object.getClass().getMethod(methodName, valueToSet.getClass()); } catch (NoSuchMethodException ex) { Method[] methods = object.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(methodName) && methods[i].getParameterCount() == 1) { if (methods[i].getParameters()[0].getType().isAssignableFrom(valueToSet.getClass())) { method = methods[i]; break; } } } if (method == null) { throw ex; } } return (T) method.invoke(object, valueToSet); }
Source:
<code>public void DeleteAndRestoreMapTests_005_StaffUserCanRestoreMap() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); <START> InteractiveMapPageObject selectedMap = base.openInteractiveMapById(wikiURL, InteractiveMapsContent.mapToDeleteAndRestore); <END> selectedMap.verifyMapOpened(); selectedMap.verifyMapDeletedMsg(); selectedMap.restoreMap(); selectedMap.verifyMapDeletedMsgNotVisible(); }</code><technical_language>suggest another MapID for 004 005 break dependency 001 002 successful</technical_language>

Target:
public void DeleteAndRestoreMapTests_005_StaffUserCanRestoreMap() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); InteractiveMapPageObject selectedMap = base.openInteractiveMapById(wikiURL, InteractiveMapsContent.mapToDeleteAndRestore[2]); selectedMap.verifyMapOpened(); selectedMap.restoreMap(); }
Source:
<code>private void removeAllGlobalStores(JSONArray args, CallbackContext callbackContext) throws JSONException { <START> List<String> globalDBNames = SmartStoreSDKManager.getInstance().getGlobalStoresPrefixList(); <END> for(String storeName : globalDBNames) { SmartStoreSDKManager.getInstance().removeGlobalSmartStore(storeName); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, true); callbackContext.sendPluginResult(pluginResult); }</code><technical_language>a removeAllGlobalStores method SmartStoreSDKManager do iOS</technical_language>

Target:
private void removeAllGlobalStores(JSONArray args, CallbackContext callbackContext) throws JSONException { SmartStoreSDKManager.getInstance().removeAllGlobalStores(); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, true); callbackContext.sendPluginResult(pluginResult); }
Source:
<code>private void writeHeaderForResultsDetailsByResultCode(Class businessObjectClass, RassObjectUpdateResultCode resultCode) { String header = StringUtils.EMPTY; String objectName = businessObjectClass.getSimpleName(); switch (resultCode) { case SUCCESS_NEW: header = "** " + objectName + " objects successfully created:"; break; case SUCCESS_EDIT: header = "** " + objectName + " objects successfully updated:"; break; case ERROR: header = "** " + objectName + " objects that had errors:"; break; case SKIPPED: header = "** " + objectName + " objects that were skipped:"; break; <START> } <END> reportWriterService.writeNewLines(1); reportWriterService.writeFormattedMessageLine(header); }</code><technical_language>Another switch block helpful a "default" case</technical_language>

Target:
private void writeHeaderForResultsDetailsByResultCode(Class businessObjectClass, RassObjectUpdateResultCode resultCode) { String header; String objectName = businessObjectClass.getSimpleName(); switch (resultCode) { case SUCCESS_NEW: header = "** " + objectName + " objects successfully created:"; break; case SUCCESS_EDIT: header = "** " + objectName + " objects successfully updated:"; break; case ERROR: header = "** " + objectName + " objects that had errors:"; break; case SKIPPED: header = "** " + objectName + " objects that were skipped:"; break; default: header = StringUtils.EMPTY; break; } reportWriterService.writeNewLines(1); reportWriterService.writeFormattedMessageLine(header); }
Source:
<code>public static String toJavaIdentifier(String suggestion) { StringBuilder result = new StringBuilder(); <START> for (int i = 0, codePoint; i < suggestion.length(); i += Character.charCount(codePoint)) { <END> codePoint = suggestion.codePointAt(i); if (i == 0 && !Character.isJavaIdentifierStart(codePoint) && Character.isJavaIdentifierPart(codePoint)) { result.append("_"); } int validCodePoint = Character.isJavaIdentifierPart(codePoint) ? codePoint : '_'; result.appendCodePoint(validCodePoint); } return result.toString(); }</code><technical_language>I this clearer a while loop, a for empty part. codePoint declaration initializer brought short</technical_language>

Target:
public static String toJavaIdentifier(String suggestion) { StringBuilder result = new StringBuilder(); for (int i = 0; i < suggestion.length(); ) { int codePoint = suggestion.codePointAt(i); if (i == 0 && !Character.isJavaIdentifierStart(codePoint) && Character.isJavaIdentifierPart(codePoint)) { result.append("_"); } int validCodePoint = Character.isJavaIdentifierPart(codePoint) ? codePoint : '_'; result.appendCodePoint(validCodePoint); i += Character.charCount(codePoint); } return result.toString(); }
Source:
<code>public SimpleObject asRepresentation(AllergyReaction instance, Representation rep) throws ConversionException { SimpleObject allergenReactionObject = new SimpleObject(); allergenReactionObject.add("allergyReactionId", instance.getAllergyReactionId()); <START> allergenReactionObject.add("allergy", instance.getAllergy().getAllergyId()); <END> ConceptResource1_11 conceptResource = (ConceptResource1_11) Context.getService(RestService.class).getResourceBySupportedClass(Concept.class); allergenReactionObject.add("reaction", conceptResource.asRepresentation(instance.getReaction(), rep)); allergenReactionObject.add("reactionNonCoded", instance.getReactionNonCoded()); return allergenReactionObject; }</code><technical_language>I need include a link object get this AllergyReaction Allergy. (Also, primary key id.)</technical_language>

Target:
public SimpleObject asRepresentation(AllergyReaction instance, Representation rep) throws ConversionException { SimpleObject allergenReactionObject = new SimpleObject(); Concept reaction = instance.getReaction(); if (reaction != null) { ConceptResource1_11 conceptResource = (ConceptResource1_11) Context.getService(RestService.class).getResourceBySupportedClass(Concept.class); allergenReactionObject.add("reaction", conceptResource.asRepresentation(reaction, rep)); } allergenReactionObject.add("reactionNonCoded", instance.getReactionNonCoded()); return allergenReactionObject; }
Source:
<code>private boolean extendImageTransferSession(final ImageTransfer entity) { if (entity.getImagedTicketId() == null) { log.error("Failed to extend image transfer session: no existing session to extend"); return false; } long timeout = getHostTicketLifetime(); Guid resourceId = entity.getImagedTicketId(); try { getImageioClient().extendTicket(resourceId, timeout); } catch (RuntimeException e) { log.error("Failed to extent image ticket in ovirt-imageio-proxy: {}", e.getMessage(), e); <START> return false; <END> } ExtendImageTicketVDSCommandParameters transferCommandParams = new ExtendImageTicketVDSCommandParameters(entity.getVdsId(), entity.getImagedTicketId(), timeout); VDSReturnValue vdsRetVal; try { vdsRetVal = vdsBroker.runVdsCommand(VDSCommandType.ExtendImageTicket, transferCommandParams); } catch (RuntimeException e) { log.error("Failed to extend image transfer session for ticket '{}': {}", resourceId.toString(), e); return false; } if (!vdsRetVal.getSucceeded()) { log.error("Failed to extend image transfer session"); return false; } log.info("Transfer session with ticket id extended, timeout seconds", resourceId.toString(), timeout); setNewSessionExpiration(timeout); return true; }</code><technical_language>If user proxy this break upload. Lets log continue</technical_language>

Target:
private boolean extendImageTransferSession(final ImageTransfer entity) { if (entity.getImagedTicketId() == null) { log.error("Failed to extend image transfer session: no existing session to extend"); return false; } long timeout = getHostTicketLifetime(); Guid resourceId = entity.getImagedTicketId(); ExtendImageTicketVDSCommandParameters transferCommandParams = new ExtendImageTicketVDSCommandParameters(entity.getVdsId(), entity.getImagedTicketId(), timeout); VDSReturnValue vdsRetVal; try { vdsRetVal = vdsBroker.runVdsCommand(VDSCommandType.ExtendImageTicket, transferCommandParams); } catch (RuntimeException e) { log.error("Failed to extend image transfer session for ticket '{}': {}", resourceId.toString(), e); return false; } if (!vdsRetVal.getSucceeded()) { log.error("Failed to extend image transfer session"); return false; } log.info("Transfer session with ticket id extended, timeout seconds", resourceId.toString(), timeout); try { getImageioClient().extendTicket(resourceId, timeout); } catch (RuntimeException e) { log.error("Failed to extent image ticket in ovirt-imageio-proxy: {}", e.getMessage(), e); if (getParameters().isTransferringViaBrowser()) { updateEntityPhaseToStoppedBySystem( AuditLogType.TRANSFER_IMAGE_STOPPED_BY_SYSTEM_FAILED_TO_ADD_TICKET_TO_PROXY); return false; } } setNewSessionExpiration(timeout); return true; }
Source:
<code>public void registerMaxCulBindingMessageProcessor( MaxCulBindingMessageProcessor mcbmp ) { if (this.mcbmp == null) { this.mcbmp = mcbmp; logger.debug("Associated MaxCulBindingMessageProcessor"); } <START> else <END> logger.error("Tried to associate a second MaxCulBindingMessageProcessor!"); }</code><technical_language>please add curly braces</technical_language>

Target:
public void registerMaxCulBindingMessageProcessor( MaxCulBindingMessageProcessor mcbmp) { if (this.mcbmp == null) { this.mcbmp = mcbmp; logger.debug("Associated MaxCulBindingMessageProcessor"); } else { logger.error("Tried to associate a second MaxCulBindingMessageProcessor!"); } }
Source:
<code>public JMXConnector newJMXConnector(JMXServiceURL serviceURL, Map<String, ?> environment) throws IOException { if(!"jolokia".equals(serviceURL.getProtocol())) { <START> throw new MalformedURLException("I only serve Jolokia connections"); <END> } return new JolokiaJmxConnector(serviceURL, environment); }</code><technical_language>error message a bit more informative giving more context ? Invalid URL %s : protocol "jolokia" is supported (not %s) params servericeUrl serviceURL.getProtocol() for placeholders</technical_language>

Target:
public JMXConnector newJMXConnector(JMXServiceURL serviceURL, Map<String, ?> environment) throws IOException { if(!"jolokia".equals(serviceURL.getProtocol())) { throw new MalformedURLException(String.format("Invalid URL %s : Only protocol \"jolokia\" is supported (not %s)", serviceURL, serviceURL.getProtocol())); } return new JolokiaJmxConnector(serviceURL, environment); }
Source:
<code>public Connection acquire() { Connection connection = activate(); if (connection == null) { <START> int queuedRequests = destination.getQueuedRequestCount(); <END> int maxMultiplex = getMaxMultiplex(); int maxPending = queuedRequests / maxMultiplex; if (maxPending * maxMultiplex != queuedRequests) ++maxPending; tryCreate(maxPending); connection = activate(); } return connection; }</code><technical_language>this one-liner instead? int maxPending = (destination.getQueuedRequestCount() + getMaxMultiplex() - 1) / getMaxMultiplex();</technical_language>

Target:
public Connection acquire() { Connection connection = activate(); if (connection == null) { int queuedRequests = destination.getQueuedRequestCount(); int maxMultiplex = getMaxMultiplex(); int maxPending = ceilDiv(queuedRequests, maxMultiplex); tryCreate(maxPending); connection = activate(); } return connection; }
Source:
<code>private String getSyncTokenHeader() { StringBuilder syncTokenHeaderBuilder = new StringBuilder(); <START> syncTokenMap.forEach((k, v) -> syncTokenHeaderBuilder.append(k).append("=").append(v.getValue()).append(",")); <END> int syncTokenInRequestBuilderLength = syncTokenHeaderBuilder.length(); if (syncTokenInRequestBuilderLength > 0) { syncTokenHeaderBuilder.setLength(syncTokenInRequestBuilderLength - 1); } return syncTokenHeaderBuilder.toString(); }</code><technical_language>SyncTokens in ConcurrentHashMap full Sync-Token string this change to: java return syncTokenMap.values() .stream() .map(SyncToken::getSyncTokenString) .collect(Collectors.joining(","));</technical_language>

Target:
private String getSyncTokenHeader() { return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue()) .collect(Collectors.joining(COMMA)); }
Source:
<code>void checkIfDockerRunning() { ProcessBuilder pb = new ProcessBuilder("docker", "ps"); try { Process process = pb.start(); process.waitFor(); if (process.exitValue() != 0) { String type = this.getEntryType().toLowerCase(); out("WARNING: Docker is not running. If this " + type + " uses Docker, it will fail."); } } catch (IOException | InterruptedException e) { <START> exceptionMessage(e, "Error checking for Docker.", 1); <END> } }</code><technical_language>I exit if check fails (exceptionMessage() a System.exit). I silently ignore this error continue</technical_language>

Target:
void checkIfDockerRunning() { try (DockerClient docker = DefaultDockerClient.fromEnv().build()) { docker.info(); } catch (DockerException | DockerCertificateException e) { String type = this.getEntryType().toLowerCase(); out("WARNING: Docker is not running. If this " + type + " uses Docker, it will fail."); } catch (InterruptedException e) { LOG.error("Check for Docker failed", e); } }
Source:
<code>MWApiServiceCall(ApiTemplate template, String endpoint, Map<String, IVariableOrConstant> inputVars, List<OutputVariable> outputVars, HttpClient client, LexiconRelation lexiconRelation) throws MalformedURLException { this.template = template; this.endpoint = new URL("https", endpoint, "/w/api.php").toExternalForm(); this.inputVars = inputVars; this.outputVars = outputVars; this.client = client; this.lexiconRelation = lexiconRelation; this.requestTimeout = Integer.parseInt(System.getProperty(TIMEOUT_PROPERTY, TIMEOUT_MILLIS)); this.maxContinue = Integer.parseInt(System.getProperty(MAX_CONTINUE_CONFIG, "10000")); this.docBuilder = new ThreadLocal<DocumentBuilder>() { @Override protected DocumentBuilder initialValue() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); dbf.setFeature("<LINK_0>", false); dbf.setFeature("<LINK_1>", false); return dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("Could not configure parser: {}", e); throw new <START> RuntimeException(e); <END> } } }; this.xpath = new ThreadLocal<XPath>() { @Override protected XPath initialValue() { return XPathFactory.newInstance().newXPath(); } }; }</code><technical_language>This IllegalStateException (which is a RuntimeException)</technical_language>

Target:
MWApiServiceCall(ApiTemplate template, String endpoint, Map<String, IVariableOrConstant> inputVars, List<OutputVariable> outputVars, HttpClient client, LexiconRelation lexiconRelation) throws MalformedURLException { this.template = template; this.endpoint = new URL("https", endpoint, "/w/api.php").toExternalForm(); this.inputVars = inputVars; this.outputVars = outputVars; this.client = client; this.lexiconRelation = lexiconRelation; this.requestTimeout = Integer.parseInt(System.getProperty(TIMEOUT_PROPERTY, TIMEOUT_MILLIS)); this.maxContinue = Integer.parseInt(System.getProperty(MAX_CONTINUE_CONFIG, "10000")); this.docBuilder = new ThreadLocal<DocumentBuilder>() { @Override protected DocumentBuilder initialValue() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); dbf.setFeature("<LINK_0>", false); dbf.setFeature("<LINK_1>", false); return dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("Could not configure parser: {}", e); throw new IllegalStateException(e); } } }; this.xpath = new ThreadLocal<XPath>() { @Override protected XPath initialValue() { return XPathFactory.newInstance().newXPath(); } }; }
Source:
<code>public List<Attribute> getAttributes() { <START> return attributes; <END> }</code><technical_language>attributes changed client this method returns original reference. Is this intended</technical_language>

Target:
public List<Attribute> getAttributes() { return Collections.unmodifiableList(attributes); }