auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void updateActionAvailability() { boolean allowStart = true; boolean allowStop = true; boolean allowRemove = true; boolean allowStartRebalance = true; boolean allowOptimize = true; if (getSelectedItems() == null || getSelectedItems().size() == 0) { allowStart = false; allowStop = false; allowRemove = false; allowStartRebalance = false; allowOptimize = false; } else { allowStart = true; allowStop = true; allowRemove = true; allowStartRebalance = true; <START> allowOptimize = true; <END> for (GlusterVolumeEntity volume : Linq.<GlusterVolumeEntity> cast(getSelectedItems())) { if (volume.getStatus() == GlusterStatus.UP) { allowStart = false; allowRemove = false; } else if (volume.getStatus() == GlusterStatus.DOWN) { allowStop = false; allowStartRebalance = false; } } } getStartCommand().setIsExecutionAllowed(allowStart); getStopCommand().setIsExecutionAllowed(allowStop); getRemoveVolumeCommand().setIsExecutionAllowed(allowRemove); getRebalanceCommand().setIsExecutionAllowed(allowStartRebalance); getOptimizeForVirtStoreCommand().setIsExecutionAllowed(allowOptimize); boolean isAvailable = !(getSystemTreeSelectedItem() != null && getSystemTreeSelectedItem().getType() == SystemTreeItemType.Volume); getNewVolumeCommand().setIsAvailable(isAvailable); getRemoveVolumeCommand().setIsAvailable(isAvailable); }</code><technical_language>redundant lines (initialized true)</technical_language>

Target:
private void updateActionAvailability() { boolean allowStart = true; boolean allowStop = true; boolean allowRemove = true; boolean allowStartRebalance = true; boolean allowOptimize = true; if (getSelectedItems() == null || getSelectedItems().size() == 0) { allowStart = false; allowStop = false; allowRemove = false; allowStartRebalance = false; allowOptimize = false; } else { for (GlusterVolumeEntity volume : Linq.<GlusterVolumeEntity> cast(getSelectedItems())) { if (volume.getStatus() == GlusterStatus.UP) { allowStart = false; allowRemove = false; } else if (volume.getStatus() == GlusterStatus.DOWN) { allowStop = false; allowStartRebalance = false; } } } getStartCommand().setIsExecutionAllowed(allowStart); getStopCommand().setIsExecutionAllowed(allowStop); getRemoveVolumeCommand().setIsExecutionAllowed(allowRemove); getRebalanceCommand().setIsExecutionAllowed(allowStartRebalance); getOptimizeForVirtStoreCommand().setIsExecutionAllowed(allowOptimize); boolean isAvailable = !(getSystemTreeSelectedItem() != null && getSystemTreeSelectedItem().getType() == SystemTreeItemType.Volume); getNewVolumeCommand().setIsAvailable(isAvailable); getRemoveVolumeCommand().setIsAvailable(isAvailable); }
Source:
<code>private Set<ObjectId> listNonHEADIndexObjects() throws CorruptObjectException, IOException { RevWalk revWalk = null; <START> DirCache dc = null; <END> try { if (repo.getIndexFile() == null) return Collections.emptySet(); } catch (NoWorkTreeException e) { return Collections.emptySet(); } TreeWalk treeWalk = new TreeWalk(repo); try { dc = repo.readDirCache(); treeWalk.addTree(new DirCacheIterator(dc)); ObjectId headID = repo.resolve(Constants.HEAD); if (headID != null) { revWalk = new RevWalk(repo); treeWalk.addTree(revWalk.parseTree(headID)); revWalk.dispose(); } treeWalk.setFilter(TreeFilter.ANY_DIFF); treeWalk.setRecursive(true); Set<ObjectId> ret = new HashSet<ObjectId>(); while (treeWalk.next()) { ObjectId objectId = treeWalk.getObjectId(0); if (!ObjectId.zeroId().equals(objectId)) ret.add(objectId); } return ret; } finally { if (revWalk != null) revWalk.dispose(); treeWalk.release(); } }</code><technical_language>dc is unnecessary local variable, i inline addTree call</technical_language>

Target:
private Set<ObjectId> listNonHEADIndexObjects() throws CorruptObjectException, IOException { RevWalk revWalk = null; try { if (repo.getIndexFile() == null) return Collections.emptySet(); } catch (NoWorkTreeException e) { return Collections.emptySet(); } TreeWalk treeWalk = new TreeWalk(repo); try { treeWalk.addTree(new DirCacheIterator(repo.readDirCache())); ObjectId headID = repo.resolve(Constants.HEAD); if (headID != null) { revWalk = new RevWalk(repo); treeWalk.addTree(revWalk.parseTree(headID)); revWalk.dispose(); } treeWalk.setFilter(TreeFilter.ANY_DIFF); treeWalk.setRecursive(true); Set<ObjectId> ret = new HashSet<ObjectId>(); while (treeWalk.next()) { ObjectId objectId = treeWalk.getObjectId(0); if (!ObjectId.zeroId().equals(objectId)) ret.add(objectId); } return ret; } finally { if (revWalk != null) revWalk.dispose(); treeWalk.release(); } }
Source:
<code>public void showPictureEditor() throws Exception { uploadPopupButton.click(); <START> waitForElementVisible(browser.driver.findElement(By.id("studentPhotoUploader"))); <END> }</code><technical_language>waitForElementVisible sound right. waitForElementVisibility</technical_language>

Target:
public void showPictureEditor() throws Exception { uploadPopupButton.click(); waitForElementVisibility(browser.driver.findElement(By.id("studentPhotoUploader"))); }
Source:
<code>private SiriusDiagramEditor switchToTargetEditor(final SiriusDiagramEditor defaultEditor, final URI sessionResourceUri, URI markedDiagramDescriptorURI) { SiriusDiagramEditor targetEditor = null; DRepresentationDescriptor markedDiagramDescriptor = (DRepresentationDescriptor) defaultEditor.getDiagram().eResource().getEObject(markedDiagramDescriptorURI.fragment()); if (markedDiagramDescriptor == null) { markedDiagramDescriptor = (DRepresentationDescriptor) defaultEditor.getEditingDomain().getResourceSet().getEObject(markedDiagramDescriptorURI, true); } <START> Option<Diagram> <END> option = getGMFDiagramFromDRepresentationDescriptor(markedDiagramDescriptor); if (option.some()) { Diagram markerDiagram = option.get(); URI markerDiagramURI = EcoreUtil.getURI(markerDiagram); if (defaultEditor.getDiagram().equals(markerDiagram)) { targetEditor = defaultEditor; } else { URIEditorInput editorInput = null; String editorName = markedDiagramDescriptor.getName(); Session session = new EObjectQuery(markedDiagramDescriptor).getSession(); if (session != null) { editorInput = new SessionEditorInput(markerDiagramURI, editorName, session); } else { editorInput = new URIEditorInput(markerDiagramURI, editorName); } final SiriusDiagramEditor searchEditor = searchEditor(editorInput); if (searchEditor != null) { targetEditor = searchEditor; } else { targetEditor = handleClosedEditorCase(defaultEditor, sessionResourceUri, markedDiagramDescriptorURI, markerDiagram, editorInput); } } } return targetEditor; }</code><technical_language>java.util.optional instead</technical_language>

