auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void exec(final Context ctx) throws IOException { final String uri = ctx.memo().read().xpath("/memo/uri/text()").get(0); final Repo repo = this.github.repos().get( new Coordinates.Simple( URI.create(uri).getPath() .replaceFirst("/", "").replaceFirst("\\.git", "") ) ); final XML content = new YamlXML( <START> IOUtils.toString(repo.contents().get(".thindeck.yml").raw()) <END> ).get(); final Directives dirs = new Directives() .xpath("/memo").addIf("domains"); for (final String domain : content.xpath(" dirs.xpath("/memo/domains").add("domain").set(domain); } dirs.up().up().addIf("ports"); for (final String port : content.xpath(" dirs.xpath("/memo/ports").add("port").set(port); } ctx.memo().update(dirs); }</code><technical_language>encoding here.. this problems. CharEncoding.UTF_8</technical_language>

Target:
public void exec(final Context ctx) throws IOException { final String uri = ctx.memo().read().xpath("/memo/uri/text()").get(0); final Repo repo = this.github.repos().get( new Coordinates.Simple( URI.create(uri).getPath() .replaceFirst("/", "").replaceFirst("\\.git", "") ) ); final XML content = new YamlXML( IOUtils.toString( repo.contents().get(".thindeck.yml").raw(), CharEncoding.UTF_8 ) ).get(); final Directives dirs = new Directives() .xpath("/memo").addIf("domains"); for (final String domain : content.xpath(" dirs.xpath("/memo/domains").add("domain").set(domain); } dirs.up().up().addIf("ports"); for (final String port : content.xpath(" dirs.xpath("/memo/ports").add("port").set(port); } ctx.memo().update(dirs); }
Source:
<code>public void itemChanged(T item) { if (item != null && <START> getView().asWidget().isVisible()) { <END> getView().setMainTabSelectedItem(item); } else if (item == null && getView().asWidget().isVisible() && modelProvider.getMainModel().getItems().isEmpty()) { placeManager.revealPlace(getMainTabRequest()); } }</code><technical_language>Nit-pick: consider extracting repeating expressions meaningfully-named variables, for example: boolean detailViewVisible = getView().asWidget().isVisible(); This conditions if/else more readable</technical_language>

Target:
public void itemChanged(T item) { boolean widgetVisible = getView().asWidget().isVisible(); if (item != null && widgetVisible) { getView().setMainTabSelectedItem(item); } else if (item == null && widgetVisible && modelProvider.getMainModel().getItems().isEmpty()) { placeManager.revealPlace(getMainTabRequest()); } }
Source:
<code><START> public void setUp() throws <END> Exception { verifierWebWorkerConnection = spy(new VerifierWebWorkerConnectionImpl(initialize, "verifier/dtableVerifier/dtableVerifier.nocache.js", poster, receiver) { @Override Worker createWorker() { return worker; } }); }</code><technical_language>@Rikkola is this "throws' Exception necessary</technical_language>

Target:
public void setUp() { verifierWebWorkerConnection = spy(new VerifierWebWorkerConnectionImpl(initialize, "verifier/dtableVerifier/dtableVerifier.nocache.js", poster, receiver) { @Override protected Worker createWorker() { return worker; } }); }
Source:
<code>private static long parseEnumEnumerator(CommonTree enumerator, EnumDeclaration enumDeclaration, long lastHigh) throws ParseException { List<CommonTree> children = enumerator.getChildren(); long low = 0, high = 0; boolean valueSpecified = false; String label = null; for (CommonTree child : children) { if (isUnaryString(child)) { label = parseUnaryString(child); } else if (child.getType() == CTFParser.ENUM_VALUE) { valueSpecified = true; low = parseUnaryInteger((CommonTree) child.getChild(0)); high = low; } else if (child.getType() == CTFParser.ENUM_VALUE_RANGE) { valueSpecified = true; low = parseUnaryInteger((CommonTree) child.getChild(0)); high = parseUnaryInteger((CommonTree) child.getChild(1)); } else { childTypeError(child); } } if (!valueSpecified) { low = lastHigh + 1; high = low; } if (low > high) { throw new ParseException("enum low value greater than high value"); } if (!enumDeclaration.add(low, high, label)) { throw new ParseException("enum declarator values overlap."); } if (valueSpecified && (BigInteger.valueOf(low).compareTo(enumDeclaration.getContainerType().getMinValue()) == -1 || BigInteger.valueOf(high).compareTo(enumDeclaration.getContainerType().getMaxValue()) == 1)) { <START> throw new ParseException("enum value is not in range"); END> } return high; }</code><technical_language>Good</technical_language>

Target:
private static long parseEnumEnumerator(CommonTree enumerator, EnumDeclaration enumDeclaration, long lastHigh) throws ParseException { List<CommonTree> children = enumerator.getChildren(); long low = 0, high = 0; boolean valueSpecified = false; String label = null; for (CommonTree child : children) { if (isAnyUnaryString(child)) { label = parseUnaryString(child); } else if (child.getType() == CTFParser.ENUM_VALUE) { valueSpecified = true; low = parseUnaryInteger((CommonTree) child.getChild(0)); high = low; } else if (child.getType() == CTFParser.ENUM_VALUE_RANGE) { valueSpecified = true; low = parseUnaryInteger((CommonTree) child.getChild(0)); high = parseUnaryInteger((CommonTree) child.getChild(1)); } else { childTypeError(child); } } if (!valueSpecified) { low = lastHigh + 1; high = low; } if (low > high) { throw new ParseException("enum low value greater than high value"); } if (!enumDeclaration.add(low, high, label)) { throw new ParseException("enum declarator values overlap."); } if (valueSpecified && (BigInteger.valueOf(low).compareTo(enumDeclaration.getContainerType().getMinValue()) == -1 || BigInteger.valueOf(high).compareTo(enumDeclaration.getContainerType().getMaxValue()) == 1)) { throw new ParseException("enum value is not in range"); } return high; }
Source:
<code>private static LintAnnotationsModel getAnnotations(@NonNull NlModel model, @NonNull ProgressIndicator progress) { <START> assert ApplicationManager.getApplication().isReadAccessAllowed(); <END> LintAnnotationsModel lintModel = new LintAnnotationsModel(); XmlFile xmlFile = model.getFile(); AndroidLintExternalAnnotator annotator = new AndroidLintExternalAnnotator(); State state = annotator.collectInformation(xmlFile); state = annotator.doAnnotate(state); if (state == null) { return lintModel; } for (ProblemData problemData : state.getProblems()) { if (progress.isCanceled()) { break; } TextRange range = problemData.getTextRange(); if (range.getStartOffset() == range.getEndOffset()) { continue; } final PsiElement startElement = xmlFile.findElementAt(range.getStartOffset()); final PsiElement endElement = xmlFile.findElementAt(range.getEndOffset()); if (startElement == null || endElement == null) { continue; } NlComponent component = model.findViewByPsi(startElement); if (component == null) { continue; } Issue issue = problemData.getIssue(); Pair<AndroidLintInspectionBase, HighlightDisplayLevel> pair = AndroidLintUtil.getHighlighLevelAndInspection(xmlFile.getProject(), issue, xmlFile); if (pair == null) { continue; } AndroidLintInspectionBase inspection = pair.getFirst(); if (inspection == null) { continue; } HighlightDisplayLevel level = pair.getSecond(); HighlightDisplayKey key = HighlightDisplayKey.find(inspection.getShortName()); if (key == null) { continue; } lintModel.addIssue(component, inspection, level); } return lintModel; }</code><technical_language>a separate assertReadAccessAllowed method</technical_language>

Target:
private static LintAnnotationsModel getAnnotations(@NonNull NlModel model, @NonNull ProgressIndicator progress) { ApplicationManager.getApplication().assertReadAccessAllowed(); LintAnnotationsModel lintModel = new LintAnnotationsModel(); XmlFile xmlFile = model.getFile(); AndroidLintExternalAnnotator annotator = new AndroidLintExternalAnnotator(); State state = annotator.collectInformation(xmlFile); state = annotator.doAnnotate(state); if (state == null) { return lintModel; } for (ProblemData problemData : state.getProblems()) { if (progress.isCanceled()) { break; } TextRange range = problemData.getTextRange(); final PsiElement startElement = xmlFile.findElementAt(range.getStartOffset()); final PsiElement endElement = xmlFile.findElementAt(range.getEndOffset()); if (startElement == null || endElement == null) { continue; } NlComponent component = model.findViewByPsi(startElement); if (component == null) { continue; } Issue issue = problemData.getIssue(); Pair<AndroidLintInspectionBase, HighlightDisplayLevel> pair = AndroidLintUtil.getHighlighLevelAndInspection(xmlFile.getProject(), issue, xmlFile); if (pair == null) { continue; } AndroidLintInspectionBase inspection = pair.getFirst(); if (inspection == null) { continue; } HighlightDisplayLevel level = pair.getSecond(); HighlightDisplayKey key = HighlightDisplayKey.find(inspection.getShortName()); if (key == null) { continue; } lintModel.addIssue(component, inspection, level); } return lintModel; }
Source:
<code>public UpdateVmCommand(T parameters) { super(parameters); if (getVdsGroup() != null) { setStoragePoolId(getVdsGroup().getStoragePoolId()); } if (isVmExist()) { setCustomDefinedProperties(parameters.getVmStaticData()); setCustomDefinedProperties(getVm().getStaticData()); } <START> if (parameters.isConsoleEnabled() == null) { <END> parameters.setConsoleEnabled(false); } }</code><technical_language>i update null "don't touch device setting" (if leave it, if create)</technical_language>

Target:
public UpdateVmCommand(T parameters) { super(parameters); if (getVdsGroup() != null) { setStoragePoolId(getVdsGroup().getStoragePoolId()); } if (isVmExist()) { setCustomDefinedProperties(parameters.getVmStaticData()); setCustomDefinedProperties(getVm().getStaticData()); } }
Source:
<code>private static IncrementalIndex makeIncrementalIndex( Bucket theBucket, AggregatorFactory[] aggs, HadoopDruidIndexerConfig config, Iterable<String> oldDimOrder ) { final HadoopTuningConfig tuningConfig = config.getSchema().getTuningConfig(); final IncrementalIndexSchema indexSchema = new IncrementalIndexSchema.Builder() .withMinTimestamp(theBucket.time.getMillis()) .withDimensionsSpec(config.getSchema().getDataSchema().getParser()) .withQueryGranularity(config.getSchema().getDataSchema().getGranularitySpec().getQueryGranularity()) .withMetrics(aggs) .build(); OnheapIncrementalIndex newIndex = new OnheapIncrementalIndex( indexSchema, <START> true, <END> tuningConfig.getRowFlushBoundary() ); if (oldDimOrder != null && !indexSchema.getDimensionsSpec().hasCustomDimensions()) { newIndex.loadDimensionIterable(oldDimOrder); } return newIndex; }</code><technical_language>hadoop batch ingestion a config ignoreInvalidRows instead</technical_language>

Target:
private static IncrementalIndex makeIncrementalIndex( Bucket theBucket, AggregatorFactory[] aggs, HadoopDruidIndexerConfig config, Iterable<String> oldDimOrder ) { final HadoopTuningConfig tuningConfig = config.getSchema().getTuningConfig(); final IncrementalIndexSchema indexSchema = new IncrementalIndexSchema.Builder() .withMinTimestamp(theBucket.time.getMillis()) .withDimensionsSpec(config.getSchema().getDataSchema().getParser()) .withQueryGranularity(config.getSchema().getDataSchema().getGranularitySpec().getQueryGranularity()) .withMetrics(aggs) .build(); OnheapIncrementalIndex newIndex = new OnheapIncrementalIndex( indexSchema, !tuningConfig.isIgnoreInvalidRows(), tuningConfig.getRowFlushBoundary() ); if (oldDimOrder != null && !indexSchema.getDimensionsSpec().hasCustomDimensions()) { newIndex.loadDimensionIterable(oldDimOrder); } return newIndex; }
Source:
<code>public void testOpenExistingStateFile() { <START> TestLttngKernelAnalysisModule module2 = new TestLttngKernelAnalysisModule(BENCHMARK_FILE_NAME); <END> try { module2.setTrace(testTrace.getTrace()); } catch (TmfAnalysisException e) { fail(); } module2.schedule(); assertTrue(module2.waitForCompletion(new NullProgressMonitor())); ITmfStateSystem ssb2 = module2.getStateSystem(); assertNotNull(ssb2); assertEquals(startTime, ssb2.getStartTime()); assertEquals(endTime, ssb2.getCurrentEndTime()); }</code><technical_language>TEST_FILE_NAME here, goal of test is re-open file created in @BeforeClass. BENCHMARK_FILE_NAME, this previous test identical ;) previous test, passed a 'null' state provider, is allowed for cases file exists (throws exception if doesn't). lose ability do if analysis module, necessarily a bad thing</technical_language>

Target:
public void testOpenExistingStateFile() { try { ITmfStateSystem ssb2 = TmfStateSystemFactory.newFullHistory(stateFile, null, true); assertNotNull(ssb2); assertEquals(startTime, ssb2.getStartTime()); assertEquals(endTime, ssb2.getCurrentEndTime()); } catch (TmfTraceException e) { fail(); } }
Source:
<code>protected void startInternal() { super.startInternal(); service.registerAction(getStartPattern(), m -> { <START> for (int i = 0; i < 10; i++) { <END> String matchedString = m.group(); String fileName = matchedString.substring(matchedString.lastIndexOf("/")); try { FileInputStream fileInputStream = new FileInputStream(Paths.get(service.home, "logs", fileName).toFile()); getOutputReader().setStream(fileInputStream); return; } catch (FileNotFoundException e) { log.error("Log file not created yet"); Utils.sleep(1000); continue; } } throw new IllegalStateException("Failed to attach reader to log file"); }); }</code><technical_language>Configurable timeout</technical_language>

Target:
protected void startInternal() { super.startInternal(); service.registerAction(getStartPattern(), m -> { long end = TimeService.currentTimeMillis() + service.logCreationTimeout; while (TimeService.currentTimeMillis() <= end) { String matchedString = m.group(); String fileName = matchedString.substring(matchedString.lastIndexOf("/")); try { FileInputStream fileInputStream = new FileInputStream(Paths.get(service.home, "logs", fileName).toFile()); getOutputReader().setStream(fileInputStream); return; } catch (FileNotFoundException e) { log.error("Log file not created yet"); Utils.sleep(1000); continue; } } throw new IllegalStateException("Failed to attach reader to log file"); }); }
Source:
<code>private void validateQosOverriddenInterfaces() { for (VdsNetworkInterface iface : params.getInterfaces()) { String networkName = iface.getNetworkName(); if (networkName == null) { continue; } <START> if (iface.isQosOverridden() && !iface.getQos().isEmpty()) { <END> if (!hostNetworkQosSupported) { addViolation(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NETWORK_QOS_NOT_SUPPORTED, networkName); } HostNetworkQosValidator qosValidator = new HostNetworkQosValidator(iface.getQos()); if (qosValidator.requiredValuesPresent() != ValidationResult.VALID) { addViolation(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NETWORK_QOS_SETUP_NETWORKS_MISSING_VALUES, networkName); } if (qosValidator.valuesConsistent() != ValidationResult.VALID) { addViolation(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NETWORK_QOS_SETUP_NETWORKS_INCONSISTENT_VALUES, networkName); } } } }</code><technical_language>Please check iface.getQos() != null</technical_language>

Target:
private void validateQosOverriddenInterfaces() { for (VdsNetworkInterface iface : params.getInterfaces()) { String networkName = iface.getNetworkName(); if (networkName == null || !iface.isQosOverridden()) { continue; } if (!hostNetworkQosSupported) { addViolation(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NETWORK_QOS_NOT_SUPPORTED, networkName); } if (iface.getQos() != null && !iface.getQos().isEmpty()) { HostNetworkQosValidator qosValidator = new HostNetworkQosValidator(iface.getQos()); if (qosValidator.requiredValuesPresent() != ValidationResult.VALID) { addViolation(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NETWORK_QOS_SETUP_NETWORKS_MISSING_VALUES, networkName); } if (qosValidator.valuesConsistent() != ValidationResult.VALID) { addViolation(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NETWORK_QOS_SETUP_NETWORKS_INCONSISTENT_VALUES, networkName); } } } }
Source:
<code>static PathAddress translateProxyPath(OperationContext context, PathAddress address) throws OperationFailedException { <START> Set<Resource.ResourceEntry> children = context.readResourceFromRoot(address).getChildren(ProxyConfigurationResourceDefinition.WILDCARD_PATH.getKey()); <END> if (children.size() != 1) { throw new OperationFailedException(ModClusterLogger.ROOT_LOGGER.legacyOperationsWithMultipleProxies()); } PathAddress proxyPath = PathAddress.pathAddress(ProxyConfigurationResourceDefinition.pathElement(children.iterator().next().getName())); address = address.append(proxyPath); return address; }</code><technical_language>This context.readResourceFromRoot(address, false)..... This a flaw in this PR fix it. :)</technical_language>

Target:
static PathAddress translateProxyPath(OperationContext context, PathAddress address) throws OperationFailedException { Set<Resource.ResourceEntry> children = context.readResourceFromRoot(address, false).getChildren(ProxyConfigurationResourceDefinition.WILDCARD_PATH.getKey()); if (children.size() != 1) { throw new OperationFailedException(ModClusterLogger.ROOT_LOGGER.legacyOperationsWithMultipleProxies()); } PathAddress proxyPath = PathAddress.pathAddress(ProxyConfigurationResourceDefinition.pathElement(children.iterator().next().getName())); address = address.append(proxyPath); return address; }
Source:
<code>private void importRootProject(File rootDir, IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor); progress.setWorkRemaining(3); WorkspaceOperations workspaceOperations = CorePlugin.workspaceOperations(); Optional<IProject> projectOrNull = workspaceOperations.findProjectByLocation(rootDir); if (!projectOrNull.isPresent() && this.newProjectHandler.shouldImport()) { String projectName = findFreeProjectName(rootDir.getName()); projectOrNull = Optional.of(workspaceOperations.createProject(projectName, rootDir, ImmutableList.<String>of(), progress.newChild(1))); } if (projectOrNull.isPresent()) { IProject project = projectOrNull.get(); project.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1)); <START> CorePlugin.workspaceOperations().addNature(project, GradleProjectNature.ID, progress.newChild(1)); <END> this.newProjectHandler.afterImport(project); progress.worked(1); } }</code><technical_language>refreshing adding Gradle nature here? I this done next step (synchronization)</technical_language>

