auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Connection getDBConnection() { Connection dbConnection = null; try { Class.forName(DB_DRIVER); } catch (ClassNotFoundException e) { <START> LOG.error("Driver not found", e); <END> } try { dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); return dbConnection; } catch (SQLException e) { LOG.error("Exception in getting connection handle", e); } return dbConnection; }</code><technical_language>Rethrow exception</technical_language>

Target:
private static Connection getDBConnection() { Connection dbConnection = null; try { Class.forName(DB_DRIVER); } catch (ClassNotFoundException e) { LOG.error("Driver not found", e); throw new RuntimeException(e); } try { dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); return dbConnection; } catch (SQLException e) { LOG.error("Exception in getting connection handle", e); throw new RuntimeException(e); } }
Source:
<code>public FactoryDto createFactory(@NotNull final Map<String, String> factoryParameters) throws BadRequestException, ServerException { <START> final GithubUrl githubUrl = githubUrlParser.parse(factoryParameters.remove(URL_PARAMETER_NAME)); <END> FactoryDto factory = urlFactoryBuilder .createFactoryFromDevfile( githubUrl, fileName -> urlFetcher.fetch(githubUrl.rawFileLocation(fileName)), factoryParameters) .orElseGet( () -> urlFactoryBuilder .createFactoryFromJson(githubUrl) .orElseGet( () -> newDto(FactoryDto.class) .withV(CURRENT_VERSION) .withSource("repo"))); if (factory.getWorkspace() != null) { return projectConfigDtoMerger.merge( factory, () -> { return newDto(ProjectConfigDto.class) .withSource(githubSourceStorageBuilder.buildWorkspaceConfigSource(githubUrl)) .withName(githubUrl.getRepository()) .withPath("/".concat(githubUrl.getRepository())); }); } else if (factory.getDevfile() == null) { factory.setDevfile(urlFactoryBuilder.buildDefaultDevfile(githubUrl.getRepository())); factory .getDevfile() .setProjects( Collections.singletonList( newDto(ProjectDto.class) .withSource(githubSourceStorageBuilder.buildDevfileSource(githubUrl)) .withName(githubUrl.getRepository()))); } return factory; }</code><technical_language>need do that. control query parameter naming devfile schema ensure clashes</technical_language>

Target:
public FactoryDto createFactory(@NotNull final Map<String, String> factoryParameters) throws BadRequestException, ServerException { final GithubUrl githubUrl = githubUrlParser.parse(factoryParameters.get(URL_PARAMETER_NAME)); FactoryDto factory = urlFactoryBuilder .createFactoryFromDevfile( githubUrl, fileName -> urlFetcher.fetch(githubUrl.rawFileLocation(fileName)), extractOverrideParams(factoryParameters)) .orElseGet( () -> urlFactoryBuilder .createFactoryFromJson(githubUrl) .orElseGet( () -> newDto(FactoryDto.class) .withV(CURRENT_VERSION) .withSource("repo"))); if (factory.getWorkspace() != null) { return projectConfigDtoMerger.merge( factory, () -> { return newDto(ProjectConfigDto.class) .withSource(githubSourceStorageBuilder.buildWorkspaceConfigSource(githubUrl)) .withName(githubUrl.getRepository()) .withPath("/".concat(githubUrl.getRepository())); }); } else if (factory.getDevfile() == null) { factory.setDevfile(urlFactoryBuilder.buildDefaultDevfile(githubUrl.getRepository())); factory .getDevfile() .setProjects( Collections.singletonList( newDto(ProjectDto.class) .withSource(githubSourceStorageBuilder.buildDevfileSource(githubUrl)) .withName(githubUrl.getRepository()))); } return factory; }
Source:
<code>public Class<? extends IndexManager> getIndexManagerType(XClass entity, SearchConfiguration cfg, WorkerBuildContext buildContext) { ServiceManager serviceManager = buildContext.getServiceManager(); IndexManagerFactory indexManagerFactory = serviceManager.requestService( IndexManagerFactory.class ); String indexName = getIndexName( entity, cfg ); Properties[] indexProperties = getIndexProperties( cfg, indexName ); String indexManagerImplementationName = indexProperties[0].getProperty( Environment.INDEX_MANAGER_IMPL_NAME ); <START> String indexManagerImplementationKey = indexManagerImplementationName != null ? <END> indexManagerImplementationName : DEFAULT_INDEX_MANAGER_KEY; if ( indexManagerImplementationsRegistry.containsKey( indexManagerImplementationKey ) ) { return indexManagerImplementationsRegistry.get( indexManagerImplementationKey ); } try { Class<? extends IndexManager> indexManagerType; if ( StringHelper.isEmpty( indexManagerImplementationName ) ) { indexManagerType = indexManagerFactory.createDefaultIndexManager().getClass(); } else { indexManagerType = indexManagerFactory.createIndexManagerByName( indexManagerImplementationName ).getClass(); } indexManagerImplementationsRegistry.put( indexManagerImplementationKey, indexManagerType ); return indexManagerType; } finally { serviceManager.releaseService( IndexManagerFactory.class ); } }</code><technical_language>StringHelper#isEmpty() consistent usage below</technical_language>

Target:
public Class<? extends IndexManager> getIndexManagerType(XClass entity, SearchConfiguration cfg, WorkerBuildContext buildContext) { ServiceManager serviceManager = buildContext.getServiceManager(); IndexManagerFactory indexManagerFactory = serviceManager.requestService( IndexManagerFactory.class ); String indexName = getIndexName( entity, cfg ); Properties[] indexProperties = getIndexProperties( cfg, indexName ); String indexManagerImplementationName = indexProperties[0].getProperty( Environment.INDEX_MANAGER_IMPL_NAME ); String indexManagerImplementationKey = StringHelper.isEmpty( indexManagerImplementationName ) ? DEFAULT_INDEX_MANAGER_KEY : indexManagerImplementationName; if ( indexManagerImplementationsRegistry.containsKey( indexManagerImplementationKey ) ) { return indexManagerImplementationsRegistry.get( indexManagerImplementationKey ); } try { Class<? extends IndexManager> indexManagerType; if ( StringHelper.isEmpty( indexManagerImplementationName ) ) { indexManagerType = indexManagerFactory.createDefaultIndexManager().getClass(); } else { indexManagerType = indexManagerFactory.createIndexManagerByName( indexManagerImplementationName ).getClass(); } indexManagerImplementationsRegistry.put( indexManagerImplementationKey, indexManagerType ); return indexManagerType; } finally { serviceManager.releaseService( IndexManagerFactory.class ); } }
Source:
<code><START> public int lastIndexOf(Object o) { <END> int last = -1; for (Entry<Integer, E> entry : fInnerElements.entrySet()) { if (Objects.equals(entry.getValue(), o)) { last = Math.max(last, entry.getKey()); } } return last; }</code><technical_language>Special case for null</technical_language>