Target:
private SiriusDiagramEditor switchToTargetEditor(final SiriusDiagramEditor defaultEditor, final URI sessionResourceUri, URI markedDiagramDescriptorURI) { SiriusDiagramEditor targetEditor = null; DRepresentationDescriptor markedDiagramDescriptor = (DRepresentationDescriptor) defaultEditor.getDiagram().eResource().getEObject(markedDiagramDescriptorURI.fragment()); if (markedDiagramDescriptor == null) { markedDiagramDescriptor = (DRepresentationDescriptor) defaultEditor.getEditingDomain().getResourceSet().getEObject(markedDiagramDescriptorURI, true); } Optional<Diagram> optionalDiagram = getGMFDiagramFromDRepresentationDescriptor(markedDiagramDescriptor); if (optionalDiagram.isPresent()) { Diagram markerDiagram = optionalDiagram.get(); URI markerDiagramURI = EcoreUtil.getURI(markerDiagram); if (defaultEditor.getDiagram().equals(markerDiagram)) { targetEditor = defaultEditor; } else { URIEditorInput editorInput = null; String editorName = markedDiagramDescriptor.getName(); Session session = new EObjectQuery(markedDiagramDescriptor).getSession(); if (session != null) { editorInput = new SessionEditorInput(markerDiagramURI, editorName, session); } else { editorInput = new URIEditorInput(markerDiagramURI, editorName); } final SiriusDiagramEditor searchEditor = searchEditor(editorInput); if (searchEditor != null) { targetEditor = searchEditor; } else { targetEditor = handleClosedEditorCase(defaultEditor, sessionResourceUri, markedDiagramDescriptorURI, markerDiagram, editorInput); } } } return targetEditor; }
Source:
<code>public Object[] fetchChildren(Object o, IProgressMonitor monitor) throws TeamException { if (!(o instanceof ICVSRemoteFolder)) return new Object[0]; ICVSRemoteFolder remoteFolder = (ICVSRemoteFolder) o; monitor = Policy.monitorFor(monitor); monitor.beginTask(NLS.bind( CVSUIMessages.RemoteFolderElement_fetchingRemoteChildren, new String[] { getLabel(remoteFolder) }), 200); try { if (remoteFolder.getTag() != null && remoteFolder.getTag().getType() == CVSTag.BRANCH) { ICVSRemoteResource[] cachedFolders = CVSUIPlugin .getPlugin() .getRepositoryManager() .getFoldersForTag(remoteFolder.getRepository(), remoteFolder.getTag(), Policy.subMonitorFor(monitor, 100)); if (!hasParentInCachedFolders(cachedFolders, remoteFolder)) { return getChildrenFromCachedFolders(cachedFolders, remoteFolder, Policy.subMonitorFor(monitor, 100)); } } return ((ICVSRemoteFolder) o).members(Policy.subMonitorFor(monitor, <START> 100)); <END> } finally { monitor.done(); } }</code><technical_language>need submonitor check for cached folders. I moved checking for branch upper avoid submonitor if dealing branch</technical_language>

Target:
public Object[] fetchChildren(Object o, IProgressMonitor monitor) throws TeamException { if (!(o instanceof ICVSRemoteFolder)) return new Object[0]; ICVSRemoteFolder remoteFolder = (ICVSRemoteFolder) o; if (remoteFolder.getTag() != null && remoteFolder.getTag().getType() == CVSTag.BRANCH) { monitor = Policy.monitorFor(monitor); monitor.beginTask(NLS.bind( CVSUIMessages.RemoteFolderElement_fetchingRemoteChildren, new String[] { getLabel(remoteFolder) }), 100); try { ICVSRemoteResource[] cachedFolders = CVSUIPlugin .getPlugin() .getRepositoryManager() .getFoldersForTag(remoteFolder.getRepository(), remoteFolder.getTag(), Policy.subMonitorFor(monitor, 50)); if (!hasCachedParent(cachedFolders, remoteFolder)) { return getCachedChildren(cachedFolders, remoteFolder, Policy.subMonitorFor(monitor, 50)); } return remoteFolder.members(Policy.subMonitorFor(monitor, 50)); } finally { monitor.done(); } } return remoteFolder.members(monitor); }
Source:
<code>public void testKafkaTemplateCanBeReferencedFromSubclass() { KafkaItemWriter<String, String> kafkaItemWriter = new KafkaItemWriter<String, String>() { @Override protected void writeKeyValue(String key, String value) { <START> this.kafkaTemplate.flush(); <END> } }; kafkaItemWriter.setKafkaTemplate(kafkaTemplate); kafkaItemWriter.writeKeyValue("k", "v"); verify(kafkaTemplate).flush(); }</code><technical_language>This changed this.kafkaTemplate.sendDefault(key, value);, currently parameters used. Do agree</technical_language>

Target:
public void testKafkaTemplateCanBeReferencedFromSubclass() { KafkaItemWriter<String, String> kafkaItemWriter = new KafkaItemWriter<String, String>() { @Override protected void writeKeyValue(String key, String value) { this.kafkaTemplate.sendDefault(key, value); } }; kafkaItemWriter.setKafkaTemplate(kafkaTemplate); kafkaItemWriter.writeKeyValue("k", "v"); verify(kafkaTemplate).sendDefault("k", "v"); }
Source:
<code>public static synchronized void startInstance(String portsConfig) { if (jmxServer == null) { if (portsConfig != null) { Iterator<Integer> ports = NetUtils.getPortRangeFromString(portsConfig); if (ports.hasNext()) { jmxServer = startJMXServerWithPortRanges(ports); } if (jmxServer == null) { <START> LOG.error("Could not start JMx server on any configured port(s) in: " + portsConfig); <END> } } } else { LOG.warn("JVM-wide JMXServer already started at port: " + jmxServer.getPort()); } }</code><technical_language>suggestion LOG.error("Could start JMX server configured port(s) in: " + portsConfig);</technical_language>