Target:
private void importRootProject(File rootDir, IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor); progress.setWorkRemaining(3); WorkspaceOperations workspaceOperations = CorePlugin.workspaceOperations(); Optional<IProject> projectOrNull = workspaceOperations.findProjectByLocation(rootDir); if (!projectOrNull.isPresent() && this.newProjectHandler.shouldImportNewProjects()) { String projectName = findFreeProjectName(rootDir.getName()); projectOrNull = Optional.of(workspaceOperations.createProject(projectName, rootDir, ImmutableList.<String>of(), progress.newChild(1))); } if (projectOrNull.isPresent()) { IProject project = projectOrNull.get(); project.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1)); CorePlugin.workspaceOperations().addNature(project, GradleProjectNature.ID, progress.newChild(1)); this.newProjectHandler.afterProjectImported(project); progress.worked(1); } }
Source:
<code>public ActionResult execute() throws EntityDoesNotExistException { Assumption.assertPostParamNotNull(Const.ParamsNames.REGKEY, regkey); String nextUrl = getNextUrl(); statusToAdmin = "Action Student Clicked Join Link" + (account.googleId == null ? "<br/>Email: " + account.email : "<br/>Google ID: " + account.googleId + "<br/>Key: " + regkey); if (logic.getCurrentUser() == null) { return createRedirectToAuthenticatedJoinPage(nextUrl); } String confirmUrl = Const.ActionURIs.STUDENT_COURSE_JOIN_AUTHENTICATED + "?" + Const.ParamsNames.REGKEY + "=" + regkey + "&" + Const.ParamsNames.NEXT_URL + "=" + Sanitizer.sanitizeForNextUrl(nextUrl); <START> String nextUrlType = nextUrl.replaceFirst("^(/page/[A-Za-z]+)\\?.*$", "$1"); <END> boolean isRedirectResult = Const.SystemParams.PAGES_ACCESSIBLE_WITHOUT_GOOGLE_LOGIN.contains(nextUrlType); String courseId = new Url(nextUrl).get(Const.ParamsNames.COURSE_ID); data = new StudentCourseJoinConfirmationPageData(account, student, confirmUrl, Logic.getLogoutUrl(Sanitizer.sanitizeForNextUrl(confirmUrl)), isRedirectResult, courseId); excludeStudentDetailsFromResponseParams(); return createShowPageResult( Const.ViewURIs.STUDENT_COURSE_JOIN_CONFIRMATION, data); }</code><technical_language>good if this kind of unit tested. e.g. extract a small static method write a unit tests it</technical_language>