Target:
public int lastIndexOf(Object o) { int last = -1; if (o == null && contains(null)) { for (int i = size() -1; i >= 0; i--) { if (!fInnerElements.containsKey(i)) { return i; } } } for (Entry<Integer, E> entry : fInnerElements.entrySet()) { if (Objects.equals(entry.getValue(), o)) { last = Math.max(last, entry.getKey()); } } return last; }
Source:
<code>public void tryInstallFailed() { synchronized (failedInstalls) { Iterator<File> iterator = failedInstalls.iterator(); while (iterator.hasNext()) { File f = iterator.next(); <START> if (doInstall(f)) { <END> iterator.remove(); } } } }</code><technical_language>please avoid names f... scope is short feel free native language describe output; nextFileInQueueToInstall fileToInstall,</technical_language>

Target:
public void tryInstallFailed() { synchronized (failedInstalls) { Iterator<File> failedInstallsIterator = failedInstalls.iterator(); while (failedInstallsIterator.hasNext()) { File fileToInstall = failedInstallsIterator.next(); if (doInstall(fileToInstall)) { failedInstallsIterator.remove(); } } } }
Source:
<code><START> protected String getWarningMessage(PrestoWarning warning) <END> { return REAL_TERMINAL ? format("%sWARNING: %s%s", WARNING_BEGIN, warning.getMessage(), WARNING_END) : format("WARNING: %s", warning.getMessage()); }</code><technical_language>do need this flag? This is printWithInitialSeparator (why other methods need if this is needed?)</technical_language>

Target:
private String getWarningMessage(PrestoWarning warning) { if (REAL_TERMINAL) { return format("%sWARNING: %s%s", WARNING_BEGIN, warning.getMessage(), WARNING_END); } return format("WARNING: %s", warning.getMessage()); }
Source:
<code>public List<Type> typeArguments() { if (typeArguments == null) { <START> ITypeBinding[] typeArgs = typeBinding.getTypeArguments(); <END> Type[] result = new Type[typeArgs.length]; for (int i = 0; i < typeArgs.length; i++) { result[i] = sema.type(typeArgs[i]); } typeArguments = Arrays.asList(result); } return typeArguments; }</code><technical_language>extract body of if a method convertTypeArguments</technical_language>

Target:
public List<Type> typeArguments() { if (typeArguments == null) { convertTypeArguments(); } return typeArguments; }
Source:
<code>private void initUI() { addStyleName("gerrit-ChangeScreen"); descriptionBlock = new ChangeDescriptionBlock(); add(descriptionBlock); dependencies = new ChangeTable(); dependsOn = new ChangeTable.Section(Util.C.changeScreenDependsOn()); neededBy = new ChangeTable.Section(Util.C.changeScreenNeededBy()); dependencies.addSection(dependsOn); dependencies.addSection(neededBy); dependenciesPanel = new DisclosurePanel(Util.C.changeScreenDependencies()); dependenciesPanel.setContent(dependencies); dependenciesPanel.setWidth("95%"); add(dependenciesPanel); <START> approvals = new ApprovalTable(changeId); <END> approvalsPanel = new DisclosurePanel(Util.C.changeScreenApprovals()); approvalsPanel.setContent(wrap(approvals)); dependenciesPanel.setWidth("95%"); add(approvalsPanel); patchSetPanels = new FlowPanel(); add(patchSetPanels); messagesContent = new FlowPanel(); messagesContent.setStyleName("gerrit-ChangeMessages"); messagesPanel = new DisclosurePanel(Util.C.changeScreenMessages()); messagesPanel.setContent(messagesContent); add(messagesPanel); }</code><technical_language>I do that. ChangeScreen instances recycled changes, navigate Open screen change, back, screen. screen reuse existing ChangeScreen instance update displayed data</technical_language>

Target:
private void initUI() { addStyleName("gerrit-ChangeScreen"); descriptionBlock = new ChangeDescriptionBlock(); add(descriptionBlock); dependencies = new ChangeTable(); dependsOn = new ChangeTable.Section(Util.C.changeScreenDependsOn()); neededBy = new ChangeTable.Section(Util.C.changeScreenNeededBy()); dependencies.addSection(dependsOn); dependencies.addSection(neededBy); dependenciesPanel = new DisclosurePanel(Util.C.changeScreenDependencies()); dependenciesPanel.setContent(dependencies); dependenciesPanel.setWidth("95%"); add(dependenciesPanel); approvals = new ApprovalTable(); approvalsPanel = new DisclosurePanel(Util.C.changeScreenApprovals()); approvalsPanel.setContent(wrap(approvals)); dependenciesPanel.setWidth("95%"); add(approvalsPanel); patchSetPanels = new FlowPanel(); add(patchSetPanels); messagesContent = new FlowPanel(); messagesContent.setStyleName("gerrit-ChangeMessages"); messagesPanel = new DisclosurePanel(Util.C.changeScreenMessages()); messagesPanel.setContent(messagesContent); add(messagesPanel); }
Source:
<code><START> public static String collectionString(Collection<?> c) { <END> StringBuilder res = new StringBuilder("["); boolean subsequent = false; synchronized (c) { for (Object o: c) { if (subsequent) { res.append(", "); } res.append(o); subsequent = true; } } return res.append("]").toString(); }</code><technical_language>I catch exception return "[...] (size=X)"</technical_language>

