auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void addMetadata(Context context, T dso, MetadataField metadataField, String lang, List<String> values, List<String> authorities, List<Integer> confidences) throws SQLException { addMetadata(context, dso, metadataField, lang, values, authorities, confidences, null); }

Target:
public void addMetadata(Context context, T dso, MetadataField metadataField, String lang, List<String> values, List<String> authorities, List<Integer> confidences) throws SQLException { boolean authorityControlled = metadataAuthorityService.isAuthorityControlled(metadataField); boolean authorityRequired = metadataAuthorityService.isAuthorityRequired(metadataField); for (int i = 0; i < values.size(); i++) { MetadataValue metadataValue = metadataValueService.create(context, dso, metadataField); metadataValue.setLanguage(lang == null ? null : lang.trim()); if (authorityControlled) { if (authorities != null && authorities.get(i) != null && authorities.get(i).length() > 0) { metadataValue.setAuthority(authorities.get(i)); metadataValue.setConfidence(confidences == null ? Choices.CF_NOVALUE : confidences.get(i)); } else { metadataValue.setAuthority(null); metadataValue.setConfidence(confidences == null ? Choices.CF_UNSET : confidences.get(i)); } if (authorityRequired && (metadataValue.getAuthority() == null || metadataValue.getAuthority() .length() == 0)) { throw new IllegalArgumentException("The metadata field \"" + metadataField .toString() + "\" requires an authority key but none was provided. Value=\"" + values .get(i) + "\""); } } if (values.get(i) != null) { String temp = values.get(i).trim(); char[] dcvalue = temp.toCharArray(); for (int charPos = 0; charPos < dcvalue.length; charPos++) { if (Character.isISOControl(dcvalue[charPos]) && !String.valueOf(dcvalue[charPos]).equals("\u0009") && !String.valueOf(dcvalue[charPos]).equals("\n") && !String.valueOf(dcvalue[charPos]).equals("\r")) { dcvalue[charPos] = ' '; } } metadataValue.setValue(String.valueOf(dcvalue)); ; } else { metadataValue.setValue(null); } dso.addDetails(metadataField.toString()); } }
Source:
public void onAddPassenger(net.minecraft.entity.Entity passenger, CallbackInfo ci) { if (!this.worldObj.isRemote) { MountEntityEvent event = SpongeEventFactory.createMountEntityEvent(Cause.of(NamedCause.source(passenger)), this); SpongeImpl.postEvent(event); Thread.dumpStack(); if(event.isCancelled()) { ci.cancel(); } } }

Target:
public void onAddPassenger(net.minecraft.entity.Entity passenger, CallbackInfo ci) { if (!this.worldObj.isRemote && ShouldFire.MOUNT_ENTITY_EVENT) { if (SpongeImpl.postEvent(SpongeEventFactory.createMountEntityEvent(Cause.of(NamedCause.source(passenger)), this))) { ci.cancel(); } } }
Source:
public void failForNonexistingName() throws Exception { when(jenkins.getView("NoSuchViewOrItemGroup")).thenReturn(null); when(jenkins.getItemByFullName("NoSuchViewOrItemGroup")).thenReturn(null); try { assertThat(runWith("NoSuchViewOrItemGroup"), equalTo(3)); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString("No view or item group with the given name 'NoSuchViewOrItemGroup' found.")); } catch (Exception e) { throw e; } assertThat(stdout, is(empty())); }

Target:
public void failForNonexistingName() throws Exception { when(jenkins.getView("NoSuchViewOrItemGroup")).thenReturn(null); when(jenkins.getItemByFullName("NoSuchViewOrItemGroup")).thenReturn(null); try { runWith("NoSuchViewOrItemGroup"); fail("Exception should be thrown in the previous call."); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString("No view or item group with the given name 'NoSuchViewOrItemGroup' found.")); } assertThat(stdout, is(empty())); }
Source:
public List<String> getExamples() { return Lists.newArrayList( "# Copy the contents of from sample.tar.gz to dataset \"sample\"", "csv-import path/to/sample.tar.gz sample --compression gzip", "# Copy the records from sample.tar.bz2 to a dataset in HDFS", "csv-import path/to/sample.tar.bz2 sample --compression bzip2 --use-hdfs -d datasets" ); }

Target:
public List<String> getExamples() { return Lists.newArrayList( "# Copy the contents of from sample.tar.gz to HDFS dataset \"sample\"", "path/to/sample.tar.gz dataset:hdfs:/path/to/sample" ); }
Source:
private Boolean isTaskKilled(long taskId) { boolean isKilled = false; LOGGER.info("Checking the task status for the task id from backend: " + taskId); if (taskDAO.hasKillFlag(taskId)) { isKilled = true; } return isKilled; }

Target:
private Boolean isTaskKilled(long taskId) { boolean isKilled = false; LOGGER.info("Checking the task status for the task id from backend: {}" , taskId); if (taskDAO.hasKillFlag(taskId)) { isKilled = true; } return isKilled; }
Source:
public Object visitContextDefinition(@NotNull cqlParser.ContextDefinitionContext ctx) { String modelIdentifier = ctx.modelIdentifier() != null ? (String)visit(ctx.modelIdentifier()) : null; String unqualifiedContext = (String)visit(ctx.identifier()); if (modelIdentifier != null && !modelIdentifier.equals("")) { currentContext = modelIdentifier + "." + unqualifiedContext; } else { currentContext = unqualifiedContext; } if (!implicitContextCreated && !unqualifiedContext.equals("Unspecified")) { ExpressionDefinitionInfo expressionDefinition = new ExpressionDefinitionInfo(); expressionDefinition.setName(unqualifiedContext); expressionDefinition.setContext(currentContext); libraryInfo.addExpressionDefinition(expressionDefinition); implicitContextCreated = true; } return currentContext; }