Target:
public ActionResult execute() throws EntityDoesNotExistException { Assumption.assertPostParamNotNull(Const.ParamsNames.REGKEY, regkey); String nextUrl = getNextUrl(); statusToAdmin = "Action Student Clicked Join Link" + (account.googleId == null ? "<br/>Email: " + account.email : "<br/>Google ID: " + account.googleId + "<br/>Key: " + regkey); if (logic.getCurrentUser() == null) { return createRedirectToAuthenticatedJoinPage(nextUrl); } String confirmUrl = Const.ActionURIs.STUDENT_COURSE_JOIN_AUTHENTICATED + "?" + Const.ParamsNames.REGKEY + "=" + regkey + "&" + Const.ParamsNames.NEXT_URL + "=" + Sanitizer.sanitizeForNextUrl(nextUrl); String nextUrlType = getPageTypeOfUrl(nextUrl); boolean isRedirectResult = !Const.SystemParams.PAGES_ACCESSIBLE_WITHOUT_REGISTRATION.contains(nextUrlType); boolean isNextUrlAccessibleWithoutLogin = Const.SystemParams.PAGES_ACCESSIBLE_WITHOUT_GOOGLE_LOGIN.contains(nextUrlType); String courseId = student.course; data = new StudentCourseJoinConfirmationPageData(account, student, confirmUrl, Logic.getLogoutUrl(Sanitizer.sanitizeForNextUrl(confirmUrl)), isRedirectResult, courseId, isNextUrlAccessibleWithoutLogin); excludeStudentDetailsFromResponseParams(); return createShowPageResult( Const.ViewURIs.STUDENT_COURSE_JOIN_CONFIRMATION, data); }
Source:
<code>public boolean add(Object resource, Utils.ValueHolder<UInt128> outHash) { try { if (resource instanceof Resource) { resource = getSortedJsonStringValueFromResource((Resource)resource); } outHash.v = DistinctHash.getHash(resource); boolean value = true; if (lastHash != null) { value = !(outHash.v.equals(lastHash)); } lastHash = outHash.v; return value; } catch (IOException e) { <START> throw new IllegalStateException("Failed to add value to distinct map" +e); <END> } }</code><technical_language>loose root exception this suggestion throw new IllegalStateException("Failed add distinct map", e);</technical_language>