Target:
public static String collectionString(Collection<?> c) { StringBuilder res = new StringBuilder("["); boolean subsequent = false; try { for (Object o: c) { if (subsequent) { res.append(", "); } res.append(o); subsequent = true; } } catch (ConcurrentModificationException e) { return "[...] (size=" + c.size() + ")"; } return res.append("]").toString(); }
Source:
<code>public void createsFork() throws Exception { final MkForks forks = new MkForks(new MkStorage.InFile(), "Test", new Coordinates.Simple("tests", "forks") ); MatcherAssert.assertThat( forks.create(), <START> Matchers.notNullValue() <END> ); }</code><technical_language>Instead of Matchers.notNullValue() please, check actual equals expected</technical_language>

Target:
public void createsFork() throws Exception { final Fork.Smart fork = new Fork.Smart(this.repo().forks().create()); MatcherAssert.assertThat( this.repo().forks().get(Integer.parseInt(fork.forkId())), Matchers.notNullValue() ); }
Source:
<code>public String toString() { <START> return this.getClass().getSimpleName() + ": " + fboToBind; <END> }</code><technical_language>Hmmm. This generate as: BindFBOTask:3 a spartan debug string. able tie this a node (more importantly) fboName output of taskListGenerator. BindFBO state change prints out fboName fboId task store of fboName, I think, purely for debugging purposes</technical_language>

Target:
public String toString() { return String.format("%16s: %s(%s)", this.getClass().getSimpleName(), fboName, fboId); }
Source:
<code>protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (logger.isDebugEnabled()) { String pathInfo = req.getPathInfo(); logger.warn("Serving request from " + pathInfo); } final String className = extractClassName(req.getPathInfo()); final FileProcess fp = new FileProcess(null, className); boolean ok = true; byte[] bytes = null; try { bytes = fp.getBytes(); resp.setContentType("application/java"); resp.setStatus(HttpServletResponse.SC_OK); resp.getOutputStream().write(bytes); } catch (ClassNotFoundException e) { ok = false; resp.setContentType("text/plain"); resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } if (logger.isDebugEnabled()) { final String from = req.getLocalAddr() + ":" + req.getLocalPort(); final String status = ok ? "OK" : "Class Not Found"; <START> if (logger.isDebugEnabled()) { <END> logger.debug("Served request from " + from + " for " + className + " status: " + status + (bytes != null ? " bytes: " + bytes.length : "")); } } }</code><technical_language>is if necessary ? in if condition line 132</technical_language>

Target:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (logger.isDebugEnabled()) { String pathInfo = req.getPathInfo(); logger.warn("Serving request from " + pathInfo); } final String className = extractClassName(req.getPathInfo()); final FileProcess fp = new FileProcess(null, className); boolean ok = true; byte[] bytes = null; try { bytes = fp.getBytes(); resp.setContentType("application/java"); resp.setStatus(HttpServletResponse.SC_OK); resp.getOutputStream().write(bytes); } catch (ClassNotFoundException e) { ok = false; resp.setContentType("text/plain"); resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } if (logger.isDebugEnabled()) { final String from = req.getLocalAddr() + ":" + req.getLocalPort(); final String status = ok ? "OK" : "Class Not Found"; logger.debug("Served request from " + from + " for " + className + " status: " + status + (bytes != null ? " bytes: " + bytes.length : "")); } }
Source:
<code>public void testDeployRoot_alreadyDeployed() throws Exception { TestApplication app = new TestApplication(); ManagedApplication ma = new ManagedApplication( app ); this.managerWrapper.getNameToManagedApplication().put( app.getName(), ma ); String targetId = this.manager.targetsMngr().createTarget( "id:tid\nprop: ok\nhandler: test" ); this.manager.targetsMngr().associateTargetWith( targetId, app, null ); <START> File dir = new File( this.manager.configurationMngr().getWorkingDirectory(), ConfigurationUtils.TARGETS + "/" + targetId ); <END> Utils.createDirectory( dir ); Utils.writeStringInto( "#!/bin/bash\necho Bonjour le monde cruel > toto.txt", new File( dir, Constants.TARGET_SCRIPT_FILE_NAME )); Assert.assertNotNull( this.manager.targetsMngr().findScriptResources(targetId) ); Assert.assertEquals( 0, this.targetResolver.instancePathToRunningStatus.size()); Assert.assertEquals( 0, ma.getScopedInstanceToAwaitingMessages().size()); app.getMySqlVm().data.put( Instance.MACHINE_ID, "something" ); this.manager.instancesMngr().changeInstanceState( ma, app.getMySqlVm(), InstanceStatus.DEPLOYED_STARTED ); Assert.assertEquals( 0, this.targetResolver.instancePathToRunningStatus.size()); Assert.assertEquals( 0, this.msgClient.allSentMessages.size()); Assert.assertEquals( 0, ma.getScopedInstanceToAwaitingMessages().size()); }</code><technical_language>A HUGE no. Do modify this test. Write a new one. This test prevents regressions</technical_language>

Target:
public void testDeployRoot_alreadyDeployed() throws Exception { TestApplication app = new TestApplication(); ManagedApplication ma = new ManagedApplication( app ); this.managerWrapper.getNameToManagedApplication().put( app.getName(), ma ); String targetId = this.manager.targetsMngr().createTarget( "id:tid\nprop: ok\nhandler: test" ); this.manager.targetsMngr().associateTargetWith( targetId, app, null ); Assert.assertEquals( 0, this.targetResolver.instancePathToRunningStatus.size()); Assert.assertEquals( 0, ma.getScopedInstanceToAwaitingMessages().size()); app.getMySqlVm().data.put( Instance.MACHINE_ID, "something" ); this.manager.instancesMngr().changeInstanceState( ma, app.getMySqlVm(), InstanceStatus.DEPLOYED_STARTED ); Assert.assertEquals( 0, this.targetResolver.instancePathToRunningStatus.size()); Assert.assertEquals( 0, this.msgClient.allSentMessages.size()); Assert.assertEquals( 0, ma.getScopedInstanceToAwaitingMessages().size()); }
Source:
<code>protected boolean canDoAction() { final VM vm = getVm(); <START> if (vm == null) { <END> return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_VM_NOT_FOUND); } if (!canRunActionOnNonManagedVm()) { return false; } if (getVm().getStatus() != VMStatus.Up && getVm().getStatus() != VMStatus.PoweringUp) { return failVmStatusIllegal(); } return true; }</code><technical_language>please inline (I you'r'e getVm() on)</technical_language>