Target:
public Object visitContextDefinition(@NotNull cqlParser.ContextDefinitionContext ctx) { String modelIdentifier = ctx.modelIdentifier() != null ? (String)visit(ctx.modelIdentifier()) : null; String unqualifiedContext = (String)visit(ctx.identifier()); if (modelIdentifier != null && !modelIdentifier.equals("")) { currentContext = modelIdentifier + "." + unqualifiedContext; } else { currentContext = unqualifiedContext; } if (!implicitContextCreated && !unqualifiedContext.equals("Unfiltered")) { ExpressionDefinitionInfo expressionDefinition = new ExpressionDefinitionInfo(); expressionDefinition.setName(unqualifiedContext); expressionDefinition.setContext(currentContext); libraryInfo.addExpressionDefinition(expressionDefinition); implicitContextCreated = true; } return currentContext; }
Source:
protected int runWithJobId(final Namespace options, final HeliosClient client, final PrintStream out, final boolean json, final JobId jobId, final BufferedReader stdin) throws ExecutionException, InterruptedException { final Map<JobId, Job> jobs = client.jobs(jobId.toString()).get(); if (jobs.size() == 0) { out.printf("Unknown job: %s%n", jobId); return 1; } final Job job = Iterables.getOnlyElement(jobs.values()); if (json) { out.println(Json.asPrettyStringUnchecked(job)); } else { out.printf("Id: %s%n", job.getId()); out.printf("Image: %s%n", job.getImage()); out.printf("Command: %s%n", quote(job.getCommand())); printMap(out, "Env: ", QUOTE, job.getEnv()); out.printf("Health check:%n %s%n", formatHealthCheck(job.getHealthCheck())); out.printf("Grace period (seconds): %s%n", job.getGracePeriod()); printMap(out, "Ports: ", FORMAT_PORTMAPPING, job.getPorts()); printMap(out, "Reg: ", FORMAT_SERVICE_PORTS, job.getRegistration()); out.printf("Token: %s%n", job.getToken()); printVolumes(out, job.getVolumes()); } return 0; }

Target:
protected int runWithJobId(final Namespace options, final HeliosClient client, final PrintStream out, final boolean json, final JobId jobId, final BufferedReader stdin) throws ExecutionException, InterruptedException { final Map<JobId, Job> jobs = client.jobs(jobId.toString()).get(); if (jobs.size() == 0) { out.printf("Unknown job: %s%n", jobId); return 1; } final Job job = Iterables.getOnlyElement(jobs.values()); if (json) { out.println(Json.asPrettyStringUnchecked(job)); } else { out.printf("Id: %s%n", job.getId()); out.printf("Image: %s%n", job.getImage()); out.printf("Command: %s%n", quote(job.getCommand())); printMap(out, "Env: ", QUOTE, job.getEnv()); out.printf("Health check: %s%n", formatHealthCheck(job.getHealthCheck())); out.printf("Grace period (seconds): %s%n", job.getGracePeriod()); printMap(out, "Ports: ", FORMAT_PORTMAPPING, job.getPorts()); printMap(out, "Reg: ", FORMAT_SERVICE_PORTS, job.getRegistration()); out.printf("Token: %s%n", job.getToken()); printVolumes(out, job.getVolumes()); } return 0; }
Source:
public String requestGetConfigurationObject(final DlmsConnectionHolder conn, final DlmsDevice device) throws ProtocolAdapterException { return this.getConfigurationObjectCommandExecutor.execute(conn, device, null); }

Target:
public GetConfigurationObjectResponseDto requestGetConfigurationObject(final DlmsConnectionHolder conn, final DlmsDevice device) throws ProtocolAdapterException { return new GetConfigurationObjectResponseDto( this.getConfigurationObjectCommandExecutor.execute(conn, device, null)); }
Source:
public void testContent() { ______TS("content: typical page"); Url logPageUrl = createUrl(Const.ActionURIs.ADMIN_ACTIVITY_LOG_PAGE); logPage = loginAdminToPage(browser, logPageUrl, AdminActivityLogPage.class); logPage.verifyIsCorrectPage(); ______TS("content: navigate to other pages to get some logs"); logPage.navigateTo(createUrl(Const.ActionURIs.ADMIN_HOME_PAGE)); logPage.waitForPageToLoad(); logPage.navigateTo(createUrl(Const.ActionURIs.ADMIN_ACCOUNT_MANAGEMENT_PAGE)); logPage.waitForPageToLoad(); logPage.navigateTo(createUrl(Const.ActionURIs.ADMIN_SEARCH_PAGE)); logPage.waitForPageToLoad(); logPage.navigateTo(createUrl(Const.ActionURIs.ADMIN_ACTIVITY_LOG_PAGE)); logPage.waitForPageToLoad(); logPage.verifyHtmlMainContent("/adminActivityLogPage.html"); }

Target:
public void testContent() { ______TS("content: typical page"); Url logPageUrl = createUrl(Const.ActionURIs.ADMIN_ACTIVITY_LOG_PAGE); logPage = loginAdminToPage(browser, logPageUrl, AdminActivityLogPage.class); logPage.verifyIsCorrectPage(); ______TS("content: navigate to other pages to get some logs"); logPage.navigateTo(createUrl(Const.ActionURIs.ADMIN_HOME_PAGE)); logPage.waitForPageToLoad(); logPage.navigateTo(createUrl(Const.ActionURIs.ADMIN_ACCOUNT_MANAGEMENT_PAGE)); logPage.waitForPageToLoad(); logPage.navigateTo(createUrl(Const.ActionURIs.ADMIN_SEARCH_PAGE)); logPage.waitForPageToLoad(); logPage.navigateTo(createUrl(Const.ActionURIs.ADMIN_ACTIVITY_LOG_PAGE)); logPage.waitForPageToLoad(); assertNotNull(logPage.getFirstActivityLogRow()); logPage.verifyHtmlPart(logPage.getFirstActivityLogRow(), "/adminActivityLogPage.html"); }
Source:
public EntityLoader() { }

Target:
public EntityLoader() { this.qb = null; }
Source:
public void setUp() throws Exception { repo = tmp.getRoot(); j.jenkins .getDescriptorByType(MercurialInstallation.DescriptorImpl.class) .setInstallations(new MercurialInstallation(CACHING_INSTALLATION, "", "hg", false, true, Paths.get("target", "test-data", "custom-cache-dir").toString(), false, "", Collections.<ToolProperty<?>> emptyList())); }

