auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String enqueueSetSpecialDaysRequest(@Identification final String organisationIdentification, @Identification final String deviceIdentification, final SpecialDaysRequest requestData) throws FunctionalException { LOGGER.debug("enqueueSpecialDaysRequest called with organisation and device {}", organisationIdentification, deviceIdentification); final String correlationUid = this.correlationIdProviderService.getCorrelationId(organisationIdentification, deviceIdentification); final SmartMeteringRequestMessage message = new SmartMeteringRequestMessage( SmartMeteringRequestMessageType.REQUEST_SPECIAL_DAYS, correlationUid, organisationIdentification, deviceIdentification, requestData); this.smartMeteringRequestMessageSender.send(message); return correlationUid; }

Target:
public String enqueueSetSpecialDaysRequest(@Identification final String organisationIdentification, @Identification final String deviceIdentification, final SpecialDaysRequest requestData) throws FunctionalException { LOGGER.debug("enqueueSetSpecialDaysRequest called with organisation and device {}", organisationIdentification, deviceIdentification); final String correlationUid = this.correlationIdProviderService.getCorrelationId(organisationIdentification, deviceIdentification); final SmartMeteringRequestMessage message = new SmartMeteringRequestMessage( SmartMeteringRequestMessageType.REQUEST_SPECIAL_DAYS, correlationUid, organisationIdentification, deviceIdentification, requestData); this.smartMeteringRequestMessageSender.send(message); return correlationUid; }
Source:
public List<? extends CatalogItem<?,?>> addItems(String yaml, boolean forceUpdate) { log.debug("Adding manual catalog item to "+mgmt+": "+yaml); checkNotNull(yaml, "yaml"); List<CatalogItemDtoAbstract<?, ?>> result = collectCatalogItems(yaml); for (final CatalogItemDtoAbstract<?, ?> item : result) { if (item.getCatalogItemType().equals(CatalogItemType.ENTITY) || item.getCatalogItemType().equals(CatalogItemType.TEMPLATE)) { Class<?> type = CatalogUtils.newClassLoadingContext(mgmt, item).tryLoadClass(item.getReferenceType()).orNull(); while (type == null) { CatalogItem refCatalogItem = getCatalogItem(item.getReferenceType(), item.getVersion()); if (refCatalogItem == null) { refCatalogItem = Iterables.tryFind(result, new Predicate<CatalogItemDtoAbstract<?, ?>>() { @Override public boolean apply(@Nullable CatalogItemDtoAbstract<?, ?> catalogItemDtoAbstract) { return catalogItemDtoAbstract != null && StringUtils.equals(catalogItemDtoAbstract.getSymbolicName(), item.getReferenceType()); } }).orNull(); } if (refCatalogItem == null) { break; } type = CatalogUtils.newClassLoadingContext(mgmt, refCatalogItem).tryLoadClass(refCatalogItem.getReferenceType()).orNull(); } if (type != null) { item.tags().addTag(BrooklynTags.newInterfacesTag(ClassUtils.getAllInterfaces(type))); } } } for (CatalogItemDtoAbstract<?, ?> item: result) { addItemDto(item, forceUpdate); } return result; }

Target:
public List<? extends CatalogItem<?,?>> addItems(String yaml, boolean forceUpdate) { log.debug("Adding manual catalog item to "+mgmt+": "+yaml); checkNotNull(yaml, "yaml"); List<CatalogItemDtoAbstract<?, ?>> result = collectCatalogItems(yaml); for (CatalogItemDtoAbstract<?, ?> item: result) { addItemDto(item, forceUpdate); } return result; }
Source:
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") ); } group = new Group(Integer.toString(groupData.getGroupId()), groupData); PlayerData playerData = new PlayerData(cOwnerId); playerData.setUsername(null); playerData.setGroupId(Integer.toString(groupId)); new UpdatePlayerData(playerData).query(databaseConnection); } return group; }

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:
public void close() throws Exception { Throwable rootCause = null; for (AutoCloseable closeable : closeables) { 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); } }

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:
public Api getSiteApi() { return getAPIForSite(new Site("authmanager.wmflabs.org")); }

Target:
public Api getSiteApi() { return new Api("authmanager.wmflabs.org", false); }
Source:
public String getTypeImage() { String ambiguousName = Optional.ofNullable(getAmbiguousLhs()).map(s -> s.getName() + ".").orElse(""); return Optional.ofNullable(getLhsType()).map(s -> s.getTypeImage() + ".").orElse(ambiguousName) + getImage(); }

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:
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; } this.webServiceResponseMessageSender.send( ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withDataObject(response) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }

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:
public static String getHeronAuroraPath(Config config) { String template = System.getenv(JOB_TEMPLATE_ENV); 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(); }