Target:
public boolean add(Object resource, Utils.ValueHolder<UInt128> outHash) { try { if (resource instanceof Resource) { resource = getSortedJsonStringValueFromResource((Resource)resource); } outHash.v = DistinctHash.getHash(resource); boolean value = true; if (lastHash != null) { value = !(outHash.v.equals(lastHash)); } lastHash = outHash.v; return value; } catch (IOException e) { throw new IllegalStateException("Failed to add value to distinct map", e); } }
Source:
<code>public void rethrowsExceptionsFromMappingFunction() { RuntimeException ex = new IllegalStateException("bad"); TransactionService unusableService = SplitKeyDelegatingTransactionService.create( num -> { throw ex; }, transactionServiceMap); <START> assertThatThrownBy(() -> unusableService.get(5L)) <END> .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("bad"); }</code><technical_language>change? no</technical_language>

Target:
public void rethrowsExceptionsFromMappingFunction() { RuntimeException ex = new IllegalStateException("bad"); TransactionService unusableService = new SplitKeyDelegatingTransactionService<>( num -> { throw ex; }, transactionServiceMap); assertThatThrownBy(() -> unusableService.get(5L)).isEqualTo(ex); }
Source:
<code>public void closeEditors() { IFile file = getBookmarksFile(); FileEditorInput input = new FileEditorInput(file); IWorkbench wb = PlatformUI.getWorkbench(); for (IWorkbenchWindow wbWindow : wb.getWorkbenchWindows()) { for (IWorkbenchPage wbPage : wbWindow.getPages()) { for (IEditorReference editorReference : wbPage.getEditorReferences()) { try { <START> IEditorPart editor = editorReference.getEditor(false); <END> if (editor instanceof ITmfTraceEditor && editorReference.getEditorInput().equals(input)) { wbPage.closeEditor(editor, false); } } catch (PartInitException e) { Activator.getDefault().logError(NLS.bind(Messages.TmfCommonProjectElement_ErrorClosingEditor, getName()), e); } } } } }</code><technical_language>If editor tab is in background editor part is instantiated, this returns null editor tab is closed. This is OK for "Delete Supplementary Files...", is OK if "Delete" trace. give focus editor tab get "Invalid IEditorInput: trace name"</technical_language>