Target:
protected boolean canDoAction() { if (getVm() == null) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_VM_NOT_FOUND); } if (!canRunActionOnNonManagedVm()) { return false; } if (getVm().getStatus() != VMStatus.Up && getVm().getStatus() != VMStatus.PoweringUp) { return failVmStatusIllegal(); } return true; }
Source:
<code>private void showProgress(final boolean show) { final CGeoMap map = mapRef.get(); if (map == null) { return; } final ProgressBar progress = ButterKnife.findById(map.activity, R.id.actionbar_progress); if (progress != null) { final int visibility = show ? View.VISIBLE : View.GONE; progress.setVisibility(visibility); } <START> map.activity.setProgressBarIndeterminateVisibility(show); <END> map.spinner.setVisibility(show ? View.VISIBLE : View.GONE); }</code><technical_language>If I get right, remove activity.setProgress... calls everywhere, anymore</technical_language>

Target:
private void showProgress(final boolean show) { final CGeoMap map = mapRef.get(); if (map == null) { return; } map.spinner.setVisibility(show ? View.VISIBLE : View.GONE); }
Source:
<code>public void visitNode(Tree tree) { if (hasSemantic()) { Type varType; ExpressionTree expr; if (tree.is(Tree.Kind.ASSIGNMENT)) { AssignmentExpressionTree aet = (AssignmentExpressionTree) tree; varType = aet.symbolType(); expr = aet.expression(); checkExpression(varType, expr); } else if (tree.is(Tree.Kind.VARIABLE)) { VariableTree variableTree = (VariableTree) tree; varType = variableTree.type().symbolType(); expr = variableTree.initializer(); checkExpression(varType, expr); } else if (tree.is(Tree.Kind.METHOD_INVOCATION)) { checkMethodInvocationArgument((MethodInvocationTree) tree); } else if (tree.is(Tree.Kind.METHOD)) { MethodTreeImpl methodTree = (MethodTreeImpl) tree; Type returnType = methodTree.returnType() != null ? methodTree.returnType().symbolType() : null; if (returnType != null && isVarTypeErrorProne(returnType)) { methodTree.accept(new ReturnStatementVisitor(returnType)); } <START> } else if (tree.is(Tree.Kind.DIVIDE)) { <END> BinaryExpressionTree binaryExpr = (BinaryExpressionTree) tree; if (isIntOrLong(binaryExpr.symbolType())) { checkIntegerDivisionInsideFloatingPointExpression(binaryExpr); } } } }</code><technical_language>I a 5th subscribed tree, more elegant a switch cover kinds. In a commit</technical_language>

Target:
public void visitNode(Tree tree) { if (hasSemantic()) { Type varType; ExpressionTree expr; switch (tree.kind()) { case ASSIGNMENT: AssignmentExpressionTree aet = (AssignmentExpressionTree) tree; varType = aet.symbolType(); expr = aet.expression(); checkExpression(varType, expr); break; case VARIABLE: VariableTree variableTree = (VariableTree) tree; varType = variableTree.type().symbolType(); expr = variableTree.initializer(); checkExpression(varType, expr); break; case METHOD_INVOCATION: checkMethodInvocationArgument((MethodInvocationTree) tree); break; case METHOD: checkMethodTree((MethodTreeImpl) tree); break; case DIVIDE: BinaryExpressionTree binaryExpr = (BinaryExpressionTree) tree; if (isIntOrLong(binaryExpr.symbolType())) { checkIntegerDivisionInsideFloatingPointExpression(binaryExpr); } break; default: throw new IllegalArgumentException("Tree " + tree.kind() + " not handled."); } } }
Source:
<code>private TenderDto mapTender(Tender tender) { TenderDto tenderDto = new TenderDto(); List<String> locations = new ArrayList<>(); Set<String> categories = new HashSet<>(); List<String> roles = new ArrayList<>(); tenderDto.setId(tender.getId()); tenderDto.setTitle(tender.getTitle()); tenderDto.setAuthorName(tender.getAuthor().getFirstName()); tenderDto.setCreateDate(tender.getCreateDate()); tenderDto.setEndDate(tender.getEndDate()); tenderDto.setStatus(tender.getStatus().getName()); tenderDto.setSuitablePrice(tender.getSuitablePrice()); for (Location location : tender.getLocations()) { locations.add(location.getName()); } tenderDto.setLocations(locations); for (Unit unit : tender.getUnits()) { categories.add(unit.getItem().getCategory().getName()); } tenderDto.setCategories(categories); if (tender.getProposals()!=null){tenderDto.setProposals(tender.getProposals().size());} if (tender.getDescription()!=null){ tenderDto.setDescription(tender.getDescription()); } if (USER_LOGIN!=null){ for (Role role:userService.findByLogin(USER_LOGIN).getRoles()){ <START> roles.add(role.getName()); <END> } } tenderDto.setRoles(roles); return tenderDto; }</code><technical_language>fetch roles securityContext.getPrincipal.getRoles() standart Spring Security methods. Please fix</technical_language>