Target:
public void setUp() throws Exception { repo = tmp.getRoot(); j.jenkins .getDescriptorByType(MercurialInstallation.DescriptorImpl.class) .setInstallations(new MercurialInstallation(CACHING_INSTALLATION, "", "hg", false, true, new File(tmp.newFolder(),"custom-cache-dir").getAbsolutePath().toString(), false, "", Collections.<ToolProperty<?>> emptyList())); }
Source:
public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException { if (authConfig.isEnabled()) { QueryInterruptedException unauthorizedError = new QueryInterruptedException( QueryInterruptedException.UNAUTHORIZED, null, null, DruidNode.getDefaultHost() ); unauthorizedError.setStackTrace(new StackTraceElement[0]); OutputStream out = servletResponse.getOutputStream(); Boolean authInfoChecked = null; final HttpServletResponse response = (HttpServletResponse) servletResponse; if (servletRequest.getAttribute(AuthConfig.DRUID_AUTH_TOKEN) == null) { Set<String> supportedAuthSchemes = Sets.newHashSet(); for (Authenticator authenticator : authenticators) { String challengeHeader = authenticator.getAuthChallengeHeader(); if (challengeHeader != null) { supportedAuthSchemes.add(challengeHeader); } } for (String authScheme : supportedAuthSchemes) { response.addHeader("WWW-Authenticate", authScheme); } sendJsonError(response, Response.SC_UNAUTHORIZED, jsonMapper.writeValueAsString(unauthorizedError), out); return; } GenericResponseWrapper wrapper = new GenericResponseWrapper((HttpServletResponse) servletResponse); filterChain.doFilter(servletRequest, wrapper); authInfoChecked = (Boolean) servletRequest.getAttribute(AuthConfig.DRUID_AUTH_TOKEN_CHECKED); if (authInfoChecked == null && !errorOverridesMissingAuth(response.getStatus())) { log.error( "Request did not have an authorization check performed: %s", ((HttpServletRequest) servletRequest).getRequestURI() ); sendJsonError(response, Response.SC_FORBIDDEN, jsonMapper.writeValueAsString(unauthorizedError), out); } else { out.write(wrapper.getData()); } out.close(); } else { filterChain.doFilter(servletRequest, servletResponse); } }

Target:
public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException { final HttpServletResponse response = (HttpServletResponse) servletResponse; final HttpServletRequest request = (HttpServletRequest) servletRequest; if (servletRequest.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) == null) { handleUnauthenticatedRequest(response); return; } filterChain.doFilter(servletRequest, servletResponse); Boolean authInfoChecked = (Boolean) servletRequest.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED); if (authInfoChecked == null && !errorOverridesMissingAuth(response.getStatus())) { handleAuthorizationCheckError( "Request did not have an authorization check performed.", request, response ); } if (authInfoChecked != null && !authInfoChecked && response.getStatus() != Response.SC_FORBIDDEN) { handleAuthorizationCheckError( "Request's authorization check failed but status code was not 403.", request, response ); } }
Source:
public ReferenceWithError<Optional<Entity>> addInSingleLocation(Location location, Map<?,?> flags) { ReferenceWithError<Collection<Entity>> added = addInEachLocation(ImmutableList.of(location), flags); return ReferenceWithError.newInstanceWithInformativeError( Iterables.isEmpty(added.getIgnoringError()) ? Optional.<Entity>absent() : Optional.of(Iterables.getOnlyElement(added.getIgnoringError())), added.getError()); }

Target:
protected ReferenceWithError<Optional<Entity>> addInSingleLocation(Location location, Map<?,?> flags) { ReferenceWithError<Collection<Entity>> added = addInEachLocation(ImmutableList.of(location), flags); Optional<Entity> result = Iterables.isEmpty(added.getMaskingError()) ? Optional.<Entity>absent() : Optional.of(Iterables.getOnlyElement(added.get())); if (!added.hasError()) { return ReferenceWithError.newInstanceWithoutError( result ); } else { if (added.masksErrorIfPresent()) { return ReferenceWithError.newInstanceMaskingError( result, added.getError() ); } else { return ReferenceWithError.newInstanceThrowingError( result, added.getError() ); } } }
Source:
public void anonCanRemindPasswordFromAuthModal() { MailFunctions.deleteAllEmails(credentials.email, credentials.emailPassword); WikiBasePageObject base = new WikiBasePageObject(); base.openWikiPage(wikiURL); DetachedSignInPage loginModal = new DetachedSignInPage(new NavigationBar(driver).clickOnSignIn()); loginModal .clickForgotPasswordLink() .requestLinkForUsername(User.FORGOTTEN_PASSWORD.getUserName()); String resetLink = base.getPasswordResetLink(credentials.email, credentials.emailPassword); ResetPasswordPage resetPass = new ResetPasswordPage(resetLink); resetPass.setNewPassword(User.FORGOTTEN_PASSWORD.getPassword()); Assertion.assertTrue(resetPass.newPasswordSetSuccessfully()); }

Target:
public void anonCanRemindPasswordFromAuthModal() { EmailUtils.deleteAllEmails(credentials.email, credentials.emailPassword); WikiBasePageObject base = new WikiBasePageObject(); base.openWikiPage(wikiURL); DetachedSignInPage loginModal = new DetachedSignInPage(new NavigationBar(driver).clickOnSignIn()); loginModal .clickForgotPasswordLink() .requestLinkForUsername(User.FORGOTTEN_PASSWORD.getUserName()); String resetLink = base.getPasswordResetLink(credentials.email, credentials.emailPassword); ResetPasswordPage resetPass = new ResetPasswordPage(resetLink); resetPass.setNewPassword(User.FORGOTTEN_PASSWORD.getPassword()); assertTrue(resetPass.newPasswordSetSuccessfully()); }
Source:
private void createEmptyFolder() throws Exception { File path = new File(db.getWorkTree(), FOLDER); assertTrue(path.mkdir()); assertTrue(path.isDirectory()); }

Target:
private void createEmptyFolder() throws Exception { File path = new File(db.getWorkTree(), FOLDER); FileUtils.mkdir(path); }
Source:
void handleRevocation(final Collection<TopicPartition> revokedPartitions) { final Set<TopicPartition> remainingPartitions = new HashSet<>(revokedPartitions); final Map<TaskId, Map<TopicPartition, OffsetAndMetadata>> consumedOffsetsAndMetadataPerTask = new HashMap<>(); for (final Task task : tasks.values()) { if (remainingPartitions.containsAll(task.inputPartitions())) { task.prepareSuspend(); if (task.state() != CREATED) { consumedOffsetsAndMetadataPerTask.put(task.id(), task.committableOffsetsAndMetadata()); } } remainingPartitions.removeAll(task.inputPartitions()); } if (!consumedOffsetsAndMetadataPerTask.isEmpty()) { commitOffsetsOrTransaction(consumedOffsetsAndMetadataPerTask); } for (final Task task : tasks.values()) { if (consumedOffsetsAndMetadataPerTask.containsKey(task.id())) { task.suspend(); } } if (!remainingPartitions.isEmpty()) { log.warn("The following partitions are missing from the task partitions. It could potentially " + "due to race condition of consumer detecting the heartbeat failure, or the tasks " + "have been cleaned up by the handleAssignment callback.", remainingPartitions); } }