Target:
public static synchronized void startInstance(String portsConfig) { if (jmxServer == null) { if (portsConfig != null) { Iterator<Integer> ports = NetUtils.getPortRangeFromString(portsConfig); if (ports.hasNext()) { jmxServer = startJMXServerWithPortRanges(ports); } if (jmxServer == null) { LOG.error("Could not start JMX server on any configured port(s) in: " + portsConfig); } } } else { LOG.warn("JVM-wide JMXServer already started at port: " + jmxServer.getPort()); } }
Source:
<code>private void drawPreview() { JPanel pdfImagePanel = pdfDisplay.drawPreviewOnJPanel(); if(PDFDisplay.isDisableNextFlag()){ nextPageButton.setEnabled(false); } else{ nextPageButton.setEnabled(true); } if(PDFDisplay.isDisablePrevFlag()){ previousPageButton.setEnabled(false); } else{ previousPageButton.setEnabled(true); <START> } <END> if (pdfImagePanel != null) { JViewport vp = jScrollPane.getViewport(); Point p = vp.getViewPosition(); vp.setView(pdfImagePanel); vp.setViewPosition(p); } jLabel.setText("of " + pdfDisplay.getTotalPages()); }</code><technical_language>more place logic coded. This defined in a single place</technical_language>

Target:
private void drawPreview() { JPanel pdfImagePanel = pdfDisplay.drawPreviewOnJPanel(); if (pdfImagePanel != null) { JViewport vp = jScrollPane.getViewport(); Point p = vp.getViewPosition(); vp.setView(pdfImagePanel); vp.setViewPosition(p); } jLabel.setText("of " + pdfDisplay.getTotalPages()); }
Source:
<code>public void consume(Context context, Event event) throws Exception { int subjectType = event.getSubjectType(); int eventType = event.getEventType(); switch (subjectType) { case Constants.ITEM: if (eventType == Event.INSTALL) { items.add((Item) event.getSubject(context)); } break; default: <START> log.warn("consume() got unrecognized event: " + event.toString()); <END> } }</code><technical_language>afraid this spam logs. I bad experiences logging developing DOIConsumer. Please reduce log level debug</technical_language>

Target:
public void consume(Context context, Event event) throws Exception { int subjectType = event.getSubjectType(); int eventType = event.getEventType(); switch (subjectType) { case Constants.ITEM: if (eventType == Event.INSTALL) { items.add((Item) event.getSubject(context)); } break; default: log.debug("consume() got unrecognized event: " + event.toString()); } }
Source:
<code>public void run() { vertx = Vertx.vertx(); eb = vertx.eventBus(); AccountManager.create(eb, tracer); OrderLog.create(eb, tracer); InventoryManager.create(eb, tracer); Router router = Router.router(vertx); router.route(HttpMethod.POST, "/orders").handler(this::handlePlaceOrder); router.route(HttpMethod.GET, "/orders").handler(this::handleListOrders); <START> vertx.createHttpServer().requestHandler(router::accept).listen(8080); <END> }</code><technical_language>some system property define a bind port</technical_language>

Target:
public void run() { vertx = Vertx.vertx(); eb = vertx.eventBus(); AccountManager.create(eb, tracer); OrderLog.create(eb, tracer); InventoryManager.create(eb, tracer); Router router = Router.router(vertx); router.route(HttpMethod.POST, "/orders").handler(this::handlePlaceOrder); router.route(HttpMethod.GET, "/orders").handler(this::handleListOrders); vertx.createHttpServer().requestHandler(router::accept).listen(8180); }
Source:
<code>public static <T extends TypedSPI> Optional<T> newTypedServiceInstance(final Class<T> typedServiceInterface, final String type) { <START> Class<?> instanceClass = TYPED_SERVICE_CLASSES.containsKey(typedServiceInterface) ? TYPED_SERVICE_CLASSES.get(typedServiceInterface).get(type) : null; <END> if (null == instanceClass) { return Optional.empty(); } return Optional.of((T) newServiceInstance(instanceClass)); }</code><technical_language>Consider making good of Optional#map if Optional</technical_language>

Target:
public static <T extends TypedSPI> Optional<T> newTypedServiceInstance(final Class<T> typedServiceInterface, final String type) { return Optional.ofNullable(TYPED_SERVICE_CLASSES.get(typedServiceInterface)) .map(serviceClasses -> serviceClasses.get(type)) .map(clazz -> (T) newServiceInstance(clazz)); }
Source:
<code>public List<String> getParameterNames(HtmlParameter.Type type) { List<String> list = new ArrayList<String>(); Model.getSingleton() .getSession() .getParameters(this, type) .forEach((nvp) -> list.add(nvp.getName())); <START> ; <END> return list; }</code><technical_language>Remove</technical_language>

Target:
public List<String> getParameterNames(HtmlParameter.Type type) { List<String> list = new ArrayList<String>(); Model.getSingleton() .getSession() .getParameters(this, type) .forEach((nvp) -> list.add(nvp.getName())); return list; }
Source:
<code>public void doApprovePendingScripts(@JsonBody AllSelectedHashesModel content) { Jenkins.getInstance().checkPermission(Jenkins.RUN_SCRIPTS); LOG.log(Level.FINE, "Approval granted for selected {0}", content.hashes); synchronized (this) { String userLogin = this.getCurrentUserLogin(); for (String hash : content.hashes) { approvedScriptHashes.add(hash); PendingScript pendingScript = removePendingScript(hash); if (METADATA_GATHERING) { String script = pendingScript == null ? null : pendingScript.script; this.metadataStorage.withMetadata(hash, script, metadata -> metadata.notifyApproval(pendingScript, userLogin) ); } } save(); } <START> SecurityContext orig = ACL.impersonate(ACL.SYSTEM); <END> try { for (ApprovalListener listener : ExtensionList.lookup(ApprovalListener.class)) { for (String hash : content.hashes) { listener.onApproved(hash); } } } finally { SecurityContextHolder.setContext(orig); } }</code><technical_language>This is deprecated! ACL.as, fix existing usages in this class while it</technical_language>