Target:
private TenderDto mapTender(Tender tender) { TenderDto tenderDto = new TenderDto(); List<String> locations = new ArrayList<>(); Set<String> categories = new HashSet<>(); List<String> roles = new ArrayList<>(); tenderDto.setId(tender.getId()); tenderDto.setTitle(tender.getTitle()); tenderDto.setAuthorName(tender.getAuthor().getFirstName()); tenderDto.setCreateDate(tender.getCreateDate()); tenderDto.setEndDate(tender.getEndDate()); tenderDto.setStatus(tender.getStatus().getName()); tenderDto.setSuitablePrice(tender.getSuitablePrice()); for (Location location : tender.getLocations()) { locations.add(location.getName()); } tenderDto.setLocations(locations); for (Unit unit : tender.getUnits()) { categories.add(unit.getItem().getCategory().getName()); } tenderDto.setCategories(categories); if (tender.getProposals()!=null){tenderDto.setProposals(tender.getProposals().size());} if (tender.getDescription()!=null){ tenderDto.setDescription(tender.getDescription()); } if (SecurityContextHolder.getContext().getAuthentication().getName()!="anonymousUser"){ for (Role role:userService.findByLogin(SecurityContextHolder.getContext().getAuthentication().getName()).getRoles()){ roles.add(role.getName()); } } tenderDto.setRoles(roles); return tenderDto; }
Source:
<code>public void userCanReassignClaimedTaskToCandidateUsers() { String taskId = createTask("garth"); userAssignTask(taskId,"garth", "dean"); userAssignTask(taskId,"dean", "garth"); test_shouldReturnIllegalStateExceptionWhenUserIsNotAssigneeOrOwner(taskId,"dean", "garth"); <START> cleanUp(taskId); <END> }</code><technical_language>need clean here. done [the @AfterEach method](<LINK_0></technical_language>

Target:
public void userCanReassignClaimedTaskToCandidateUsers() { String taskId = createTask("garth"); claimTask(taskId,"garth"); userAssignTask(taskId, "garth", "dean"); userAssignTask(taskId, "dean", "john"); }
Source:
<code>public void doGetRole(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleName) throws IOException{ checkAdminPerm(); JSONObject responseJson = new JSONObject(); RoleMap roleMap = this.grantedRoles.get(type); if (roleMap != null){ Role role = roleMap.getRole(roleName); if (role != null){ Set<Permission> permissions = role.getPermissions(); Map<String,Boolean> permissionsMap = new HashMap<String, Boolean>(); for (Permission permission : permissions) { permissionsMap.put(permission.getId(),permission.getEnabled()); } responseJson.put("permissionIds",permissionsMap); <START> if (type.equals(RoleBasedAuthorizationStrategy.PROJECT)){ <END> responseJson.put("pattern",role.getPattern().pattern()); } } } Stapler.getCurrentResponse().setContentType("application/json;charset=UTF-8"); Writer writer = Stapler.getCurrentResponse().getCompressedWriter(Stapler.getCurrentRequest()); responseJson.write(writer); writer.close(); }</code><technical_language>applies agents other types. I check for != RoleBasedAuthorizationStrategy.GLOBAL</technical_language>

Target:
public void doGetRole(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleName) throws IOException{ checkAdminPerm(); JSONObject responseJson = new JSONObject(); RoleMap roleMap = this.grantedRoles.get(type); if (roleMap != null){ Role role = roleMap.getRole(roleName); if (role != null){ Set<Permission> permissions = role.getPermissions(); Map<String,Boolean> permissionsMap = new HashMap<String, Boolean>(); for (Permission permission : permissions) { permissionsMap.put(permission.getId(),permission.getEnabled()); } responseJson.put("permissionIds",permissionsMap); if (!type.equals(RoleBasedAuthorizationStrategy.GLOBAL)){ responseJson.put("pattern",role.getPattern().pattern()); } } } Stapler.getCurrentResponse().setContentType("application/json;charset=UTF-8"); Writer writer = Stapler.getCurrentResponse().getCompressedWriter(Stapler.getCurrentRequest()); responseJson.write(writer); writer.close(); }
Source:
<code>public Optional<List<Class>> getResultType(List<Class> inputTypes) { if (inputTypes == null || inputTypes.size() != 1) throw new IllegalArgumentException( "Expecting a single type in input, not " + inputTypes); Class type = inputTypes.get(0); if (Number.class.isAssignableFrom(type)) { <START> return Optional.of(inputTypes); <END> } throw new IllegalArgumentException( "The input type for sum must be numeric, instead this was found: " + type); }</code><technical_language>want Double here? standard deviation below</technical_language>

Target:
public Optional<List<Class>> getResultType(List<Class> inputTypes) { if (inputTypes == null || inputTypes.size() != 1) throw new IllegalArgumentException( "Expecting a single type in input, not " + inputTypes); Class type = inputTypes.get(0); if (Number.class.isAssignableFrom(type)) { return Optional.of(Collections.singletonList(Double.class)); } throw new IllegalArgumentException( "The input type for sum must be numeric, instead this was found: " + type); }
Source:
<code>private Topology loadTopologyAttempt(File file) throws IOException, SAXException { <START> Topology topology = parse(FileUtils.openInputStream(file)); <END> if (topology != null) { topology.setUri(file.toURI()); topology.setName(FilenameUtils.removeExtension(file.getName())); topology.setTimestamp(file.lastModified()); } return topology; }</code><technical_language>I cleaner open/close input stream in parse method. Basically pass a file reference input stream? I need close input stream</technical_language>

Target:
private Topology loadTopologyAttempt(File file) throws IOException, SAXException { Topology topology; try (InputStream in = FileUtils.openInputStream(file)) { topology = parse(in); if (topology != null) { topology.setUri(file.toURI()); topology.setName(FilenameUtils.removeExtension(file.getName())); topology.setTimestamp(file.lastModified()); } } return topology; }
Source:
<code>public void open(final Map<String, Object> conf, final TopologyContext context, final SpoutOutputCollector spoutOutputCollector) { if (jmsProvider == null) { throw new IllegalStateException( "JMS provider has not been set."); } if (tupleProducer == null) { throw new IllegalStateException( "JMS Tuple Producer has not been set."); } collector = spoutOutputCollector; try { ConnectionFactory cf = jmsProvider.connectionFactory(); Destination dest = jmsProvider.destination(); connection = cf.createConnection(); <START> session = messageHandler.createSession(connection); <END> consumer = session.createConsumer(dest); connection.start(); } catch (Exception e) { LOG.warn("Error creating JMS connection.", e); } }</code><technical_language>want consider case: users provide mode is in JMS standard, setIndividualAck() is called. case is handled AUTO_ACKNOWLEDGE of providing default of messageHandler. Is intended? prevented case IllegalArgumentException</technical_language>

Target:
public void open(final Map<String, Object> conf, final TopologyContext context, final SpoutOutputCollector spoutOutputCollector) { if (jmsProvider == null) { throw new IllegalStateException( "JMS provider has not been set."); } if (tupleProducer == null) { throw new IllegalStateException( "JMS Tuple Producer has not been set."); } validateJmsAckMode(); collector = spoutOutputCollector; try { ConnectionFactory cf = jmsProvider.connectionFactory(); Destination dest = jmsProvider.destination(); connection = cf.createConnection(); session = messageHandler.createSession(connection); consumer = session.createConsumer(dest); connection.start(); } catch (Exception e) { LOG.warn("Error creating JMS connection.", e); } }
Source:
<code>private Set<String> moduleNames() { if (fModuleNames != null) return fModuleNames; Set<String> moduleNames= new HashSet<>(); if (fJavaElements != null) { for (IJavaElement <START> fJavaElement : <END> fJavaElements) { if (fJavaElement instanceof IPackageFragmentRoot) { IModuleDescription module= ((IPackageFragmentRoot) fJavaElement).getModuleDescription(); if (module != null) { recordModule(module, moduleNames); } else { try { recordModule(JavaCore.getAutomaticModuleDescription(fJavaElement), moduleNames); }catch (JavaModelException e) { JavaPlugin.log(e); } } } else if (fJavaElement instanceof IJavaProject) { try { IModuleDescription module= ((IJavaProject) fJavaElement).getModuleDescription(); if (module != null) { recordModule(module, moduleNames); } else { recordModule(JavaCore.getAutomaticModuleDescription(fJavaElement), moduleNames); } }catch (JavaModelException e) { JavaPlugin.log(e); } } } } return fModuleNames= moduleNames; }</code><technical_language>rename element</technical_language>

Target:
private Set<String> moduleNames() { if (fModuleNames != null) return fModuleNames; Set<String> moduleNames= new HashSet<>(); if (fJavaElements != null) { for (IJavaElement element : fJavaElements) { if (element instanceof IPackageFragmentRoot) { IModuleDescription module= ((IPackageFragmentRoot) element).getModuleDescription(); if (module != null) { recordModule(module, moduleNames); } else { try { recordModule(JavaCore.getAutomaticModuleDescription(element), moduleNames); }catch (JavaModelException e) { JavaPlugin.log(e); } } } else if (element instanceof IJavaProject) { try { IModuleDescription module= ((IJavaProject) element).getModuleDescription(); if (module != null) { recordModule(module, moduleNames); } else { recordModule(JavaCore.getAutomaticModuleDescription(element), moduleNames); } } catch (JavaModelException e) { JavaPlugin.log(e); } } } } return fModuleNames= moduleNames; }
Source:
<code><START> private void testParseJavaNameFailure(String[] inputs, char[] stopCharacters) throws Exception { <END> for (int i = 0; i < inputs.length; i++) { try { ParsingUtils.parseJavaName(inputs[i], 0, stopCharacters); Assert.fail("An exception was expected for input value: " + inputs[i]); } catch (ParseException e) { } } }</code><technical_language>Exception is thrown in method</technical_language>

Target:
private void testParseJavaNameFailure(String[] inputs, char[] stopCharacters) { Arrays.stream(inputs).forEach(input -> { try { ParsingUtils.parseJavaName(input, 0, stopCharacters); Assert.fail("An exception was expected for input value: " + input); } catch (ParseException e) { } }); }
Source:
<code>public boolean isValid() { <START> if (this.urlString == null || httpMethod == null) { <END> return true; } else { return false; } }</code><technical_language>return this.urlString == null || httpMethod == null;</technical_language>

Target:
protected boolean isValid() { return this.urlString == null || httpMethod == null; }
Source:
<code>private ConfigStatusInfo getConfigStatus(ConfigStatusProvider configStatusProvider, String entityId, Locale locale) { Collection<ConfigStatusMessage> configStatus = configStatusProvider.getConfigStatus(); if (configStatus == null) { logger.debug("Cannot provide config status for entity because its config status provider returned null.", entityId); return null; } Bundle bundle = FrameworkUtil.getBundle(configStatusProvider.getClass()); ConfigStatusInfo info = new ConfigStatusInfo(); for (ConfigStatusMessage configStatusMessage : configStatus) { String message = i18nProvider.getText(bundle, configStatusMessage.messageKey, null, locale, <START> configStatusMessage.arguments); <END> info.add(new ConfigStatusMessage(configStatusMessage.parameterName, configStatusMessage.type, message, configStatusMessage.statusCode)); } return info; }</code><technical_language>I prefer if logging warning message. i18n provider invoked if message key is null</technical_language>

Target:
private ConfigStatusInfo getConfigStatus(ConfigStatusProvider configStatusProvider, String entityId, Locale locale) { Collection<ConfigStatusMessage> configStatus = configStatusProvider.getConfigStatus(); if (configStatus == null) { logger.debug("Cannot provide config status for entity because its config status provider returned null.", entityId); return null; } Bundle bundle = FrameworkUtil.getBundle(configStatusProvider.getClass()); ConfigStatusInfo info = new ConfigStatusInfo(); for (ConfigStatusMessage configStatusMessage : configStatus) { String message = null; if (configStatusMessage.messageKey != null) { message = i18nProvider.getText(bundle, configStatusMessage.messageKey, null, locale, configStatusMessage.arguments); if (message == null) { logger.warn( "No translation found for key and config status provider {}. Will ignore the config status message.", configStatusMessage.messageKey, configStatusProvider.getClass().getSimpleName()); continue; } } info.add(new ConfigStatusMessage(configStatusMessage.parameterName, configStatusMessage.type, message, configStatusMessage.statusCode)); } return info; }
Source:
<code>private byte[] readCertificate(String certName) throws IOException { String pemPath = getClass().getClassLoader().getResource(certName).getPath(); <START> if (pemPath.contains(":")) { pemPath = pemPath.substring(1); <END> } return Files.readAllBytes(Paths.get(pemPath)); }</code><technical_language>this change required</technical_language>

Target:
private byte[] readCertificate(String certName) throws IOException { String pemPath = getClass().getClassLoader().getResource(certName).getPath(); String pemCert = ""; BufferedReader br = new BufferedReader(new FileReader(pemPath)); try { String line; while ((line = br.readLine()) != null) { pemCert += line + "\n"; } } finally { br.close(); } return pemCert.getBytes(); }
Source:
<code>public void initMetaAndIndex(HFile.Reader reader) throws IOException { ReaderContext context = reader.getContext(); HFileBlock.FSReader blockReader = reader.getUncachedBlockReader(); blockIter = blockReader.blockRange(trailer.getLoadOnOpenDataOffset(), context.getFileSize() - trailer.getTrailerSize()); try { this.dataIndexReader = new HFileBlockIndex.CellBasedKeyBlockIndexReader(trailer.createComparator(), trailer.getNumDataIndexLevels()); dataIndexReader .readMultiLevelIndexRoot(blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX), trailer.getDataIndexCount()); reader.setDataBlockIndexReader(dataIndexReader); this.metaIndexReader = new HFileBlockIndex.ByteArrayKeyBlockIndexReader(1); metaIndexReader.readRootIndex(blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX), trailer.getMetaIndexCount()); reader.setMetaBlockIndexReader(metaIndexReader); loadMetaInfo(blockIter, hfileContext); reader.setDataBlockEncoder(HFileDataBlockEncoderImpl.createFromFileInfo(this)); HFileBlock b; while ((b = blockIter.nextBlock()) != null) { loadOnOpenBlocks.add(b); } } catch (Throwable t) { IOUtils.closeQuietly(context.getInputStreamWrapper()); throw new CorruptHFileException("Problem reading data index and meta index from file " + context.getFilePath(), t); } finally { <START> context.getInputStreamWrapper().unbuffer(); <END> } }</code><technical_language>Is safe unbuffer input stream is closed</technical_language>