Target:
void handleRevocation(final Collection<TopicPartition> revokedPartitions) { final Set<TopicPartition> remainingPartitions = new HashSet<>(revokedPartitions); final Map<TaskId, Map<TopicPartition, OffsetAndMetadata>> consumedOffsetsAndMetadataPerTask = new HashMap<>(); for (final Task task : tasks.values()) { if (remainingPartitions.containsAll(task.inputPartitions())) { task.prepareSuspend(); final Map<TopicPartition, OffsetAndMetadata> committableOffsets = task.committableOffsetsAndMetadata(); if (!committableOffsets.isEmpty()) { consumedOffsetsAndMetadataPerTask.put(task.id(), committableOffsets); } } remainingPartitions.removeAll(task.inputPartitions()); } if (!consumedOffsetsAndMetadataPerTask.isEmpty()) { commitOffsetsOrTransaction(consumedOffsetsAndMetadataPerTask); } for (final Task task : tasks.values()) { if (consumedOffsetsAndMetadataPerTask.containsKey(task.id())) { task.suspend(); } } if (!remainingPartitions.isEmpty()) { log.warn("The following partitions are missing from the task partitions. It could potentially " + "due to race condition of consumer detecting the heartbeat failure, or the tasks " + "have been cleaned up by the handleAssignment callback.", remainingPartitions); } }
Source:
private static boolean generatesPrivateAccess(VariableTree tree) { if (tree.parent() instanceof ClassTree && generatesPrivateAccess((ClassTree) tree.parent())) { return !tree.symbol().metadata().isAnnotatedWith("lombok.experimental.PackagePrivate"); } return false; }

Target:
private static boolean generatesPrivateAccess(VariableTree tree) { Tree parent = tree.parent(); if (parent instanceof ClassTree && generatesPrivateAccess((ClassTree) parent)) { return !tree.symbol().metadata().isAnnotatedWith("lombok.experimental.PackagePrivate"); } return false; }
Source:
public GCSSinkConfig(String referenceName, String bucketKey, String projectId, String serviceKeyFile, @Nullable String fileSystemProperties, String bucketDir) { super(referenceName); this.bucketKey = bucketKey; this.projectId = projectId; this.jsonKey = serviceKeyFile; this.bucketDir = bucketDir; this.fileSystemProperties = getFileSystemProperties(fileSystemProperties, projectId, serviceKeyFile); }

Target:
public GCSSinkConfig(String referenceName, String bucketKey, String projectId, String serviceKeyFile, @Nullable String fileSystemProperties, String bucketDir) { super(referenceName); this.bucketKey = bucketKey; this.projectId = projectId; this.jsonKeyFile = serviceKeyFile; this.bucketDir = bucketDir; this.fileSystemProperties = getFileSystemProperties(fileSystemProperties, projectId, serviceKeyFile); }
Source:
public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { if (skip) { return; } String packaging = getPackaging(helper); if (!SUPPORTED_PACKAGE_TYPES.contains(packaging)) { helper .getLog() .info( String.format( "Unsupported package type %s. Skipping artifact size enforcement.", packaging)); return; } String artifactPath = getArtifactPath(helper); long maxArtifactSizeBytes = maxArtifactSizeToBytes(helper); long artifactSize = getArtifact(artifactPath).length(); if (artifactSize >= maxArtifactSizeBytes) { throw new EnforcerRuleException( String.format( MAX_FILE_SIZE_EXCEEDED_MSG, artifactPath, artifactSize, maxArtifactSizeBytes)); } }

Target:
public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { if (skip) { return; } String packaging = getPackaging(helper); if (!SUPPORTED_PACKAGE_TYPES.contains(packaging)) { helper .getLog() .info( String.format( "Unsupported package type %s. Skipping artifact size enforcement.", packaging)); return; } String artifactPath = getArtifactPath(helper); long maxArtifactSizeBytes = maxArtifactSizeToBytes(helper); long artifactSize = getArtifact(artifactPath).length(); if (artifactSize > maxArtifactSizeBytes) { throw new EnforcerRuleException( String.format( MAX_FILE_SIZE_EXCEEDED_MSG, artifactPath, artifactSize, maxArtifactSizeBytes)); } }
Source:
protected void handleReceivedIkePacket(Message message) { ReceivedIkePacket receivedIkePacket = (ReceivedIkePacket) message.obj; IkeHeader ikeHeader = receivedIkePacket.ikeHeader; byte[] ikePacketBytes = receivedIkePacket.ikePacketBytes; if (ikeHeader.isResponseMsg) { DecodeResult decodeResult = IkeMessage.decode(0, ikeHeader, ikePacketBytes); switch (decodeResult.status) { case DECODE_STATUS_OK: handleResponseIkeMessage(decodeResult.ikeMessage); mIkeInitResponseMessage = decodeResult.ikeMessage; mCurrentIkeSaRecord.incrementLocalRequestMessageId(); break; case DECODE_STATUS_PROTECTED_ERROR_MESSAGE: throw new IllegalArgumentException( "Illegal decoding result for an unencrypted message. Decoding" + " result status: " + DECODE_STATUS_PROTECTED_ERROR_MESSAGE); case DECODE_STATUS_UNPROTECTED_ERROR_MESSAGE: throw new UnsupportedOperationException("Cannot handle this error."); default: throw new IllegalArgumentException("Unrecognized decoding status."); } } else { } }

Target:
protected void handleReceivedIkePacket(Message message) { ReceivedIkePacket receivedIkePacket = (ReceivedIkePacket) message.obj; IkeHeader ikeHeader = receivedIkePacket.ikeHeader; byte[] ikePacketBytes = receivedIkePacket.ikePacketBytes; if (ikeHeader.isResponseMsg) { DecodeResult decodeResult = IkeMessage.decode(0, ikeHeader, ikePacketBytes); switch (decodeResult.status) { case DECODE_STATUS_OK: handleResponseIkeMessage(decodeResult.ikeMessage); mIkeInitResponseMessage = decodeResult.ikeMessage; mCurrentIkeSaRecord.incrementLocalRequestMessageId(); break; case DECODE_STATUS_PROTECTED_ERROR_MESSAGE: case DECODE_STATUS_UNPROTECTED_ERROR_MESSAGE: throw new UnsupportedOperationException("Cannot handle this error."); default: throw new IllegalArgumentException( "Invalid decoding status: " + decodeResult.status); } } else { Log.e(TAG, "Received a request while waiting for IKE_INIT response."); } }
Source:
public List<Deployment> getDeployments(){ List<IService> services = conn.getResources(ResourceKind.SERVICE, project.getName()); Collection<IRoute> routes = conn.getResources(ResourceKind.ROUTE, project.getName()); List<Deployment> adapters = new ArrayList<>(services.size()); for (IService service : services) { adapters.add(getDeployment(service, routes)); } return adapters; }