Target:
public void doApprovePendingScripts(@JsonBody AllSelectedHashesModel content) { Jenkins.getInstance().checkPermission(Jenkins.RUN_SCRIPTS); LOG.log(Level.FINE, "Approval granted for selected {0}", content.hashes); synchronized (this) { String userLogin = this.getCurrentUserLogin(); for (String hash : content.hashes) { approvedScriptHashes.add(hash); PendingScript pendingScript = removePendingScript(hash); if (METADATA_GATHERING) { String script = pendingScript == null ? null : pendingScript.script; this.metadataStorage.withMetadata(hash, script, metadata -> metadata.notifyApproval(pendingScript, userLogin) ); } } save(); } try (ACLContext unused = ACL.as(ACL.SYSTEM)) { for (ApprovalListener listener : ExtensionList.lookup(ApprovalListener.class)) { for (String hash : content.hashes) { listener.onApproved(hash); } } } }
Source:
<code>public void setException(@Nullable Repository repo, Throwable err) { if (KetchReplica.log.isErrorEnabled()) { StringBuilder m = new StringBuilder(); m.append("pushAsync to "); m.append(replica.describeForLog()); m.append(" failed for:\n"); for (ReceiveCommand cmd : commands) { m.append(" "); m.append(cmd.getOldId().abbreviate(8).name()); m.append(' '); m.append(cmd.getNewId().abbreviate(8).name()); m.append(' '); m.append(cmd.getRefName()); m.append('\n'); } KetchReplica.log.error(m.toString(), err); } boolean invoke; synchronized (lock) { invoke = !done; this.exception = err; this.done = true; } <START> if (invoke) { <END> replica.afterPush(repo, this); } }</code><technical_language>invoke afterPush() if !done? pushed</technical_language>

Target:
public void setException(@Nullable Repository repo, Throwable err) { if (KetchReplica.log.isErrorEnabled()) { StringBuilder m = new StringBuilder(); m.append("pushAsync to "); m.append(replica.describeForLog()); m.append(" failed for:\n"); for (ReceiveCommand cmd : commands) { m.append(" "); m.append(cmd.getOldId().abbreviate(8).name()); m.append(' '); m.append(cmd.getNewId().abbreviate(8).name()); m.append(' '); m.append(cmd.getRefName()); m.append('\n'); } KetchReplica.log.error(m.toString(), err); } exception = err; replica.afterPush(repo, this); }
Source:
<code>public void testSwitchTargetVersion() throws Exception { CDOSession session = openSession(); CDOTransaction mainTx = session.openTransaction(); <START> CDOResource resource = mainTx.createResource("test"); <END> resource.getContents().add(createCategory("cat1")); mainTx.commit(); mainTx.close(); CDOBranch branch = session.getBranchManager().getMainBranch().createBranch("branch"); CDOTransaction branchTx = session.openTransaction(branch); resource = branchTx.getResource("test"); resource.getContents().add(createCategory("cat2")); branchTx.commit(); resource.getContents().add(createCategory("cat3")); branchTx.commit(); branchTx.close(); session.close(); CDOSession cleanSession = openSession(); CDOView view = cleanSession.openView(); resource = view.getResource("test"); resource.getContents().size(); assertEquals(1, resource.cdoRevision().getVersion()); view.setBranch(branch); assertEquals(2, resource.cdoRevision().getVersion()); }</code><technical_language>creating a CDOResource in CDO tests, call getResourcePath(String resourceName) test creates resources in folder disturb other tests @CleanRepositoriesBefore/After annotations</technical_language>

Target:
public void testSwitchTargetVersion() throws Exception { CDOSession session = openSession(); CDOTransaction mainTx = session.openTransaction(); String path = getResourcePath("test"); CDOResource resource = mainTx.createResource(path); resource.getContents().add(createCategory("cat1")); mainTx.commit(); mainTx.close(); CDOBranch branch = session.getBranchManager().getMainBranch().createBranch("branch"); CDOTransaction branchTx = session.openTransaction(branch); resource = branchTx.getResource(path); resource.getContents().add(createCategory("cat2")); branchTx.commit(); resource.getContents().add(createCategory("cat3")); branchTx.commit(); branchTx.close(); session.close(); CDOSession cleanSession = openSession(); CDOView view = cleanSession.openView(); resource = view.getResource(path); resource.getContents().size(); assertEquals(1, resource.cdoRevision().getVersion()); view.setBranch(branch); assertEquals(2, resource.cdoRevision().getVersion()); }
Source:
<code>public static void createInstance() throws ServerConfigurationException, NoSuchFieldException, IllegalAccessException { <START> carbonServerConfiguration = ServerConfiguration.getInstance(); <END> resourceURL = CarbonBaseUtilsTest.class.getClassLoader().getResource("carbon.xml"); assertFalse(getIsInitialized(carbonServerConfiguration, "isInitialized")); InputStream inputStream = readFile("carbon.xml"); carbonServerConfiguration.forceInit(inputStream); assertTrue(getIsInitialized(carbonServerConfiguration, "isInitialized")); }</code><technical_language>Get server conf instance</technical_language>

Target:
public void createInstance() throws ServerConfigurationException, NoSuchFieldException, IllegalAccessException { assertFalse(getIsInitialized(ServerConfiguration.getInstance(), "isInitialized")); InputStream inputStream = readFile("carbon.xml"); ServerConfiguration.getInstance().forceInit(inputStream); assertTrue(getIsInitialized(ServerConfiguration.getInstance(), "isInitialized")); }
Source:
<code>private List<File> getAllPossibleExternalConfigDirFilenames(final File configdir, final List<String> profiles) { val fileNames = new ArrayList<File>(); <START> for (val appName: getApplicationNames()) { <END> for (val ext: EXTENSIONS) { fileNames.add(new File(configdir, String.format("%s.%s", appName, ext))); } } for (val profile: profiles) { for (val ext: EXTENSIONS) { fileNames.add(new File(configdir, String.format("application-%s.%s", profile, ext))); fileNames.add(new File(configdir, String.format("%s.%s", profile, ext))); } } return fileNames; }</code><technical_language>Opportunity Java stream API</technical_language>