Target:
public void initMetaAndIndex(HFile.Reader reader) throws IOException { ReaderContext context = reader.getContext(); try { HFileBlock.FSReader blockReader = reader.getUncachedBlockReader(); blockIter = blockReader.blockRange(trailer.getLoadOnOpenDataOffset(), context.getFileSize() - trailer.getTrailerSize()); this.dataIndexReader = new HFileBlockIndex.CellBasedKeyBlockIndexReader(trailer.createComparator(), trailer.getNumDataIndexLevels()); dataIndexReader .readMultiLevelIndexRoot(blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX), trailer.getDataIndexCount()); reader.setDataBlockIndexReader(dataIndexReader); this.metaIndexReader = new HFileBlockIndex.ByteArrayKeyBlockIndexReader(1); metaIndexReader.readRootIndex(blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX), trailer.getMetaIndexCount()); reader.setMetaBlockIndexReader(metaIndexReader); loadMetaInfo(blockIter, hfileContext); reader.setDataBlockEncoder(HFileDataBlockEncoderImpl.createFromFileInfo(this)); HFileBlock b; while ((b = blockIter.nextBlock()) != null) { loadOnOpenBlocks.add(b); } context.getInputStreamWrapper().unbuffer(); } catch (Throwable t) { IOUtils.closeQuietly(context.getInputStreamWrapper()); throw new CorruptHFileException("Problem reading data index and meta index from file " + context.getFilePath(), t); } }
Source:
<code>private void selectStrutsFunctionality(HttpServletRequest request) { Functionality functionality = RenderersAnnotationProcessor.getFunctionalityForType(getFunctionalityType()); MenuFunctionality menuItem = MenuFunctionality.findFunctionality(functionality.getProvider(), functionality.getKey()); <START> if (!menuItem.isAvailableForCurrentUser()) { <END> throw AuthorizationException.unauthorized(); } BennuPortalDispatcher.selectFunctionality(request, menuItem); }</code><technical_language>add a null check here, selected functionality installed, yielding a null Menu Item</technical_language>