Target:
public void closeEditors() { IFile file = getBookmarksFile(); FileEditorInput input = new FileEditorInput(file); IWorkbench wb = PlatformUI.getWorkbench(); for (IWorkbenchWindow wbWindow : wb.getWorkbenchWindows()) { for (IWorkbenchPage wbPage : wbWindow.getPages()) { for (IEditorReference editorReference : wbPage.getEditorReferences()) { try { if (editorReference.getEditorInput().equals(input)) { IEditorPart editor = editorReference.getEditor(false); if (editor == null || editor instanceof ITmfTraceEditor) { wbPage.closeEditors(new IEditorReference[] { editorReference }, false); } } } catch (PartInitException e) { Activator.getDefault().logError(NLS.bind(Messages.TmfCommonProjectElement_ErrorClosingEditor, getName()), e); } } } } }
Source:
<code>private void removeDeletedSessions(Guid clusterId, final Map<String, GlusterGeoRepSession> sessionsMap) { List<GlusterGeoRepSession> sessionsInDb = getGeoRepDao().getGeoRepSessionsInCluster(clusterId); <START> if (sessionsInDb == null) { <END> return; } List<GlusterGeoRepSession> sessionsToDelete = new ArrayList<>(); for (GlusterGeoRepSession grepSession: sessionsInDb) { if (sessionsMap.get(grepSession.getSessionKey()) == null) { sessionsToDelete.add(grepSession); } } for (final GlusterGeoRepSession session : sessionsToDelete) { log.debug("geo-rep session: detected removed for volume: {}", session.getSessionKey(), session.getMasterVolumeName()); getGeoRepDao().remove(session.getId()); logGeoRepMessage(AuditLogType.GLUSTER_GEOREP_SESSION_DELETED_FROM_CLI, clusterId, session); } }</code><technical_language>|| sessionsInDb.isEmpty()</technical_language>

Target:
private void removeDeletedSessions(Guid clusterId, final Map<String, GlusterGeoRepSession> sessionsMap) { List<GlusterGeoRepSession> sessionsInDb = getGeoRepDao().getGeoRepSessionsInCluster(clusterId); if (sessionsInDb == null || sessionsInDb.isEmpty()) { return; } List<GlusterGeoRepSession> sessionsToDelete = new ArrayList<>(); for (GlusterGeoRepSession grepSession: sessionsInDb) { if (sessionsMap.get(grepSession.getSessionKey()) == null) { sessionsToDelete.add(grepSession); } } for (final GlusterGeoRepSession session : sessionsToDelete) { log.debug("geo-rep session '{}' detected removed for volume '{}'", session.getSessionKey(), session.getMasterVolumeName()); getGeoRepDao().remove(session.getId()); logGeoRepMessage(AuditLogType.GLUSTER_GEOREP_SESSION_DELETED_FROM_CLI, clusterId, session); } }
Source:
<code>public void initialize(boolean newInstance, InstanceInitializationFactory factory, String locale) { for (Enumeration en = formInstances.keys(); en.hasMoreElements(); ) { String instanceId = (String)en.nextElement(); DataInstance instance = formInstances.get(instanceId); formInstances.put(instanceId, instance.initialize(factory, instanceId)); } if (newInstance) { preloadInstance(mainInstance.getRoot()); } if (getLocalizer() != null) { if(locale == null || !getLocalizer().hasLocale(locale)) { if(getLocalizer().getLocale() == null) { getLocalizer().setToDefault(); } } else { getLocalizer().setLocale(locale); <START> } <END> } if (newInstance) { actionController.triggerActionsFromEvent(Action.EVENT_XFORMS_READY, this); } initAllTriggerables(); }</code><technical_language>lift this code a helper, is pretty contained</technical_language>

Target:
public void initialize(boolean newInstance, InstanceInitializationFactory factory, String locale) { for (Enumeration en = formInstances.keys(); en.hasMoreElements(); ) { String instanceId = (String)en.nextElement(); DataInstance instance = formInstances.get(instanceId); formInstances.put(instanceId, instance.initialize(factory, instanceId)); } if (newInstance) { preloadInstance(mainInstance.getRoot()); } initLocale(locale); if (newInstance) { actionController.triggerActionsFromEvent(Action.EVENT_XFORMS_READY, this); } initAllTriggerables(); }
Source:
<code>public DatabaseRepairSubTab() { reportsTable = new FlexTable(); reportsTable.addStyleName("dataTable"); <START> add(new HTML("<h3>Form corruption report</h3>")); <END> add(reportsTable); reviewPanel = new FlowPanel("div"); add(new HTML("<h3>Review panel</h3>")); add(reviewPanel); update(); }</code><technical_language>this Form report. Corruption is scary</technical_language>

Target:
public DatabaseRepairSubTab() { add(new HTML("<h3>Form corruption report</h3>")); reportsTable = new FlexTable(); reportsTable.addStyleName("dataTable"); add(reportsTable); noProblemsNotice = new HTMLPanel("div", "No problems to report"); add(noProblemsNotice); reviewPanelTitle = new HTML("<h3>Review panel</h3>"); add(reviewPanelTitle); reviewPanel = new FlowPanel("div"); add(reviewPanel); update(); }
Source:
<code><START> public PaneBasedSelectionWizardDescription createPaneBasedSelectionWizardDescription() { <END> PaneBasedSelectionWizardDescriptionImpl paneBasedSelectionWizardDescription = new PaneBasedSelectionWizardDescriptionImpl(); return paneBasedSelectionWizardDescription; }</code><technical_language>Lost @not-generated code</technical_language>