Target:
private List<File> getAllPossibleExternalConfigDirFilenames(final File configdir, final List<String> profiles) { val fileNames = getApplicationNames() .stream() .flatMap(appName -> EXTENSIONS .stream() .map(ext -> new File(configdir, String.format("%s.%s", appName, ext)))) .collect(Collectors.toList()); fileNames.addAll(profiles .stream() .flatMap(profile -> EXTENSIONS .stream() .flatMap(ext -> PROFILE_PATTERNS .stream().map(pattern -> new File(configdir, String.format(pattern, profile, ext))))).collect(Collectors.toList())); return fileNames; }
Source:
<code>public static ActionInvocation loadInvocation(String key, String token) { InvocationContext invocationContext = (InvocationContext) getInvocationMap().get(key); if ((invocationContext == null) || !invocationContext.token.equals(token)) { return null; } final ActionInvocation savedInvocation = invocationContext.invocation; if (savedInvocation != null) { final ActionContext savedActionContext = savedInvocation.getInvocationContext(); final ActionContext previousActionContext = ActionContext.getContext(); <START> ActionContext.bound(savedActionContext); <END> savedActionContext.setValueStack(savedInvocation.getStack()); if (previousActionContext != null) { savedActionContext.setPageContext(previousActionContext.getPageContext()); } else { savedActionContext.setPageContext(null); } } return savedInvocation; }</code><technical_language>candidate for bind() if method is created</technical_language>

Target:
public static ActionInvocation loadInvocation(String key, String token) { InvocationContext invocationContext = (InvocationContext) getInvocationMap().get(key); if ((invocationContext == null) || !invocationContext.token.equals(token)) { return null; } final ActionInvocation savedInvocation = invocationContext.invocation; if (savedInvocation != null) { final ActionContext previousActionContext = ActionContext.getContext(); savedInvocation .getInvocationContext() .withPageContext(previousActionContext.getPageContext()) .withValueStack(savedInvocation.getStack()) .bind(); } return savedInvocation; }
Source:
<code><START> public void createTimeZoneList() { <END> String[] ids = SimpleTimeZone.getAvailableIDs(); for (String id : ids) { TimeZone zone = TimeZone.getTimeZone(id); int offset = zone.getRawOffset() / 1000; int hour = offset / 3600; int minutes = (offset % 3600) / 60; String item = String.format("(GMT%+d:%02d) %s", hour, minutes, id); timeZoneComboBox.addItem(item); } TimeZone thisTimeZone = Calendar.getInstance().getTimeZone(); int thisOffset = thisTimeZone.getRawOffset() / 1000; int thisHour = thisOffset / 3600; int thisMinutes = (thisOffset % 3600) / 60; String formatted = String.format("(GMT%+d:%02d) %s", thisHour, thisMinutes, thisTimeZone.getID()); timeZoneComboBox.setSelectedItem(formatted); }</code><technical_language>this method need public</technical_language>

Target:
private void createTimeZoneList() { String[] ids = SimpleTimeZone.getAvailableIDs(); for (String id : ids) { TimeZone zone = TimeZone.getTimeZone(id); int offset = zone.getRawOffset() / 1000; int hour = offset / 3600; int minutes = (offset % 3600) / 60; String item = String.format("(GMT%+d:%02d) %s", hour, minutes, id); timeZoneComboBox.addItem(item); } TimeZone thisTimeZone = Calendar.getInstance().getTimeZone(); int thisOffset = thisTimeZone.getRawOffset() / 1000; int thisHour = thisOffset / 3600; int thisMinutes = (thisOffset % 3600) / 60; String formatted = String.format("(GMT%+d:%02d) %s", thisHour, thisMinutes, thisTimeZone.getID()); timeZoneComboBox.setSelectedItem(formatted); }
Source:
<code>public void testExecute_getProfileOfUnregisteredStudent_shouldReturnNotFoundMessage() { StudentAttributes student1InCourse1 = typicalBundle.students.get("student1InCourse1"); StudentAttributes unregisteredStudentInCourse1 = StudentAttributes.builder(student1InCourse1.getCourse(), "student1InUnregisteredCourse@gmail.tmt") .withGoogleId("") .withName("unregistered student in course 1") .withComment("") .withSectionName(student1InCourse1.getSection()) .withTeamName(student1InCourse1.getTeam()) .build(); typicalBundle.students.put("unregisteredStudentInCourse1", unregisteredStudentInCourse1); removeAndRestoreTypicalDataBundle(); <START> removeAndRestoreDataBundle(typicalBundle); <END> String[] submissionParams = new String[] { Const.ParamsNames.STUDENT_EMAIL, unregisteredStudentInCourse1.getEmail(), Const.ParamsNames.COURSE_ID, unregisteredStudentInCourse1.getCourse(), }; loginAsStudent(student1InCourse1.getGoogleId()); GetStudentProfileAction action = getAction(submissionParams); JsonResult result = getJsonResult(action); assertEquals(HttpStatus.SC_NOT_FOUND, result.getStatusCode()); }</code><technical_language>creation of student is weird. StudentsLogic.inst().createStudent</technical_language>

Target:
public void testExecute_getProfileOfUnregisteredStudent_shouldReturnNotFoundMessage() throws Exception { StudentAttributes student1InCourse1 = typicalBundle.students.get("student1InCourse1"); StudentAttributes unregisteredStudentInCourse1 = StudentAttributes.builder(student1InCourse1.getCourse(), "student1InUnregisteredCourse@gmail.tmt") .withGoogleId("") .withName("unregistered student in course 1") .withComment("") .withSectionName(student1InCourse1.getSection()) .withTeamName(student1InCourse1.getTeam()) .build(); StudentsLogic.inst().createStudent(unregisteredStudentInCourse1); String[] submissionParams = new String[] { Const.ParamsNames.STUDENT_EMAIL, unregisteredStudentInCourse1.getEmail(), Const.ParamsNames.COURSE_ID, unregisteredStudentInCourse1.getCourse(), }; loginAsStudent(student1InCourse1.getGoogleId()); GetStudentProfileAction action = getAction(submissionParams); JsonResult result = getJsonResult(action); assertEquals(HttpStatus.SC_NOT_FOUND, result.getStatusCode()); }
Source:
<code>public boolean verified(Payload payload, SessionWrapper session) { try { return permissionAPI.doesUserHavePermission((Permissionable) payload.getData(), Integer.parseInt(payload.getVisibilityId()), session.getUser(), false); } catch (DotDataException e) { <START> throw new BaseRuntimeInternationalizationException(e); <END> } }</code><technical_language>return a more meaningful exception</technical_language>