Target:
public List<Deployment> getDeployments(){ List<IService> services = conn.getResources(ResourceKind.SERVICE, project.getName()); Map<String, Collection<IRoute>> serviceToRoutes = mapServiceToRoutes(project.getName()); List<Deployment> adapters = new ArrayList<>(services.size()); for (IService service : services) { adapters.add(getDeployment(service, serviceToRoutes.get(service.getName()))); } return adapters; }
Source:
protected Object handleReadManyCommand(InvocationContext ctx, FlagAffectedCommand command, Collection<?> keys) throws Throwable { try { Object stage; if (!readNeedsLock(ctx, command)) { stage = invokeNext(ctx, command); } else { if (!needRemoteLocks(ctx, keys, command)) { acquireLocalLocks(ctx, command, keys); stage = invokeNext(ctx, command); } else { final TxInvocationContext txContext = (TxInvocationContext) ctx; LockControlCommand lcc = cf.buildLockControlCommand(keys, command.getFlagsBitSet(), txContext.getGlobalTransaction()); stage = invokeNextThenApply(ctx, lcc, (rCtx, rLockCommand, rv) -> { acquireLocalLocks(rCtx, command, keys); return invokeNext(rCtx, command); }); } } return makeStage(stage).andExceptionally(ctx, command, (rCtx, rCommand, t) -> { throw t; }); } catch (Throwable t) { throw t; } }

Target:
protected Object handleReadManyCommand(InvocationContext ctx, FlagAffectedCommand command, Collection<?> keys) throws Throwable { Object maybeStage; if (!readNeedsLock(ctx, command)) { maybeStage = invokeNext(ctx, command); } else { if (!needRemoteLocks(ctx, keys, command)) { acquireLocalLocks(ctx, command, keys); maybeStage = invokeNext(ctx, command); } else { final TxInvocationContext txContext = (TxInvocationContext) ctx; LockControlCommand lcc = cf.buildLockControlCommand(keys, command.getFlagsBitSet(), txContext.getGlobalTransaction()); maybeStage = invokeNextThenApply(ctx, lcc, (rCtx, rLockCommand, rv) -> { acquireLocalLocks(rCtx, command, keys); return invokeNext(rCtx, command); }); } } return maybeStage; }
Source:
private Provider<?> getProvider() { if (provider == null) { provider = getDbFacade().getProviderDao().get(getExternalNetwork().getProviderId()); } return provider; }

Target:
private Provider<?> getProvider() { if (provider == null && getExternalNetwork() != null) { provider = getDbFacade().getProviderDao().get(getExternalNetwork().getProviderId()); } return provider; }
Source:
protected String valueErrorFor(T value) { double number = value.doubleValue(); if (number > upperLimit.doubleValue() || number < lowerLimit.doubleValue()) { return value + " is out of range " + AbstractNumericProperty.rangeString(lowerLimit, upperLimit); } return null; }

Target:
protected String valueErrorFor(T value) { return module.valueErrorFor(value); }
Source:
private void warnDeprecated( String fieldName, Object value ) { Parameter parameter = mojoDescriptor.getParameterMap().get( fieldName ); String deprecated = parameter.getDeprecated(); if ( deprecated != null && !deprecated.isEmpty() ) { if ( !toString( value ).equals( toString( parameter.getDefaultValue() ) ) ) { StringBuilder sb = new StringBuilder( " Parameter '" ); sb.append( fieldName ).append( '\'' ); if ( parameter.getExpression() != null ) { String userParam = parameter.getExpression().replace( "${", "'" ).replace( '}', '\'' ); sb.append( " (User Parameter " ).append( userParam ).append( ")" ); } sb.append( " is deprecated. " ).append( deprecated ); logger.warn( MessageUtils.buffer().warning( sb.toString() ).toString() ); } } }

Target:
private void warnDeprecated( String fieldName, Object value ) { Parameter parameter = mojoDescriptor.getParameterMap().get( fieldName ); String deprecated = parameter.getDeprecated(); if ( deprecated != null && !deprecated.isEmpty() ) { if ( !toString( value ).equals( toString( parameter.getDefaultValue() ) ) ) { StringBuilder sb = new StringBuilder( " Parameter '" ); sb.append( fieldName ).append( '\'' ); if ( parameter.getExpression() != null ) { String userProperty = parameter.getExpression().replace( "${", "'" ).replace( '}', '\'' ); sb.append( " (User Property " ).append( userProperty ).append( ")" ); } sb.append( " is deprecated. " ).append( deprecated ); logger.warn( MessageUtils.buffer().warning( sb.toString() ).toString() ); } } }
Source:
public void destroy() { if (logger.isInfoEnabled()) { logger.info("Destroy registry:" + getUrl()); } Set<URL> destroyRegistered = new HashSet<>(getRegistered()); if (!destroyRegistered.isEmpty()) { for (URL url : new HashSet<>(getRegistered())) { if (url.getParameter(Constants.DYNAMIC_KEY, true)) { try { unregister(url); if (logger.isInfoEnabled()) { logger.info(String.format("Destroy unregister url %s", url)); } } catch (Throwable t) { logger.warn("Failed to unregister url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t); } } } } Map<URL, Set<NotifyListener>> destroySubscribed = new HashMap<>(getSubscribed()); if (!destroySubscribed.isEmpty()) { for (Map.Entry<URL, Set<NotifyListener>> entry : destroySubscribed.entrySet()) { URL url = entry.getKey(); for (NotifyListener listener : entry.getValue()) { try { unsubscribe(url, listener); if (logger.isInfoEnabled()) { logger.info(String.format("Destroy unsubscribe url %s", url)); } } catch (Throwable t) { logger.warn("Failed to unsubscribe url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t); } } } } }