Target:
public PaneBasedSelectionWizardDescription createPaneBasedSelectionWizardDescription() { PaneBasedSelectionWizardDescriptionImpl paneBasedSelectionWizardDescription = new PaneBasedSelectionWizardDescriptionImpl(); ElementSelectVariable elementSelectVariable = this.createElementSelectVariable(); elementSelectVariable.setName("element"); ContainerViewVariable containerViewVariable = this.createContainerViewVariable(); containerViewVariable.setName("containerView"); SelectContainerVariable selectContainerVariable = this.createSelectContainerVariable(); selectContainerVariable.setName("container"); paneBasedSelectionWizardDescription.setElement(elementSelectVariable); paneBasedSelectionWizardDescription.setContainer(selectContainerVariable); paneBasedSelectionWizardDescription.setContainerView(containerViewVariable); InitialOperation initialOperation = this.createInitialOperation(); paneBasedSelectionWizardDescription.setInitialOperation(initialOperation); return paneBasedSelectionWizardDescription; }
Source:
<code>public void should_throw_exception_when_accessing_api_after_logout() throws LoginException, LogoutException { expectedEx.expect(IllegalStateException.class); expectedEx.expectMessage("You must call login prior to access any API."); client.login(VALID_USERNAME, VALID_PASSWORD); client.logout(); <START> client.getProcessAPI(); <END> }</code><technical_language>Move expectedExption call expected throw exception</technical_language>

Target:
public void should_throw_exception_when_accessing_api_after_logout() throws LoginException, LogoutException { client.login(VALID_USERNAME, VALID_PASSWORD); client.logout(); expectedEx.expect(IllegalStateException.class); expectedEx.expectMessage("You must call login() prior to accessing any API."); client.getProcessAPI(); }
Source:
<code>private Action authenticate(final BasicAuth basicAuth) { return new Action.Simple() { @Override <START> public F.Promise<Result> call(final Http.Context ctx) throws Throwable { <END> final boolean isAuthorized; final String authorizationHeader = ctx.request().getHeader(AUTHORIZATION); if (authorizationHeader != null) { isAuthorized = basicAuth.isAuthorized(authorizationHeader); } else { isAuthorized = false; ctx.response().setHeader(WWW_AUTHENTICATE, "Basic realm=\"" + basicAuth.getRealm() + "\""); } return authenticationResult(ctx, isAuthorized); } private F.Promise<Result> authenticationResult(final Http.Context ctx, final boolean isAuthorized) throws Throwable { if (isAuthorized) { Logger.debug("Authorized"); return delegate.call(ctx); } else { Logger.debug("Unauthorized"); return F.Promise.pure(unauthorized()); } } }; }</code><technical_language>I refactored version</technical_language>

Target:
private Action authenticate(final BasicAuth basicAuth) { return new Action.Simple() { @Override public F.Promise<Result> call(final Http.Context ctx) throws Throwable { final boolean isAuthorized; final String authorizationHeader = ctx.request().getHeader(AUTHORIZATION); if (authorizationHeader != null) { isAuthorized = basicAuth.isAuthorized(authorizationHeader); } else { isAuthorized = false; ctx.response().setHeader(WWW_AUTHENTICATE, "Basic realm=\"" + basicAuth.getRealm() + "\""); } return authenticationResult(ctx, isAuthorized); } private F.Promise<Result> authenticationResult(final Http.Context ctx, final boolean isAuthorized) throws Throwable { if (isAuthorized) { LOGGER.debug("Authorized"); return delegate.call(ctx); } else { LOGGER.info("Unauthorized"); return F.Promise.pure(unauthorized()); } } }; }
Source:
<code>public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) { AuthorizationMatrixProperty as = new AuthorizationMatrixProperty(); String prop = reader.peekNextChild(); <START> if (prop!=null && prop.equals("useProjectSecurity")) { <END> reader.moveDown(); reader.getValue(); reader.moveUp(); prop = reader.peekNextChild(); } if ("blocksInheritance".equals(prop)) { reader.moveDown(); as.setBlocksInheritance("true".equals(reader.getValue())); reader.moveUp(); } while (reader.hasMoreChildren()) { reader.moveDown(); try { as.add(reader.getValue()); } catch (IllegalArgumentException ex) { Logger.getLogger(AuthorizationMatrixProperty.class.getName()) .log(Level.WARNING,"Skipping a non-existent permission",ex); RobustReflectionConverter.addErrorInContext(context, ex); } reader.moveUp(); } if (GlobalMatrixAuthorizationStrategy.migrateHudson2324(as.grantedPermissions)) OldDataMonitor.report(context, "1.301"); return as; }</code><technical_language>a non-findbugs related change... is incorrect..</technical_language>

Target:
public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) { AuthorizationMatrixProperty as = new AuthorizationMatrixProperty(); String prop = reader.peekNextChild(); if (prop!=null && prop.equals("useProjectSecurity")) { reader.moveDown(); reader.getValue(); reader.moveUp(); prop = reader.peekNextChild(); } else if ("blocksInheritance".equals(prop)) { reader.moveDown(); as.setBlocksInheritance("true".equals(reader.getValue())); reader.moveUp(); } while (reader.hasMoreChildren()) { reader.moveDown(); try { as.add(reader.getValue()); } catch (IllegalArgumentException ex) { Logger.getLogger(AuthorizationMatrixProperty.class.getName()) .log(Level.WARNING,"Skipping a non-existent permission",ex); RobustReflectionConverter.addErrorInContext(context, ex); } reader.moveUp(); } if (GlobalMatrixAuthorizationStrategy.migrateHudson2324(as.grantedPermissions)) OldDataMonitor.report(context, "1.301"); return as; }
Source:
<code>public boolean isExecutable() { <START> IReview review = ((ReviewDetailSection) getContext()).getReview(); <END> ReviewStatus currentStatus = review.getState(); return getModelObject() != null && getModelObject().getId() != null && currentStatus != ReviewStatus.ABANDONED && currentStatus != ReviewStatus.MERGED; }</code><technical_language>I a method getReview() this do this casting more once</technical_language>

Target:
public boolean isExecutable() { ReviewStatus currentStatus = getReview().getState(); return getModelObject() != null && getModelObject().getId() != null && currentStatus != ReviewStatus.ABANDONED && currentStatus != ReviewStatus.MERGED; }
Source:
<code>public static String makeLogName(long zxid) { <START> return LOG_FILE_PREFIX + "." + Long.toHexString(zxid); <END> }</code><technical_language>I if LOG_FILE_PREFIX included dot, for validation</technical_language>