Target:
public boolean verified(Payload payload, SessionWrapper session) { try { return permissionAPI.doesUserHavePermission((Permissionable) payload.getData(), Integer.parseInt(payload.getVisibilityId()), session.getUser(), false); } catch (DotDataException e) { throw new VerifierException(e); } }
Source:
<code>public byte[] receiveDatagram() throws OpenEnergyMonitorException { if (in == null) { connect(); } byte[] buffer = new byte[100]; StringBuilder sb = new StringBuilder(); int len = -1; try { while ((len = this.in.read(buffer)) > 0) { for (int i = 0; i < len; i++) { logger.trace("Received char: {}", buffer[i]); if (buffer[i] != 0x0A) { if (buffer[i] != 0x0D) { sb.append((char) buffer[i]); } } else { return parseLine(sb.toString()); } } } } catch (IOException e) { <START> throw new OpenEnergyMonitorException("Error occured while receiving data", e); <END> } return null; }</code><technical_language>"occurred"</technical_language>

Target:
public byte[] receiveDatagram() throws OpenEnergyMonitorException { if (in == null) { connect(); } byte[] buffer = new byte[100]; StringBuilder sb = new StringBuilder(); int len = -1; try { while ((len = this.in.read(buffer)) > 0) { for (int i = 0; i < len; i++) { logger.trace("Received char: {}", buffer[i]); if (buffer[i] != 0x0A) { if (buffer[i] != 0x0D) { sb.append((char) buffer[i]); } } else { return parseLine(sb.toString()); } } } } catch (IOException e) { throw new OpenEnergyMonitorException("Error occurred while receiving data. ", e); } return null; }
Source:
<code>public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException { if ((bucketName == null) || (bucketName.isEmpty())) { throw new InvalidArgumentException("bucket name cannot be empty"); } if ((objectName == null) || (objectName.isEmpty())) { throw new InvalidArgumentException("object name cannot be empty"); } if (offset < 0) { throw new InvalidArgumentException("offset should be zero or greater"); } if (length != null && length <= 0) { throw new InvalidArgumentException("length should be greater than zero"); } <START> Map<String,String> headerMap = new HashMap<>(); <END> if (offset >= 0) { if (length != null) { headerMap.put("Range", "bytes=" + offset + "-" + (offset + length - 1)); } else { headerMap.put("Range", "bytes=" + offset + "-"); } } HttpResponse response = executeGet(bucketName, objectName, headerMap, null); return response.body().byteStream(); }</code><technical_language>this is incomplete implementation follow this implement variations <LINK_0></technical_language>

Target:
public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException { if ((bucketName == null) || (bucketName.isEmpty())) { throw new InvalidArgumentException("bucket name cannot be empty"); } if ((objectName == null) || (objectName.isEmpty())) { throw new InvalidArgumentException("object name cannot be empty"); } if (offset < 0) { throw new InvalidArgumentException("offset should be zero or greater"); } if (length != null && length <= 0) { throw new InvalidArgumentException("length should be greater than zero"); } Map<String,String> headerMap = new HashMap<>(); if (length != null) { headerMap.put("Range", "bytes=" + offset + "-" + (offset + length - 1)); } else if (offset > 0) { headerMap.put("Range", "bytes=" + offset + "-"); } HttpResponse response = executeGet(bucketName, objectName, headerMap, null); return response.body().byteStream(); }
Source:
<code>private static String getValue(Method getter, Object instance, String defaultValue) { if (getter == null || instance == null) { return defaultValue; } try { Object value = getter.invoke(instance); if (value == null) { return "null"; } if (value instanceof Optional) { <START> return ((Optional<Object>) value).map(Object::toString).orElse("null"); <END> } return value.toString(); } catch (Throwable e) { return "-- ERROR --"; } }</code><technical_language>This is incorrect cast. Cast Optional<?> instead. BTW printing null a bit inappropriate for non-null optional values? ---- (or something) better? (We change "null" for == null case too)</technical_language>

Target:
private static String getValue(Method getter, Object instance, String defaultValue) { if (getter == null || instance == null) { return defaultValue; } try { Object value = getter.invoke(instance); if (value == null) { return "----"; } if (value instanceof Optional) { return ((Optional<?>) value).map(Object::toString).orElse("----"); } return value.toString(); } catch (Throwable e) { return "-- ERROR --"; } }
Source:
<code>public void loadTaskLogs() { taskService.call((final List<TaskEventSummary> events) -> allLogs = events) <START> .getTaskEvents(getServerTemplateId(), <END> getContainerId(), getTaskId()); }</code><technical_language>I service call needs some tweak in backend well, sorting event in top paging parameters need sent</technical_language>

Target:
public void loadTaskLogs() { taskService.call((final List<TaskEventSummary> events) -> { if (currentPage == 0) { visibleLogs = new ArrayList(); } visibleLogs.addAll(events); view.hideLoadButton(events.size() < PAGE_SIZE); view.setLogs(visibleLogs.stream().collect(Collectors.toList())); }).getTaskEvents(getServerTemplateId(), getContainerId(), getTaskId(), currentPage, getPageSize()); }
Source:
<code>private DataSource createPatientDataSource() { List<Lookup> lookupList = new ArrayList<>(); lookupList.add(new Lookup("openMRS.uuid", createdPatient.getUuid())); <START> DataSource dataSource = new DataSource(OPENMRS_MODULE_NAME, new Long(4), new Long(0), "Patient-" + DEFAULT_CONFIG_NAME, "openMRS.lookup.uuid", lookupList, false); <END> dataSource.setOrder(0); return dataSource; }</code><technical_language>autoboxing</technical_language>

Target:
private DataSource createPatientDataSource() { List<Lookup> lookupList = new ArrayList<>(); lookupList.add(new Lookup("openMRS.uuid", createdPatient.getUuid())); DataSource dataSource = new DataSource(OPENMRS_MODULE_NAME, 4L, 0L, "Patient-" + DEFAULT_CONFIG_NAME, "openMRS.lookup.uuid", lookupList, false); dataSource.setOrder(0); return dataSource; }
Source:
<code>public void allTests() { CourseAttributes course1 = dataBundle.courses.get("typicalCourse1"); InstructorAttributes receiver = dataBundle.instructors.get("instructor1OfCourse1"); InstructorAttributes sender = dataBundle.instructors.get("instructor2OfCourse1"); String[] submissionParams = new String[] { ParamsNames.COURSE_ID, course1.getId(), ParamsNames.EMAIL_RECEIVER, receiver.email, ParamsNames.SENDER_ID, sender.googleId }; InstructorCourseJoinEmailWorkerAction action = getAction(submissionParams); action.execute(); verifyNumberOfEmailsSent(action, 1); EmailWrapper email = action.getEmailSender().getEmailsSent().get(0); assertEquals(String.format(EmailType.INSTRUCTOR_COURSE_JOIN.getSubject(), course1.getName(), course1.getId()), email.getSubject()); <START> assertEquals(receiver.email, email.getRecipient()); <END> }</code><technical_language>Check sender well</technical_language>