Target:
public void destroy() { if (logger.isInfoEnabled()) { logger.info("Destroy registry:" + getUrl()); } Set<URL> destroyRegistered = new HashSet<>(getRegistered()); for (URL url : destroyRegistered) { if (url.getParameter(Constants.DYNAMIC_KEY, true)) { try { unregister(url); if (logger.isInfoEnabled()) { logger.info("Destroy unregister url " + url); } } catch (Throwable t) { logger.warn("Failed to unregister url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t); } } } Map<URL, Set<NotifyListener>> destroySubscribed = new HashMap<>(getSubscribed()); for (Map.Entry<URL, Set<NotifyListener>> entry : destroySubscribed.entrySet()) { URL url = entry.getKey(); for (NotifyListener listener : entry.getValue()) { try { unsubscribe(url, listener); if (logger.isInfoEnabled()) { logger.info("Destroy unsubscribe url " + url); } } catch (Throwable t) { logger.warn("Failed to unsubscribe url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t); } } } }
Source:
public DefaultAddressedEnvelope(M message, A recipient, A sender) { if (recipient == null && sender == null) { throw new NullPointerException("recipient and sender"); } this.message = ObjectUtil.checkNotNull(message, "message"); this.sender = sender; this.recipient = recipient; }

Target:
public DefaultAddressedEnvelope(M message, A recipient, A sender) { ObjectUtil.checkNotNull(message, "message"); if (recipient == null && sender == null) { throw new NullPointerException("recipient and sender"); } this.message = message; this.sender = sender; this.recipient = recipient; }
Source:
public void validate(final Diagram diagram, final Consumer<Collection<DomainViolation>> resultConsumer) { try { final List<Reader> dmnXMLReaders = new ArrayList<>(); final String uiDiagramXML = dmnMarshaller.marshall(diagram); dmnXMLReaders.add(getStringReader(uiDiagramXML)); final Definitions uiDefinitions = dmnDiagramUtils.getDefinitions(diagram); final List<Import> uiImports = uiDefinitions.getImport(); final List<org.kie.dmn.model.api.Import> dmnImports = uiImports.stream().map(ImportConverter::dmnFromWb).collect(Collectors.toList()); final Map<org.kie.dmn.model.api.Import, String> importedDiagramsXML = importsHelper.getImportXML(diagram.getMetadata(), dmnImports); importedDiagramsXML.values().forEach(importedDiagramXML -> dmnXMLReaders.add(getStringReader(importedDiagramXML))); final Reader[] aDMNXMLReaders = new Reader[]{}; final List<DMNMessage> messages = dmnValidator .validateUsing(DMNValidator.Validation.VALIDATE_MODEL, DMNValidator.Validation.VALIDATE_COMPILATION, DMNValidator.Validation.ANALYZE_DECISION_TABLE) .theseModels(dmnXMLReaders.toArray(aDMNXMLReaders)); resultConsumer.accept(convert(messages)); } catch (IOException ioe) { LOGGER.error("Error while converting diagram with UUID [" + diagram.getName() + "] to XML.", ioe); } }

Target:
public void validate(final Diagram diagram, final Consumer<Collection<DomainViolation>> resultConsumer) { final List<Reader> dmnXMLReaders = new ArrayList<>(); try { final String uiDiagramXML = dmnMarshaller.marshall(diagram); dmnXMLReaders.add(getStringReader(uiDiagramXML)); final Definitions uiDefinitions = dmnDiagramUtils.getDefinitions(diagram); final List<Import> uiImports = uiDefinitions.getImport(); final List<org.kie.dmn.model.api.Import> dmnImports = uiImports.stream().map(ImportConverter::dmnFromWb).collect(Collectors.toList()); final Map<org.kie.dmn.model.api.Import, String> importedDiagramsXML = importsHelper.getImportXML(diagram.getMetadata(), dmnImports); importedDiagramsXML.values().forEach(importedDiagramXML -> dmnXMLReaders.add(getStringReader(importedDiagramXML))); final Reader[] aDMNXMLReaders = new Reader[]{}; final List<DMNMessage> messages = dmnValidator .validateUsing(DMNValidator.Validation.VALIDATE_MODEL, DMNValidator.Validation.VALIDATE_COMPILATION, DMNValidator.Validation.ANALYZE_DECISION_TABLE) .theseModels(dmnXMLReaders.toArray(aDMNXMLReaders)); resultConsumer.accept(convert(messages)); } catch (IOException ioe) { LOGGER.error("Error while converting diagram with UUID [" + diagram.getName() + "] to XML.", ioe); } finally { dmnXMLReaders.forEach(reader -> { try { reader.close(); } catch (IOException ioe) { } }); } }
Source:
public abstract void create(boolean bare) throws IOException; @Deprecated public File getDirectory() { return getGitDir(); }

Target:
public abstract void create(boolean bare) throws IOException; public File getDirectory() { return gitDir; }
Source:
public OAuthConsumerAppDTO getOAuthApplicationData(String consumerKey) throws IdentityOAuthAdminException { OAuthConsumerAppDTO dto = new OAuthConsumerAppDTO(); OAuthAppDAO dao = new OAuthAppDAO(); try { OAuthAppDO app = dao.getAppInformation(consumerKey); if (app != null) { dto.setApplicationName(app.getApplicationName()); dto.setCallbackUrl(app.getCallbackUrl()); dto.setOauthConsumerKey(app.getOauthConsumerKey()); dto.setOauthConsumerSecret(app.getOauthConsumerSecret()); dto.setOAuthVersion(app.getOauthVersion()); dto.setGrantTypes(app.getGrantTypes()); } return dto; } catch (InvalidOAuthClientException | IdentityOAuth2Exception e) { throw new IdentityOAuthAdminException(e.getMessage(), e); } }

Target:
public OAuthConsumerAppDTO getOAuthApplicationData(String consumerKey) throws IdentityOAuthAdminException { OAuthConsumerAppDTO dto = new OAuthConsumerAppDTO(); OAuthAppDAO dao = new OAuthAppDAO(); try { OAuthAppDO app = dao.getAppInformation(consumerKey); if (app != null) { dto.setApplicationName(app.getApplicationName()); dto.setCallbackUrl(app.getCallbackUrl()); dto.setOauthConsumerKey(app.getOauthConsumerKey()); dto.setOauthConsumerSecret(app.getOauthConsumerSecret()); dto.setOAuthVersion(app.getOauthVersion()); dto.setGrantTypes(app.getGrantTypes()); } return dto; } catch (InvalidOAuthClientException | IdentityOAuth2Exception e) { throw new IdentityOAuthAdminException("Error while retrieving the app information using consumer key", e); } }
Source:
public Response add(Storage storage) { validateParameters(storage, "address", "type", "host"); StorageServerConnections storageConnection = getMapper(Storage.class, StorageServerConnections.class).map(storage, null); Guid hostId = getHostId(storage.getHost()); switch (storageConnection.getstorage_type()) { case ISCSI: validateParameters(storage, "iqn", "port"); break; case NFS: validateParameters(storage, "path"); break; case LOCALFS: validateParameters(storage, "path"); break; case POSIXFS: case GLUSTERFS: validateParameters(storage, "path", "vfsType"); break; default: break; } return performCreate(VdcActionType.AddStorageServerConnection, getAddParams(storageConnection, hostId), ENTITY_RETRIEVER); }