Target:
public static String makeLogName(long zxid) { return FileTxnLog.LOG_FILE_PREFIX + "." + Long.toHexString(zxid); }
Source:
<code>private long copyPackBypassCache(PackOutputStream out, ReadableChannel rc) throws IOException { ByteBuffer buf = newCopyBuffer(out, rc); long position = 12; long remaining = length - (12 + 20); boolean packHeadSkipped = false; while (0 < remaining) { DfsBlock b = cache.get(key, alignToBlock(position)); if (b != null) { int ptr = (int) (position - b.start); int n = (int) Math.min(b.size() - ptr, remaining); if (n <= 0) { throw packfileIsTruncated(); } b.write(out, position, n); position += n; remaining -= n; rc.position(position); packHeadSkipped = true; continue; } int ptr = packHeadSkipped ? 0 : 12; buf.position(0); int bufLen = read(rc, buf); <START> if (bufLen <= ptr) { <END> throw packfileIsTruncated(); } int n = (int) Math.min(bufLen - ptr, remaining); out.write(buf.array(), ptr, n); position += n; remaining -= n; packHeadSkipped = true; } return position; }</code><technical_language>Sanity check: for pack 12 bytes, if zero objects, objects 20-byte checksum trailer. Good</technical_language>

Target:
private long copyPackBypassCache(PackOutputStream out, ReadableChannel rc) throws IOException { ByteBuffer buf = newCopyBuffer(out, rc); long position = 12; long remaining = length - (12 + 20); boolean packHeadSkipped = false; while (0 < remaining) { DfsBlock b = cache.get(key, alignToBlock(position)); if (b != null) { int ptr = (int) (position - b.start); if (b.size() <= ptr) { throw packfileIsTruncated(); } int n = (int) Math.min(b.size() - ptr, remaining); b.write(out, position, n); position += n; remaining -= n; rc.position(position); packHeadSkipped = true; continue; } int ptr = packHeadSkipped ? 0 : 12; buf.position(0); int bufLen = read(rc, buf); if (bufLen <= ptr) { throw packfileIsTruncated(); } int n = (int) Math.min(bufLen - ptr, remaining); out.write(buf.array(), ptr, n); position += n; remaining -= n; packHeadSkipped = true; } return position; }
Source:
<code>protected boolean canDoAction() { boolean retValue; <START> List<EventNotificationMethod> event_notification_methods = (DbFacade.getInstance() <END> .getEventDao().getEventNotificationMethodsById(getParameters().getEventSubscriber().getmethod_id())); if (event_notification_methods.size() > 0) { List<event_map> event_map = DbFacade.getInstance().getEventDao().getEventMapByName( getParameters().getEventSubscriber().getevent_up_name()); if (event_map.size() > 0) { DbUser user = DbFacade.getInstance() .getDbUserDao() .get(getParameters().getEventSubscriber().getsubscriber_id()); if (user == null) { addCanDoActionMessage(VdcBllMessages.USER_MUST_EXIST_IN_DB); retValue = false; } else { retValue = ValidateRemove(event_notification_methods, getParameters().getEventSubscriber(), user); } } else { addCanDoActionMessage(VdcBllMessages.EN_UNSUPPORTED_NOTIFICATION_EVENT); retValue = false; } } else { addCanDoActionMessage(VdcBllMessages.EN_UNKNOWN_NOTIFICATION_METHOD); retValue = false; } return retValue; }</code><technical_language>eventNotificationMethods</technical_language>

Target:
protected boolean canDoAction() { boolean retValue; List<EventNotificationMethod> eventNotificationMethods = (DbFacade.getInstance() .getEventDao().getEventNotificationMethodsById(getParameters().getEventSubscriber().getmethod_id())); if (eventNotificationMethods.size() > 0) { List<event_map> event_map = DbFacade.getInstance().getEventDao().getEventMapByName( getParameters().getEventSubscriber().getevent_up_name()); if (event_map.size() > 0) { DbUser user = DbFacade.getInstance() .getDbUserDao() .get(getParameters().getEventSubscriber().getsubscriber_id()); if (user == null) { addCanDoActionMessage(VdcBllMessages.USER_MUST_EXIST_IN_DB); retValue = false; } else { retValue = ValidateRemove(eventNotificationMethods, getParameters().getEventSubscriber(), user); } } else { addCanDoActionMessage(VdcBllMessages.EN_UNSUPPORTED_NOTIFICATION_EVENT); retValue = false; } } else { addCanDoActionMessage(VdcBllMessages.EN_UNKNOWN_NOTIFICATION_METHOD); retValue = false; } return retValue; }
Source:
<code>public PasswordAuthenticator create(Map<String, String> config) { try { Bootstrap app = new Bootstrap( binder -> { configBinder(binder).bindConfig(LdapConfig.class); binder.bind(LdapAuthenticator.class).in(Scopes.SINGLETON); <START> if (config.get(INTERNAL_LDAP_USER_CONFIG) != null) { <END> httpClientBinder(binder).bindGlobalFilter(new BasicAuthRequestFilter(config.get(INTERNAL_LDAP_USER_CONFIG), config.get(INTERNAL_LDAP_PASSWORD_CONFIG))); } }); Injector injector = app .strictConfig() .doNotInitializeLogging() .setRequiredConfigurationProperties(config) .initialize(); return injector.getInstance(LdapAuthenticator.class); } catch (Exception e) { throwIfUnchecked(e); throw new RuntimeException(e); } }</code><technical_language>bind filter app context bootstrap here. work bind this filter single http client in Presto core. This is totally Guice context. if is of a plugin</technical_language>

Target:
public PasswordAuthenticator create(Map<String, String> config) { try { Bootstrap app = new Bootstrap( binder -> { configBinder(binder).bindConfig(LdapConfig.class); binder.bind(LdapAuthenticator.class).in(Scopes.SINGLETON); }); Injector injector = app .strictConfig() .doNotInitializeLogging() .setRequiredConfigurationProperties(config) .initialize(); return injector.getInstance(LdapAuthenticator.class); } catch (Exception e) { throwIfUnchecked(e); throw new RuntimeException(e); } }
Source:
<code>private void addRunCmds(StringBuilder b) { <START> if (runcmds.size() > 0) { <END> for (String runCmd : runcmds) { b.append(DockerFileDictionaryEnum.RUN.name()).append(" ").append(runCmd).append("\n"); } } }</code><technical_language>This is redundant, for run if size is 0</technical_language>