Target:
public void allTests() { CourseAttributes course1 = dataBundle.courses.get("typicalCourse1"); InstructorAttributes instr1InCourse1 = dataBundle.instructors.get("instructor1OfCourse1"); AccountAttributes inviter = AccountsLogic.inst().getAccount("idOfInstructor2OfCourse1"); String[] submissionParams = new String[] { ParamsNames.COURSE_ID, course1.getId(), ParamsNames.INSTRUCTOR_EMAIL, instr1InCourse1.email, ParamsNames.INVITER_ID, inviter.googleId }; InstructorCourseJoinEmailWorkerAction action = getAction(submissionParams); action.execute(); verifyNumberOfEmailsSent(action, 1); EmailWrapper email = action.getEmailSender().getEmailsSent().get(0); assertEquals(String.format(EmailType.INSTRUCTOR_COURSE_JOIN.getSubject(), course1.getName(), course1.getId()), email.getSubject()); assertEquals(instr1InCourse1.email, email.getRecipient()); }
Source:
<code>public ServiceHandler(Looper looper) { super(looper); <START> for (int i = 1; i <= 20; i++) { String cpuset = getCgroupCpuset(); if (cpuset == null || !cpuset.equals("/top")) { break; } try { Thread.sleep(1000); <END> } catch (InterruptedException e) { } } Log.i("SimpleIOService", "cgroup:" + getCgroupCpuset()); }</code><technical_language>nit: granularity, waking 100ms is heavy of a sample interval load, count of 200</technical_language>

Target:
public ServiceHandler(Looper looper) { super(looper); for (int i = 1; i <= 200; i++) { String cpuset = getCgroupCpuset(); if (cpuset == null || !cpuset.equals("/top")) { break; } try { Thread.sleep(100); } catch (InterruptedException e) { } } Log.i("SimpleIOService", "cgroup:" + getCgroupCpuset()); }
Source:
<code>public boolean equals(@Nullable Object obj) { <START> if (!(obj instanceof DataDrivenValueSelf)) { <END> return false; } return true; }</code><technical_language>return</technical_language>

Target:
public boolean equals(@Nullable Object obj) { if (!(obj instanceof DataDrivenValueSelf)) { return false; } return super.equals(obj); }
Source:
<code>public void scanEntryLog(long entryLogId, EntryLogScanner scanner) throws IOException { <START> EntryLogBufferedReadChannel bc = null; <END> ByteBuf data = null; try { ByteBuf headerBuffer = Unpooled.buffer(4 + 8); bc = getChannelForLogId(entryLogId); long pos = LOGFILE_HEADER_SIZE; data = PooledByteBufAllocator.DEFAULT.directBuffer(1024 * 1024); while (true) { if (pos >= bc.size()) { break; } if (readFromLogChannel(entryLogId, bc, headerBuffer, pos) != headerBuffer.capacity()) { LOG.warn("Short read for entry size from entrylog {}", entryLogId); return; } long offset = pos; pos += 4; int entrySize = headerBuffer.readInt(); long ledgerId = headerBuffer.readLong(); headerBuffer.clear(); if (ledgerId == INVALID_LID || !scanner.accept(ledgerId)) { pos += entrySize; continue; } data.clear(); data.capacity(entrySize); int rc = readFromLogChannel(entryLogId, bc, data, pos); if (rc != entrySize) { LOG.warn("Short read for ledger entry from entryLog {}@{} ({} != {})", entryLogId, pos, rc, entrySize); return; } scanner.process(ledgerId, offset, data); pos += entrySize; } } catch (IOException e) { LOG.warn("Failed to get channel to scan entry log: " + entryLogId + ".log"); throw e; } finally { if (data != null) { data.release(); } if (null != bc) { bc.release(); } } }</code><technical_language>a lot of code moved for exception. released bc object in final finally block</technical_language>

Target:
public void scanEntryLog(long entryLogId, EntryLogScanner scanner) throws IOException { ByteBuf data = null; try (EntryLogBufferedReadChannel bc = getChannelForLogId(entryLogId)) { ByteBuf headerBuffer = Unpooled.buffer(4 + 8); long pos = LOGFILE_HEADER_SIZE; data = PooledByteBufAllocator.DEFAULT.directBuffer(1024 * 1024); while (true) { if (pos >= bc.size()) { break; } if (readFromLogChannel(entryLogId, bc, headerBuffer, pos) != headerBuffer.capacity()) { LOG.warn("Short read for entry size from entrylog {}", entryLogId); return; } long offset = pos; pos += 4; int entrySize = headerBuffer.readInt(); long ledgerId = headerBuffer.readLong(); headerBuffer.clear(); if (ledgerId == INVALID_LID || !scanner.accept(ledgerId)) { pos += entrySize; continue; } data.clear(); data.capacity(entrySize); int rc = readFromLogChannel(entryLogId, bc, data, pos); if (rc != entrySize) { LOG.warn("Short read for ledger entry from entryLog {}@{} ({} != {})", entryLogId, pos, rc, entrySize); return; } scanner.process(ledgerId, offset, data); pos += entrySize; } } catch (IOException e) { LOG.warn("Failed to get channel to scan entry log: " + entryLogId + ".log"); throw e; } finally { if (data != null) { data.release(); } } }
Source:
<code>private void writeStrictMaxPoolConfig(final XMLExtendedStreamWriter writer, final Property strictMaxPoolModel) throws XMLStreamException { final ModelNode strictMaxPoolModelNode = strictMaxPoolModel.getValue(); writer.writeAttribute(EJB3SubsystemXMLAttribute.NAME.getLocalName(), strictMaxPoolModel.getName()); if (strictMaxPoolModelNode.hasDefined(MAX_POOL_SIZE)) StrictMaxPoolResourceDefinition.MAX_POOL_SIZE.marshallAsAttribute(strictMaxPoolModelNode, writer); if (strictMaxPoolModelNode.hasDefined(DERIVE_SIZE)) <START> StrictMaxPoolResourceDefinition.DERIVE_SIZE.marshallAsAttribute(strictMaxPoolModelNode, writer); <END> StrictMaxPoolResourceDefinition.INSTANCE_ACQUISITION_TIMEOUT.marshallAsAttribute(strictMaxPoolModelNode, writer); StrictMaxPoolResourceDefinition.INSTANCE_ACQUISITION_TIMEOUT_UNIT.marshallAsAttribute(strictMaxPoolModelNode, writer); }</code><technical_language>AFAICT changes this file necessary behavior of AttributeDefinitions is write if attribute defined</technical_language>