Target:
public Response add(Storage storage) { validateParameters(storage, "address", "type", "host"); StorageServerConnections storageConnection = getMapper(Storage.class, StorageServerConnections.class).map(storage, null); Guid hostId = getHostId(storage.getHost()); switch (storageConnection.getstorage_type()) { case ISCSI: validateParameters(storage, "iqn", "port"); break; case NFS: case LOCALFS: validateParameters(storage, "path"); break; case POSIXFS: case GLUSTERFS: validateParameters(storage, "path", "vfsType"); break; default: break; } return performCreate(VdcActionType.AddStorageServerConnection, getAddParams(storageConnection, hostId), ENTITY_RETRIEVER); }
Source:
private void releaseSlots(Iterable<AllocatedSlot> slotsToReturnToOwner, Throwable cause) { for (AllocatedSlot slotToReturn : slotsToReturnToOwner) { Preconditions.checkState(!slotToReturn.isUsed(), "Free slot must not be used."); LOG.info("Releasing slot [{}].", slotToReturn.getAllocationId()); final ResourceProfile matchingResourceProfile = getMatchingResourceProfile(slotToReturn.getAllocationId()); fulfilledResourceRequirements = fulfilledResourceRequirements.subtract(matchingResourceProfile, 1); slotToRequirementProfileMappings.remove(slotToReturn.getAllocationId()); final CompletableFuture<Acknowledge> freeSlotFuture = slotToReturn.getTaskManagerGateway().freeSlot( slotToReturn.getAllocationId(), cause, rpcTimeout); freeSlotFuture.whenComplete((Acknowledge ignored, Throwable throwable) -> { if (throwable != null) { LOG.debug("Releasing slot of registered TaskExecutor failed. Discarding slot.", slotToReturn.getAllocationId(), slotToReturn.getTaskManagerId(), throwable); } }); } }

Target:
private void releaseSlots(Iterable<AllocatedSlot> slotsToReturnToOwner, Throwable cause) { for (AllocatedSlot slotToReturn : slotsToReturnToOwner) { Preconditions.checkState(!slotToReturn.isUsed(), "Free slot must not be used."); if (LOG.isDebugEnabled()) { LOG.info("Releasing slot [{}].", slotToReturn.getAllocationId(), cause); } else { LOG.info("Releasing slot [{}].", slotToReturn.getAllocationId()); } final ResourceProfile matchingResourceProfile = getMatchingResourceProfile(slotToReturn.getAllocationId()); fulfilledResourceRequirements = fulfilledResourceRequirements.subtract(matchingResourceProfile, 1); slotToRequirementProfileMappings.remove(slotToReturn.getAllocationId()); final CompletableFuture<Acknowledge> freeSlotFuture = slotToReturn.getTaskManagerGateway().freeSlot( slotToReturn.getAllocationId(), cause, rpcTimeout); freeSlotFuture.whenComplete((Acknowledge ignored, Throwable throwable) -> { if (throwable != null) { LOG.debug("Releasing slot of registered TaskExecutor failed. Discarding slot.", slotToReturn.getAllocationId(), slotToReturn.getTaskManagerId(), throwable); } }); } }
Source:
public ServiceProvider getApplicationExcludingFileBasedSPs(String applicationName, String tenantDomain) throws IdentityApplicationManagementException { Collection<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getApplicationMgtListeners(); for (ApplicationMgtListener listener : listeners) { if (!listener.doPreGetApplication(applicationName, tenantDomain)) { return null; } } try { startTenantFlow(tenantDomain); ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO(); ServiceProvider serviceProvider = appDAO.getApplication(applicationName, tenantDomain); if (serviceProvider != null) { loadApplicationPermissions(applicationName, serviceProvider); } for (ApplicationMgtListener listener : listeners) { if (!listener.doPostGetApplication(serviceProvider, applicationName, tenantDomain)) { return null; } } return serviceProvider; } catch (Exception e) { String error = "Error occurred while retrieving the application, " + applicationName; log.error(error, e); throw new IdentityApplicationManagementException(error, e); } finally { endTenantFlow(); } }

Target:
public ServiceProvider getApplicationExcludingFileBasedSPs(String applicationName, String tenantDomain) throws IdentityApplicationManagementException { ServiceProvider serviceProvider = null; Collection<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getApplicationMgtListeners(); for (ApplicationMgtListener listener : listeners) { if (!listener.doPreGetApplicationExcludingFileBasedSPs(applicationName, tenantDomain)) { return null; } } try { startTenantFlow(tenantDomain); ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO(); serviceProvider = appDAO.getApplication(applicationName, tenantDomain); if (serviceProvider != null) { loadApplicationPermissions(applicationName, serviceProvider); } } catch (Exception e) { String error = "Error occurred while retrieving the application, " + applicationName; log.error(error, e); throw new IdentityApplicationManagementException(error, e); } finally { endTenantFlow(); } for (ApplicationMgtListener listener : listeners) { if (!listener.doPostGetApplicationExcludingFileBasedSPs(serviceProvider, applicationName, tenantDomain)) { return null; } } return serviceProvider; }
Source:
public void toggleLineBreakpoints(final IWorkbenchPart part, final ISelection selection) throws CoreException { Job job = new Job("Script Toggle Line Breakpoint") { protected IStatus run(IProgressMonitor monitor) { final ITextEditor editor = getTextEditor(part); if (editor != null && selection instanceof ITextSelection) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); int lineNumber = ((ITextSelection) selection) .getStartLine() + 1; final String debugModelId = getDebugModelId(); final IBreakpoint breakpoint = BreakpointUtils .findLineBreakpoint(editor, lineNumber, debugModelId); if (breakpoint != null) { breakpoint.delete(); } else { final IDocumentProvider documentProvider = editor .getDocumentProvider(); if (documentProvider == null) { return Status.CANCEL_STATUS; } final IDocument document = documentProvider .getDocument(editor.getEditorInput()); lineNumber = findBreakpointLine(document, lineNumber - 1, getValidator()) + 1; if (lineNumber != BREAKPOINT_LINE_NOT_FOUND) { if (BreakpointUtils.findLineBreakpoint(editor, lineNumber, debugModelId) == null) { BreakpointUtils.addLineBreakpoint(editor, lineNumber, debugModelId); } else { report( NLS .bind( Messages.ScriptToggleBreakpointAdapter_breakpointAlreadySetAtLine, new Object[] { Integer.valueOf( lineNumber) }), part); } } else { report( Messages.ScriptToggleBreakpointAdapter_invalidBreakpointPosition, part); } } } catch (CoreException e) { DLTKDebugUIPlugin.log(e); } } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); }