Target:
private void selectStrutsFunctionality(HttpServletRequest request) { Functionality functionality = RenderersAnnotationProcessor.getFunctionalityForType(getFunctionalityType()); MenuFunctionality menuItem = MenuFunctionality.findFunctionality(functionality.getProvider(), functionality.getKey()); if (menuItem == null || !menuItem.isAvailableForCurrentUser()) { throw AuthorizationException.unauthorized(); } BennuPortalDispatcher.selectFunctionality(request, menuItem); }
Source:
<code>protected String getSessionId() { String sessionId = null; if (getContext() != null && getContext().getEngineContext() != null) { sessionId = getContext().getEngineContext().getSessionId(); } <START> return sessionId; <END> }</code><technical_language>null? when? I hold id database (primary key) in addition of session id this for mla interaction reduce performance issues</technical_language>

Target:
protected long getSessionId() { String sessionId = getParameters().getSessionId(); if (sessionId == null && getContext() != null && getContext().getEngineContext() != null) { sessionId = getContext().getEngineContext().getSessionId(); } return SessionDataContainer.getInstance().getSessionId(sessionId); }
Source:
<code>public static String generateFileName(String string) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (Character.isSpaceChar(c) && (buf.length() == 0 || Character.isSpaceChar(buf.charAt(buf.length() - 1)))) { continue; } if (ArrayUtils.contains(validChars, c)) { buf.append(c); } } String filename = buf.toString().trim(); if (TextUtils.isEmpty(filename)) { return randomString(8); } else if (filename.length() >= MAX_FILENAME_LENGTH) { <START> return filename.substring(0, MAX_FILENAME_LENGTH - MD5_HEX_LENGTH - 1) + "filterdialog_" + md5(filename); <END> } else { return filename; } }</code><technical_language>I pretty this changed</technical_language>