Target:
private void writeStrictMaxPoolConfig(final XMLExtendedStreamWriter writer, final Property strictMaxPoolModel) throws XMLStreamException { final ModelNode strictMaxPoolModelNode = strictMaxPoolModel.getValue(); writer.writeAttribute(EJB3SubsystemXMLAttribute.NAME.getLocalName(), strictMaxPoolModel.getName()); StrictMaxPoolResourceDefinition.MAX_POOL_SIZE.marshallAsAttribute(strictMaxPoolModelNode, writer); StrictMaxPoolResourceDefinition.DERIVE_SIZE.marshallAsAttribute(strictMaxPoolModelNode, writer); StrictMaxPoolResourceDefinition.INSTANCE_ACQUISITION_TIMEOUT.marshallAsAttribute(strictMaxPoolModelNode, writer); StrictMaxPoolResourceDefinition.INSTANCE_ACQUISITION_TIMEOUT_UNIT.marshallAsAttribute(strictMaxPoolModelNode, writer); }
Source:
<code>private static String getNewId(Entry container) { if (container instanceof io.dockstore.webservice.core.Tool) { return ((io.dockstore.webservice.core.Tool)container).getToolPath(); } else if (container instanceof Workflow) { Workflow workflow = (Workflow)container; DescriptorLanguage descriptorType = workflow.getDescriptorType(); String workflowPath = workflow.getWorkflowPath(); <START> if (descriptorType.equals(DescriptorLanguage.SERVICE)) { <END> return SERVICE_PREFIX + "/" + workflowPath; } else { return WORKFLOW_PREFIX + "/" + workflowPath; } } else { LOG.error("Could not construct URL for our container with id: " + container.getId()); return null; } }</code><technical_language>(should?) Java enums, safely == actually</technical_language>

Target:
private static String getNewId(Entry container) { if (container instanceof io.dockstore.webservice.core.Tool) { return ((io.dockstore.webservice.core.Tool)container).getToolPath(); } else if (container instanceof Workflow) { Workflow workflow = (Workflow)container; DescriptorLanguage descriptorType = workflow.getDescriptorType(); String workflowPath = workflow.getWorkflowPath(); if (descriptorType == DescriptorLanguage.SERVICE) { return SERVICE_PREFIX + "/" + workflowPath; } else { return WORKFLOW_PREFIX + "/" + workflowPath; } } else { LOG.error("Could not construct URL for our container with id: " + container.getId()); return null; } }
Source:
<code>public static boolean isOrc(StorageDescriptor sd) { return sd.getSerdeInfo().getSerializationLib() <START> .toLowerCase().contains("parquet"); <END> }</code><technical_language>a word mistake? is orc instead of parquet</technical_language>

Target:
public static boolean isOrc(StorageDescriptor sd) { return sd.getSerdeInfo().getSerializationLib() .toLowerCase().contains("orc"); }
Source:
<code>private void updateParents() throws OrmException, UnloggedFailure { final StringBuilder err = new StringBuilder(); final Set<Project.NameKey> grandParents = new HashSet<Project.NameKey>(); Project.NameKey newParentKey; grandParents.add(wildProject); if (newParent != null) { newParentKey = newParent.getProject().getNameKey(); Project.NameKey gp = newParent.getProject().getParent(); while (gp != null && grandParents.add(gp)) { final ProjectState s = projectCache.get(gp); if (s != null) { gp = s.getProject().getParent(); } else { break; } } } else { newParentKey = null; } for (final ProjectControl pc : children) { final Project.NameKey key = pc.getProject().getNameKey(); final String name = pc.getProject().getName(); if (wildProject.equals(key)) { err.append("error: Cannot set parent of '" + name + "'\n"); continue; } <START> if (grandParents.contains(key) || pc.getProject().getNameKey().equals(newParentKey)) { <END> err.append("error: Cycle exists between '" + name + "' and '" + (newParentKey != null ? newParentKey.get() : wildProject.get()) + "'\n"); continue; } final Project child = db.projects().get(key); if (child == null) { err.append("error: Project '" + name + "' not found\n"); continue; } child.setParent(newParentKey); db.projects().update(Collections.singleton(child)); } projectCache.evictAll(); if (err.length() > 0) { while (err.charAt(err.length() - 1) == '\n') { err.setLength(err.length() - 1); } throw new UnloggedFailure(1, err.toString()); } }</code><technical_language>pc.getProject().getNameKey() declared "key" line 96</technical_language>

Target:
private void updateParents() throws OrmException, UnloggedFailure { final StringBuilder err = new StringBuilder(); final Set<Project.NameKey> grandParents = new HashSet<Project.NameKey>(); Project.NameKey newParentKey; grandParents.add(wildProject); if (newParent != null) { newParentKey = newParent.getProject().getNameKey(); Project.NameKey gp = newParent.getProject().getParent(); while (gp != null && grandParents.add(gp)) { final ProjectState s = projectCache.get(gp); if (s != null) { gp = s.getProject().getParent(); } else { break; } } } else { newParentKey = null; } for (final ProjectControl pc : children) { final Project.NameKey key = pc.getProject().getNameKey(); final String name = pc.getProject().getName(); if (wildProject.equals(key)) { err.append("error: Cannot set parent of '" + name + "'\n"); continue; } if (grandParents.contains(key) || key.equals(newParentKey)) { err.append("error: Cycle exists between '" + name + "' and '" + (newParentKey != null ? newParentKey.get() : wildProject.get()) + "'\n"); continue; } final Project child = db.projects().get(key); if (child == null) { err.append("error: Project '" + name + "' not found\n"); continue; } child.setParent(newParentKey); db.projects().update(Collections.singleton(child)); } projectCache.evictAll(); if (err.length() > 0) { while (err.charAt(err.length() - 1) == '\n') { err.setLength(err.length() - 1); } throw new UnloggedFailure(1, err.toString()); } }