Target:
public static String getHeronAuroraPath(Config config) { return config.getStringValue(JOB_TEMPLATE, new File(Context.heronConf(config), "heron.aurora").getPath()); }
Source:
protected List<CompletableFuture<List<ICompletionProposal>>> buildCompletionFuturesOrJobs(int invocationOffset) { Set<IContentAssistProcessor> processors = null; try { processors= fContentAssistant.fProcessors.get(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; }

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:
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(); System.out.println("stamp init " + stamp); 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); } }

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:
private static int isIsoVersionSupported(String isoVersion) { String supported = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion); return VersionUtils.compareRpmPart(isoVersion, supported); }

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

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:
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())); } } this.logger.trace("Did not find RequestMatcher that match the request returned null"); return null; }

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:
public String getFirstDescription() { waitForElementByElement(firstResult); return firstResultDescription.getText(); }

Target:
public String getFirstDescription() { return firstResultDescription.getText(); }
Source:
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) { System.out.println(); } }).start(); transferStrategy.cancel(); transferStrategy.transfer(); assertEquals(0, blobStrategy.numAttemptsToUse()); }

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:
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 = root.findViewById(R.id.emptyView); 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; }

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:
public void onApplicationEvent(String applicationId, String applicationName, String entityType, Map<String, String> metadata, ApplicationEvent event) { getMutableEvents().add(MutableList.of("application", applicationId, applicationName, entityType, metadata, event)); }

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:
public String getErrorMessage() { if (loadException != null) { String errorMessage = loadException.getMessage(); if (loadException instanceof XPathSyntaxException) { errorMessage = Localization.get("app.menu.display.cond.bad.xpath", new String[]{xPathErrorMessage, loadException.getMessage()}); 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; }

Target:
public String getErrorMessage() { if (loadException != null) { String errorMessage = loadException.getMessage(); loggerInterface.logError(errorMessage, loadException); return errorMessage; } return null; }
Source:
@Test public void configDotXmlPermission() throws Exception { ApiTokenPropertyConfiguration.get().setTokenGenerationOnCreationEnabled(true); 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); } }

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:
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) { logger.warn("SchedulerFrontend was interrupted", e); throw new JobCreationException(e); } }

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:
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("Failed to instantiate packing instance", e); } try { TopologyAPI.Topology topology = com.twitter.heron.spi.utils.Runtime.topology(runtime); packing.initialize(config, topology); return packing.pack(); } finally { SysUtils.closeIgnoringExceptions(packing); } }

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:
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) { statusToAdmin = "Email wll be sent within an hour to " + addressReceiverListString; 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)); } }

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:
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; }

Target:
private String parseDate(Date date) { return DateFormat.getDateInstance().format(date); }
Source:
public BigtableHBaseSettings(Configuration configuration) { this.configuration = configuration; this.projectId = getValue(PROJECT_ID_KEY, "Project ID"); this.instanceId = getValue(INSTANCE_ID_KEY, "Instance ID"); }

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:
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) { if (methods[i].getParameters()[0].getType().isAssignableFrom(valueToSet.getClass())) { method = methods[i]; break; } } } if (method == null) { throw ex; } } return (T) method.invoke(object, valueToSet); }

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:
public void DeleteAndRestoreMapTests_005_StaffUserCanRestoreMap() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); InteractiveMapPageObject selectedMap = base.openInteractiveMapById(wikiURL, InteractiveMapsContent.mapToDeleteAndRestore); selectedMap.verifyMapOpened(); selectedMap.verifyMapDeletedMsg(); selectedMap.restoreMap(); selectedMap.verifyMapDeletedMsgNotVisible(); }

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:
private void removeAllGlobalStores(JSONArray args, CallbackContext callbackContext) throws JSONException { List<String> globalDBNames = SmartStoreSDKManager.getInstance().getGlobalStoresPrefixList(); for(String storeName : globalDBNames) { SmartStoreSDKManager.getInstance().removeGlobalSmartStore(storeName); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, true); callbackContext.sendPluginResult(pluginResult); }

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:
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; } reportWriterService.writeNewLines(1); reportWriterService.writeFormattedMessageLine(header); }

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:
public static String toJavaIdentifier(String suggestion) { StringBuilder result = new StringBuilder(); for (int i = 0, codePoint; i < suggestion.length(); i += Character.charCount(codePoint)) { 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(); }

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:
public SimpleObject asRepresentation(AllergyReaction instance, Representation rep) throws ConversionException { SimpleObject allergenReactionObject = new SimpleObject(); allergenReactionObject.add("allergyReactionId", instance.getAllergyReactionId()); allergenReactionObject.add("allergy", instance.getAllergy().getAllergyId()); 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; }

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:
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); return false; } 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; }

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:
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!"); }

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:
public JMXConnector newJMXConnector(JMXServiceURL serviceURL, Map<String, ?> environment) throws IOException { if(!"jolokia".equals(serviceURL.getProtocol())) { throw new MalformedURLException("I only serve Jolokia connections"); } return new JolokiaJmxConnector(serviceURL, environment); }

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:
public Connection acquire() { Connection connection = activate(); if (connection == null) { int queuedRequests = destination.getQueuedRequestCount(); int maxMultiplex = getMaxMultiplex(); int maxPending = queuedRequests / maxMultiplex; if (maxPending * maxMultiplex != queuedRequests) ++maxPending; tryCreate(maxPending); connection = activate(); } return connection; }

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:
private String getSyncTokenHeader() { StringBuilder syncTokenHeaderBuilder = new StringBuilder(); syncTokenMap.forEach((k, v) -> syncTokenHeaderBuilder.append(k).append("=").append(v.getValue()).append(",")); int syncTokenInRequestBuilderLength = syncTokenHeaderBuilder.length(); if (syncTokenInRequestBuilderLength > 0) { syncTokenHeaderBuilder.setLength(syncTokenInRequestBuilderLength - 1); } return syncTokenHeaderBuilder.toString(); }