Target:
public static String generateFileName(String string) { string = StringUtils.stripAccents(string); StringBuilder buf = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (Character.isSpaceChar(c) && (buf.length() == 0 || Character.isSpaceChar(buf.charAt(buf.length() - 1)))) { continue; } if (ArrayUtils.contains(validChars, c)) { buf.append(c); } } String filename = buf.toString().trim(); if (TextUtils.isEmpty(filename)) { return randomString(8); } else if (filename.length() >= MAX_FILENAME_LENGTH) { return filename.substring(0, MAX_FILENAME_LENGTH - MD5_HEX_LENGTH - 1) + "_" + md5(filename); } else { return filename; } }
Source:
<code>public AuthenticationResult getAuthTokenInBackground(final AuthenticationRequest request) { AuthenticationResult authResult = null; verifyNotOnMainThread(); Account[] accountList = mAcctManager .getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE); Logger.v(TAG, "Account list length:" + accountList.length); <START> String accountLookupUsername = getAccountLookupUsername(request); <END> Account targetAccount = getAccount(accountList, accountLookupUsername); if (targetAccount != null) { Bundle brokerOptions = getBrokerOptions(request); AccountManagerFuture<Bundle> result = null; try { result = mAcctManager.getAuthToken(targetAccount, AuthenticationConstants.Broker.AUTHTOKEN_TYPE, brokerOptions, false, null , mHandler); Logger.v(TAG, "Received result from Authenticator"); Bundle bundleResult = result.getResult(); authResult = getResultFromBrokerResponse(bundleResult); } catch (OperationCanceledException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.AUTH_FAILED_CANCELLED, e); } catch (AuthenticatorException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.BROKER_AUTHENTICATOR_NOT_RESPONDING); } catch (IOException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.BROKER_AUTHENTICATOR_IO_EXCEPTION); } Logger.v(TAG, "Returning result from Authenticator"); return authResult; } return null; }</code><technical_language>pass result getAccountLookupUsername right getAccount</technical_language>

Target:
public AuthenticationResult getAuthTokenInBackground(final AuthenticationRequest request) { AuthenticationResult authResult = null; verifyNotOnMainThread(); Account[] accountList = mAcctManager .getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE); Logger.v(TAG, "Account list length:" + accountList.length); Account targetAccount = getAccount(accountList, getAccountLookupUsername(request)); if (targetAccount != null) { Bundle brokerOptions = getBrokerOptions(request); AccountManagerFuture<Bundle> result = null; try { result = mAcctManager.getAuthToken(targetAccount, AuthenticationConstants.Broker.AUTHTOKEN_TYPE, brokerOptions, false, null , mHandler); Logger.v(TAG, "Received result from Authenticator"); Bundle bundleResult = result.getResult(); authResult = getResultFromBrokerResponse(bundleResult); } catch (OperationCanceledException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.AUTH_FAILED_CANCELLED, e); } catch (AuthenticatorException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.BROKER_AUTHENTICATOR_NOT_RESPONDING); } catch (IOException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.BROKER_AUTHENTICATOR_IO_EXCEPTION); } Logger.v(TAG, "Returning result from Authenticator"); return authResult; } return null; }
Source:
<code><START> private ClusterSummary getClusterInfoImpl() throws Exception, AuthorizationException { <END> IStormClusterState state = stormClusterState; Map<String, SupervisorInfo> infos = state.allSupervisorInfo(); List<SupervisorSummary> summaries = new ArrayList<>(infos.size()); for (Entry<String, SupervisorInfo> entry : infos.entrySet()) { summaries.add(makeSupervisorSummary(entry.getKey(), entry.getValue())); } int uptime = this.uptime.upTime(); List<NimbusSummary> nimbuses = state.nimbuses(); NimbusInfo leader = leaderElector.getLeader(); for (NimbusSummary nimbusSummary : nimbuses) { nimbusSummary.set_uptime_secs(Time.deltaSecs(nimbusSummary.get_uptime_secs())); boolean isLeader = leader.getHost().equals(nimbusSummary.get_host()) && leader.getPort() == nimbusSummary.get_port(); if (isLeader && this.nimbusHostPortInfo.getHost().equals(leader.getHost()) && !this.isLeader()) { isLeader = false; } nimbusSummary.set_isLeader(isLeader); } List<TopologySummary> topologySummaries = getTopologySummaries(); ClusterSummary ret = new ClusterSummary(summaries, topologySummaries, nimbuses); return ret; }</code><technical_language>AuthorizationException is needed</technical_language>

Target:
private ClusterSummary getClusterInfoImpl() throws Exception { IStormClusterState state = stormClusterState; Map<String, SupervisorInfo> infos = state.allSupervisorInfo(); List<SupervisorSummary> summaries = new ArrayList<>(infos.size()); for (Entry<String, SupervisorInfo> entry : infos.entrySet()) { summaries.add(makeSupervisorSummary(entry.getKey(), entry.getValue())); } int uptime = this.uptime.upTime(); List<NimbusSummary> nimbuses = state.nimbuses(); NimbusInfo leader = leaderElector.getLeader(); for (NimbusSummary nimbusSummary : nimbuses) { nimbusSummary.set_uptime_secs(Time.deltaSecs(nimbusSummary.get_uptime_secs())); boolean isLeader = leader.getHost().equals(nimbusSummary.get_host()) && leader.getPort() == nimbusSummary.get_port(); if (isLeader && this.nimbusHostPortInfo.getHost().equals(leader.getHost()) && !this.isLeader()) { isLeader = false; } nimbusSummary.set_isLeader(isLeader); } List<TopologySummary> topologySummaries = getTopologySummariesImpl(); ClusterSummary ret = new ClusterSummary(summaries, topologySummaries, nimbuses); return ret; }
Source:
<code>public void traceOpened(TmfTraceOpenedSignal signal) { assert (signal != null); fTrace = signal.getTrace(); ITmfTrace[] traces = TmfTraceManager.getTraceSet(fTrace); if (traces != null) { this.showTraceAction.setEnabled(traces.length < fFullTraceHistogram.getMaxNbTraces()); <START> } <END> loadTrace(); }</code><technical_language>This needs done in traceSelected() too. do in initalizeHistogram() instead</technical_language>

Target:
public void traceOpened(TmfTraceOpenedSignal signal) { assert (signal != null); fTrace = signal.getTrace(); loadTrace(); }