Target:
public void toggleLineBreakpoints(final IWorkbenchPart part, final ISelection selection) throws CoreException { Job job = new Job("Script Toggle Line Breakpoint") { protected IStatus run(IProgressMonitor monitor) { final ITextEditor editor = getTextEditor(part); if (editor != null && selection instanceof ITextSelection) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); int lineNumber = ((ITextSelection) selection) .getStartLine() + 1; final String debugModelId = getDebugModelId(); final IBreakpoint breakpoint = BreakpointUtils .findLineBreakpoint(editor, lineNumber, debugModelId); if (breakpoint != null) { breakpoint.delete(); } else { final IDocumentProvider documentProvider = editor .getDocumentProvider(); if (documentProvider == null) { return Status.CANCEL_STATUS; } final IDocument document = documentProvider .getDocument(editor.getEditorInput()); lineNumber = findBreakpointLine(document, lineNumber - 1, getValidator()) + 1; if (lineNumber != BREAKPOINT_LINE_NOT_FOUND) { if (BreakpointUtils.findLineBreakpoint(editor, lineNumber, debugModelId) == null) { BreakpointUtils.addLineBreakpoint(editor, lineNumber, debugModelId); } else { report(NLS.bind( Messages.ScriptToggleBreakpointAdapter_breakpointAlreadySetAtLine, lineNumber), part); } } else { report(Messages.ScriptToggleBreakpointAdapter_invalidBreakpointPosition, part); } } } catch (CoreException e) { DLTKDebugUIPlugin.log(e); } } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); }
Source:
public List<AsyncTasks> getTasksByEntity(Guid entityId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource(); parameterSource.addValue("entity_id", entityId); return getCallsHandler().executeReadList("GetAsyncTasksByEntityId", AsyncTaskRowMapper.instance, parameterSource); }

Target:
public List<AsyncTasks> getTasksByEntity(Guid entityId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("entity_id", entityId); return getCallsHandler().executeReadList("GetAsyncTasksByEntityId", AsyncTaskRowMapper.instance, parameterSource); }
Source:
public void testGetDocContent_includedMetadata() throws Exception { options = TestObjectFactory.newConfigOptions( ImmutableMap.of("filenet.includedMetadata", "foo, bar")); String id = "{AAAAAAAA-0000-0000-0000-000000000000}"; DocId docId = newDocId(new Id(id)); MockObjectStore os = getObjectStore(); mockDocument(os, id, DOCUMENT_TIMESTAMP, RELEASED, 42d, "text/plain", ImmutableList.<Property>of( mockProperty("foo", "fooValue"), mockProperty("bar", "barValue")), new AccessPermissionListMock(), new ActiveMarkingListMock()); DocumentTraverser traverser = new DocumentTraverser(options); Request request = new MockRequest(docId); RecordingResponse response = new RecordingResponse(); traverser.getDocContent(new Id(id), request, response); assertEquals( new Metadata( ImmutableMap.of("foo", "fooValue", "bar", "barValue") .entrySet()), response.getMetadata()); }

Target:
public void testGetDocContent_includedMetadata() throws Exception { options = TestObjectFactory.newConfigOptions( ImmutableMap.of("filenet.includedMetadata", "foo, bar")); String id = "{AAAAAAAA-0000-0000-0000-000000000000}"; DocId docId = newDocId(new Id(id)); MockObjectStore os = getObjectStore(); mockDocument(os, id, DOCUMENT_TIMESTAMP, RELEASED, 42d, "text/plain", ImmutableList.<Property>of( mockProperty("foo", "fooValue"), mockProperty("bar", "barValue"), mockProperty("baz", "bazValue")), new AccessPermissionListMock(), new ActiveMarkingListMock()); DocumentTraverser traverser = new DocumentTraverser(options); Request request = new MockRequest(docId); RecordingResponse response = new RecordingResponse(); traverser.getDocContent(new Id(id), request, response); assertEquals( new Metadata( ImmutableMap.of("foo", "fooValue", "bar", "barValue").entrySet()), response.getMetadata()); }
Source:
public CompletionStage<ExecutionResult> executeAsync(ExecutionContext executionContext, GraphQLObjectType parentType, Object source, Map<String, List<Field>> fields) { Map<String, Supplier<CompletionStage<ExecutionResult>>> executingFields = new LinkedHashMap<>(); for (String fieldName : fields.keySet()) { List<Field> fieldList = fields.get(fieldName); executingFields.put(fieldName, () -> resolveFieldAsync(executionContext, parentType, source, fieldList)); } CompletionStage<Map<String, ExecutionResult>> mapCompletionStage1 = awaitFields(executingFields); return mapCompletionStage1.thenApply(map -> { Map<String, Object> map2 = new HashMap<>(); map.forEach((key, result) -> { map2.put(key, result.getData()); }); return new graphql.ExecutionResultImpl(map2, executionContext.getErrors()); }); }

Target:
public CompletionStage<ExecutionResult> executeAsync(ExecutionContext executionContext, GraphQLObjectType parentType, Object source, Map<String, List<Field>> fields) { Map<String, Supplier<CompletionStage<ExecutionResult>>> fieldsToExecute = fields.keySet() .stream() .collect(Collectors.toMap( Function.identity(), field -> () -> resolveFieldAsync(executionContext, parentType, source, fields.get(field)), (a, b) -> a, LinkedHashMap::new )); return executeFields(fieldsToExecute).<ExecutionResult>thenApply(resultMap -> { Map<String, Object> dataMap = new HashMap<>(); resultMap.forEach((key, result) -> { dataMap.put(key, result.getData()); }); return new ExecutionResultImpl(dataMap, executionContext.getErrors()); }).exceptionally(e -> { if (e.getCause() instanceof NonNullException) { return new ExecutionResultImpl(null, null); } throw new RuntimeException(e); }); }