Target:
private String getSyncTokenHeader() { return syncTokenMap.values().stream().map(syncToken -> syncToken.getId() + EQUAL + syncToken.getValue()) .collect(Collectors.joining(COMMA)); }
Source:
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) { exceptionMessage(e, "Error checking for Docker.", 1); } }

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:
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 RuntimeException(e); } } }; this.xpath = new ThreadLocal<XPath>() { @Override protected XPath initialValue() { return XPathFactory.newInstance().newXPath(); } }; }

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:
public List<Attribute> getAttributes() { return attributes; }

Target:
public List<Attribute> getAttributes() { return Collections.unmodifiableList(attributes); }
Source:
private List<HomeFeedbackSessionRow> createSessionRows(List<FeedbackSessionDetailsBundle> feedbackSessions, Map<FeedbackSessionAttributes, Boolean> sessionSubmissionStatusMap, int startingSessionIdx) { List<HomeFeedbackSessionRow> rows = new ArrayList<>(); int sessionIdx = startingSessionIdx; for (FeedbackSessionDetailsBundle session : feedbackSessions) { FeedbackSessionAttributes feedbackSession = session.feedbackSession; String sessionName = feedbackSession.getFeedbackSessionName(); boolean hasSubmitted = sessionSubmissionStatusMap.get(feedbackSession); rows.add(new StudentHomeFeedbackSessionRow( PageData.sanitizeForHtml(sessionName), getStudentSubmissionsTooltipForSession(feedbackSession, hasSubmitted), getStudentPublishedTooltipForSession(feedbackSession), getStudentSubmissionStatusForSession(feedbackSession, hasSubmitted), getStudentPublishedStatusForSession(feedbackSession), TimeHelper.formatTime12H(feedbackSession.getEndTimeLocal()), feedbackSession.getEndTimeInIso8601UtcFormat(), getStudentFeedbackSessionActions(feedbackSession, hasSubmitted), sessionIdx)); ++sessionIdx; } return rows; }

Target:
private List<HomeFeedbackSessionRow> createSessionRows(List<FeedbackSessionDetailsBundle> feedbackSessions, Map<FeedbackSessionAttributes, Boolean> sessionSubmissionStatusMap, int startingSessionIdx) { List<HomeFeedbackSessionRow> rows = new ArrayList<>(); int sessionIdx = startingSessionIdx; for (FeedbackSessionDetailsBundle session : feedbackSessions) { FeedbackSessionAttributes feedbackSession = session.feedbackSession; String sessionName = feedbackSession.getFeedbackSessionName(); boolean hasSubmitted = sessionSubmissionStatusMap.get(feedbackSession); rows.add(new StudentHomeFeedbackSessionRow( PageData.sanitizeForHtml(sessionName), getStudentSubmissionsTooltipForSession(feedbackSession, hasSubmitted), getStudentPublishedTooltipForSession(feedbackSession), getStudentSubmissionStatusForSession(feedbackSession, hasSubmitted), getStudentPublishedStatusForSession(feedbackSession), TimeHelper.formatDateTimeForSessions(feedbackSession.getEndTime(), feedbackSession.getTimeZone()), feedbackSession.getEndTimeInIso8601UtcFormat(), getStudentFeedbackSessionActions(feedbackSession, hasSubmitted), sessionIdx)); ++sessionIdx; } return rows; }