Target:
private void addRunCmds(StringBuilder b) { for (String runCmd : runcmds) { b.append(DockerFileDictionary.RUN.name()).append(" ").append(runCmd).append("\n"); } }
Source:
<code>public void createTable(TableDescriptor desc) throws IOException { <START> getResult(asyncAdmin.createTable(desc)); <END> }</code><technical_language>Please asyncAdmin for async operations, createTableAsync. synchronous operations remain before</technical_language>

Target:
public void createTable(TableDescriptor desc) throws IOException { createTable(desc, null); }
Source:
<code>public void start(final ServiceProvider<Service> serviceProvider) { try { Properties properties = new Properties(); properties.put(ConnectionPropertyNames.CONNECTION_NAME, CONNECTION_PREFIX + this.entityIdentifier); properties.put(ConnectionPropertyNames.CONNECTION_TIMEOUT, Long.toString(operationTimeouts.getLifecycleOperationTimeout().toMillis())); clusterConnection = ConnectionFactory.connect(clusterUri, properties); } catch (ConnectionException ex) { throw new RuntimeException(ex); } entityFactory = new EhcacheClientEntityFactory(clusterConnection, operationTimeouts); try { if (configuration.isAutoCreate()) { entity = autoCreateEntity(); } else { try { entity = entityFactory.retrieve(entityIdentifier, configuration.getServerConfiguration()); } catch (EntityNotFoundException e) { throw new IllegalStateException("The clustered tier manager '" + entityIdentifier + "' does not exist." + " Please review your configuration.", e); } catch (TimeoutException e) { throw new RuntimeException("Could not connect to the clustered tier manager '" + entityIdentifier + "'; retrieve operation timed out", e); } } } catch (RuntimeException e) { entityFactory = null; try { <START> Connection conn = clusterConnection; <END> clusterConnection = null; if (conn != null) { conn.close(); } } catch (IOException ex) { LOGGER.warn("Error closing cluster connection: " + ex); } throw e; } }</code><technical_language>triggered connection closing changes? ... duplication ... I a method wants extracted</technical_language>

Target:
public void start(final ServiceProvider<Service> serviceProvider) { initClusterConnection(); createEntityFactory(); try { if (configuration.isAutoCreate()) { entity = autoCreateEntity(); } else { try { entity = entityFactory.retrieve(entityIdentifier, configuration.getServerConfiguration()); } catch (EntityNotFoundException e) { throw new IllegalStateException("The clustered tier manager '" + entityIdentifier + "' does not exist." + " Please review your configuration.", e); } catch (TimeoutException e) { throw new RuntimeException("Could not connect to the clustered tier manager '" + entityIdentifier + "'; retrieve operation timed out", e); } } } catch (RuntimeException e) { entityFactory = null; closeConnection(); throw e; } }
Source:
<code>private Analyzer getAnalyzer(String lang) { <START> if (lang == null) { <END> return new StandardAnalyzer(); } switch(lang) { case "ar": return new ArabicAnalyzer(); case "bg": return new BulgarianAnalyzer(); case "br": return new BrazilianAnalyzer(); case "ca": return new CatalanAnalyzer(); case "cz": return new CzechAnalyzer(); case "da": return new DanishAnalyzer(); case "de": return new GermanAnalyzer(); case "el": return new GreekAnalyzer(); case "en": return new EnglishAnalyzer(); case "es": return new SpanishAnalyzer(); case "eu": return new BasqueAnalyzer(); case "fa": return new PersianAnalyzer(); case "fi": return new FinnishAnalyzer(); case "fr": return new FrenchAnalyzer(); case "ga": return new IrishAnalyzer(); case "gl": return new GalicianAnalyzer(); case "hi": return new HindiAnalyzer(); case "hu": return new HungarianAnalyzer(); case "hy": return new ArmenianAnalyzer(); case "id": return new IndonesianAnalyzer(); case "it": return new ItalianAnalyzer(); case "lt": return new LithuanianAnalyzer(); case "lv": return new LatvianAnalyzer(); case "nl": return new DutchAnalyzer(); case "no": return new NorwegianAnalyzer(); case "pt": return new PortugueseAnalyzer(); case "ro": return new RomanianAnalyzer(); case "ru": return new RussianAnalyzer(); case "sv": return new SwedishAnalyzer(); case "th": return new ThaiAnalyzer(); case "tr": return new TurkishAnalyzer(); default: return new StandardAnalyzer(); } }</code><technical_language>is worthy this class instantiated language. I abstract file enforces class is a singleton UDF, if call "initialize" method *i think* application environment ensures instance exists explicit code too</technical_language>

Target:
private Analyzer getAnalyzer(String lang) { if (!analyzers.containsKey(lang)) { analyzers.put(lang, createAnalyzer(lang)); } return analyzers.get(lang); }
Source:
<code>public void service(HttpRequest request, HttpResponse response) throws IOException { if (request.getMethod() != "POST") { response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD); return; } String bodyString = request.getReader().lines().collect(Collectors.joining()); JsonObject body = (new Gson()).fromJson(bodyString, JsonObject.class); if (body == null || !body.has("text")) { response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); return; } if (!isValidSlackWebhook(request, bodyString)) { response.setStatusCode(HttpURLConnection.HTTP_UNAUTHORIZED); return; } String query = body.get("text").getAsString(); <START> List<Object> kgResults = searchKnowledgeGraph(query); <END> BufferedWriter writer = response.getWriter(); writer.write(formatSlackMessage(kgResults, query)); }</code><technical_language>List<Object> rarely a good idea</technical_language>

Target:
public void service(HttpRequest request, HttpResponse response) throws IOException { if (request.getMethod() != "POST") { response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD); return; } String bodyString = request.getReader().lines().collect(Collectors.joining()); JsonObject body = (new Gson()).fromJson(bodyString, JsonObject.class); if (body == null || !body.has("text")) { response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); return; } if (!isValidSlackWebhook(request, bodyString)) { response.setStatusCode(HttpURLConnection.HTTP_UNAUTHORIZED); return; } String query = body.get("text").getAsString(); JsonObject kgResponse = searchKnowledgeGraph(query); BufferedWriter writer = response.getWriter(); writer.write(formatSlackMessage(kgResponse, query)); }