auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private OMResponse createErrorResponse( OMRequest omRequest, IOException exception) { OzoneManagerProtocolProtos.Type cmdType = omRequest.getCmdType(); switch (cmdType) { case CreateVolume: case SetVolumeProperty: case DeleteVolume: case CreateBucket: case SetBucketProperty: case DeleteBucket: case CreateKey: case RenameKey: case DeleteKey: case CommitKey: case AllocateBlock: case CreateS3Bucket: case DeleteS3Bucket: case InitiateMultiPartUpload: case CommitMultiPartUpload: case CompleteMultiPartUpload: case AbortMultiPartUpload: case GetS3Secret: case GetDelegationToken: case RenewDelegationToken: case CancelDelegationToken: case CreateDirectory: case CreateFile: case RemoveAcl: case SetAcl: case AddAcl: case PurgeKeys: OMResponse.Builder omResponse = OMResponse.newBuilder() .setStatus( OzoneManagerRatisUtils.exceptionToResponseStatus(exception)) .setCmdType(cmdType) .setSuccess(false); if (exception.getMessage() != null) { omResponse.setMessage(exception.getMessage()); } return omResponse.build(); default: return null; } }

Target:
private OMResponse createErrorResponse( OMRequest omRequest, IOException exception) { OzoneManagerProtocolProtos.Type cmdType = omRequest.getCmdType(); OMResponse.Builder omResponse = OMResponse.newBuilder() .setStatus( OzoneManagerRatisUtils.exceptionToResponseStatus(exception)) .setCmdType(cmdType) .setSuccess(false); if (exception.getMessage() != null) { omResponse.setMessage(exception.getMessage()); } return omResponse.build(); }
Source:
public void createIndex( Iterator rows, InputRowParser parser, final AggregatorFactory[] metrics, File outDir, long minTimestamp, QueryGranularity gran, boolean deserializeComplexMetrics, int maxRowCount ) throws Exception { IncrementalIndex index = null; List<File> toMerge = new ArrayList<>(); try { index = new OnheapIncrementalIndex(minTimestamp, gran, metrics, deserializeComplexMetrics, maxRowCount); while (rows.hasNext()) { Object row = rows.next(); try { if (row instanceof String && parser instanceof StringInputRowParser) { index.add(((StringInputRowParser) parser).parse((String) row)); } else { index.add(parser.parse(row)); } } catch (IndexSizeExceededException ex) { File tmp = Files.createTempDir(); toMerge.add(tmp); IndexMerger.persist(index, tmp, null, new IndexSpec()); index.close(); index = new OnheapIncrementalIndex(minTimestamp, gran, metrics, deserializeComplexMetrics, maxRowCount); } } if (toMerge.size() > 0) { File tmp = Files.createTempDir(); toMerge.add(tmp); IndexMerger.persist(index, tmp, null, new IndexSpec()); List<QueryableIndex> indexes = new ArrayList<>(toMerge.size()); for (File file : toMerge) { indexes.add(IndexIO.loadIndex(file)); } IndexMerger.mergeQueryableIndex(indexes, metrics, outDir, new IndexSpec()); for (QueryableIndex qi : indexes) { qi.close(); } } else { IndexMerger.persist(index, outDir, null, new IndexSpec()); } } finally { if (index != null) { index.close(); } for (File file : toMerge) { FileUtils.deleteDirectory(file); } } }

Target:
public void createIndex( Iterator rows, InputRowParser parser, final AggregatorFactory[] metrics, File outDir, long minTimestamp, QueryGranularity gran, boolean deserializeComplexMetrics, int maxRowCount ) throws Exception { IncrementalIndex index = null; List<File> toMerge = new ArrayList<>(); try { index = new OnheapIncrementalIndex(minTimestamp, gran, metrics, deserializeComplexMetrics, maxRowCount); while (rows.hasNext()) { Object row = rows.next(); try { if (row instanceof String && parser instanceof StringInputRowParser) { index.add(((StringInputRowParser) parser).parse((String) row)); } else { index.add(parser.parse(row)); } } catch (IndexSizeExceededException ex) { File tmp = tempFolder.newFolder(); toMerge.add(tmp); IndexMerger.persist(index, tmp, null, new IndexSpec()); index.close(); index = new OnheapIncrementalIndex(minTimestamp, gran, metrics, deserializeComplexMetrics, maxRowCount); } } if (toMerge.size() > 0) { File tmp = tempFolder.newFolder(); toMerge.add(tmp); IndexMerger.persist(index, tmp, null, new IndexSpec()); List<QueryableIndex> indexes = new ArrayList<>(toMerge.size()); for (File file : toMerge) { indexes.add(IndexIO.loadIndex(file)); } IndexMerger.mergeQueryableIndex(indexes, metrics, outDir, new IndexSpec()); for (QueryableIndex qi : indexes) { qi.close(); } } else { IndexMerger.persist(index, outDir, null, new IndexSpec()); } } finally { if (index != null) { index.close(); } } }
Source:
public MwPageCombo pageCombo(String title, boolean noImages) throws IOException { Response<MwPageCombo> rsp = webService.pageCombo(title, noImages).execute(); if (rsp.isSuccessful() && !rsp.body().hasError()) { return rsp.body(); } throw new IOException(rsp.message()); }

Target:
public MwPageCombo pageCombo(String title, boolean noImages) throws IOException { Response<MwPageCombo> rsp = webService.pageCombo(title, noImages).execute(); if (rsp.isSuccessful() && !rsp.body().hasError()) { return rsp.body(); } ServiceError err = rsp.body() == null || rsp.body().getError() == null ? null : rsp.body().getError(); throw new IOException(err == null ? rsp.message() : err.getDetails()); }
Source:
private void openWelcomeEditors(IWorkbenchWindow window) { if (IDEWorkbenchPlugin.getDefault().getPreferenceStore().getBoolean( IDEInternalPreferences.WELCOME_DIALOG)) { IProduct product = Platform.getProduct(); if (product == null) { return; } AboutInfo productInfo = new AboutInfo(product); URL url = productInfo.getWelcomePageURL(); if (url == null) { return; } IDEWorkbenchPlugin.getDefault().getPreferenceStore().setValue( IDEInternalPreferences.WELCOME_DIALOG, false); openWelcomeEditor(window, new WelcomeEditorInput(productInfo), null); } else { List<AboutInfo> welcomeFeatures = new ArrayList<>(); for (Object element : wbAdvisor.getNewlyAddedBundleGroups().entrySet()) { Map.Entry entry = (Map.Entry) element; AboutInfo info = (AboutInfo) entry.getValue(); if (info != null && info.getWelcomePageURL() != null) { welcomeFeatures.add(info); String pi = info.getBrandingBundleId(); if (pi != null) { Bundle bundle = Platform.getBundle(pi); if (bundle != null) { try { bundle.start(Bundle.START_TRANSIENT); } catch (BundleException exception) { StatusManager .getManager() .handle( new Status( IStatus.ERROR, IDEApplication.PLUGIN_ID, "Failed to load feature", exception)); } } } } } int wCount = getWorkbench().getWorkbenchWindowCount(); for (int i = 0; i < welcomeFeatures.size(); i++) { AboutInfo newInfo = welcomeFeatures.get(i); String id = newInfo.getWelcomePerspectiveId(); if (id == null || i >= wCount) { openWelcomeEditor(window, new WelcomeEditorInput(newInfo), id); } } } }

Target:
private void openWelcomeEditors(IWorkbenchWindow window) { if (IDEWorkbenchPlugin.getDefault().getPreferenceStore().getBoolean( IDEInternalPreferences.WELCOME_DIALOG)) { IProduct product = Platform.getProduct(); if (product == null) { return; } AboutInfo productInfo = new AboutInfo(product); URL url = productInfo.getWelcomePageURL(); if (url == null) { return; } IDEWorkbenchPlugin.getDefault().getPreferenceStore().setValue( IDEInternalPreferences.WELCOME_DIALOG, false); openWelcomeEditor(window, new WelcomeEditorInput(productInfo), null); } else { List<AboutInfo> welcomeFeatures = new ArrayList<>(); for (AboutInfo info : wbAdvisor.getNewlyAddedBundleGroups().values()) { if (info != null && info.getWelcomePageURL() != null) { welcomeFeatures.add(info); String pi = info.getBrandingBundleId(); if (pi != null) { Bundle bundle = Platform.getBundle(pi); if (bundle != null) { try { bundle.start(Bundle.START_TRANSIENT); } catch (BundleException exception) { StatusManager.getManager().handle(new Status(IStatus.ERROR, IDEApplication.PLUGIN_ID, "Failed to load feature", exception)); } } } } } int wCount = getWorkbench().getWorkbenchWindowCount(); for (int i = 0; i < welcomeFeatures.size(); i++) { AboutInfo newInfo = welcomeFeatures.get(i); String id = newInfo.getWelcomePerspectiveId(); if (id == null || i >= wCount) { openWelcomeEditor(window, new WelcomeEditorInput(newInfo), id); } } } }
Source:
protected List<CaseDefinitionEntity> transformDefinitions(DeploymentEntity deployment, ResourceEntity resource, Properties properties) { List<CaseDefinitionEntity> defList=transformer.createTransform().deployment(deployment).resource(resource).transform(); if(!properties.contains(TIMER_DECLR_KEY)){ properties.set(TIMER_DECLR_KEY,new HashMap()); } for(CaseDefinitionEntity caseDefinitionEntity: defList){ if(caseDefinitionEntity.getTimerJobDeclarationMap()!=null){ properties.get(TIMER_DECLR_KEY).putAll(caseDefinitionEntity.getTimerJobDeclarationMap()); } } return defList; }

Target:
protected List<CaseDefinitionEntity> transformDefinitions(DeploymentEntity deployment, ResourceEntity resource, Properties properties) { CmmnTransform cmmnTransform = transformer.createTransform(); List<CaseDefinitionEntity> defList=cmmnTransform.deployment(deployment).resource(resource).transform(); if(!properties.contains(JOB_DECLARATIONS_PROPERTY)){ properties.set(JOB_DECLARATIONS_PROPERTY, new HashMap<String, List<JobDeclaration<?, ?>>>()); } properties.get(JOB_DECLARATIONS_PROPERTY).putAll(cmmnTransform.getJobDeclarations()); return defList; }
Source:
public boolean handlesEvent(CellPreviewEvent<EntityModel> event) { NativeEvent nativeEvent = event.getNativeEvent(); if (!BrowserEvents.CLICK.equals(nativeEvent.getType())) { return false; } return true; }

Target:
public boolean handlesEvent(CellPreviewEvent<EntityModel> event) { return BrowserEvents.CLICK.equals(event.getNativeEvent().getType()); }
Source:
public HadoopWritableInputRow getCurrentValue() throws IOException, InterruptedException { Map<String, Object> event = currRow.getEvent(); for(Metric m : complexMetrics) { if(event.containsKey(m.getName())) { ComplexMetricSerde serde = ComplexMetrics.getSerdeForType(m.getComplexTypeName()); if (serde == null) { throw new ISE("Unknown type[%s]", m.getComplexTypeName()); } event.put(m.getName(), serde.getObjectStrategy().toBytes(event.get(m.getName()))); } } return new MapBasedHadoopWritableInputRow(new MapBasedInputRow(currRow.getTimestamp(), spec.getDimensions(), event)); }

Target:
public InputRow getCurrentValue() throws IOException, InterruptedException { return new SegmentInputRow( new MapBasedInputRow( currRow.getTimestamp(), spec.getDimensions(), currRow.getEvent() ) ); }
Source:
public Repository build(Environment env) { List<TerminologyRepositoryConfigurer> repositoryConfigurers = ClassPathScanner.INSTANCE.getComponentsByInterface(TerminologyRepositoryConfigurer.class) .stream() .filter(configurer -> repositoryId.equals(configurer.getRepositoryId())) .collect(Collectors.toList()); repositoryConfigurers .forEach(configurer -> { configurer.getAdditionalMappings().forEach(mappings::putMapping); }); if (deletionPolicy instanceof CompositeComponentDeletionPolicy) { CompositeComponentDeletionPolicy compositePolicy = (CompositeComponentDeletionPolicy) deletionPolicy; repositoryConfigurers.forEach(configurer -> { configurer.getComponentDeletionPolicies().forEach( (clazz, predicate) -> { if (!compositePolicy.getDeletionPolicies().containsKey(clazz)) { compositePolicy.getDeletionPolicies().put(clazz, predicate); } }); }); } final TerminologyRepository repository = new TerminologyRepository(repositoryId, mergeMaxResults, env, mappings, log); repository.bind(VersioningRequestBuilder.class, versioningRequestBuilder); repository.bind(ComponentDeletionPolicy.class, deletionPolicy); repository.bind(ComponentRevisionConflictProcessor.class, componentRevisionConflictProcessor); repository.bind(TerminologyComponents.class, terminologyComponents); repository.activate(); repository.service(RevisionIndex.class).hooks().addHook(hook); manager.put(repositoryId, repository); repository.waitForHealth(Health.GREEN, 3 * 60L ); new RepositoryRequest<>(repositoryId, initializer).execute(env); return repository; }

Target:
public Repository build(Environment env) { List<TerminologyRepositoryConfigurer> repositoryConfigurers = ClassPathScanner.INSTANCE.getComponentsByInterface(TerminologyRepositoryConfigurer.class) .stream() .filter(configurer -> repositoryId.equals(configurer.getRepositoryId())) .collect(Collectors.toList()); repositoryConfigurers .forEach(configurer -> { configurer.getAdditionalMappings().forEach(mappings::putMapping); }); if (deletionPolicy instanceof CompositeComponentDeletionPolicy) { repositoryConfigurers.forEach(configurer -> ((CompositeComponentDeletionPolicy) deletionPolicy).mergeWith(configurer.getComponentDeletionPolicy())); } final TerminologyRepository repository = new TerminologyRepository(repositoryId, mergeMaxResults, env, mappings, log); repository.bind(VersioningRequestBuilder.class, versioningRequestBuilder); repository.bind(ComponentDeletionPolicy.class, deletionPolicy); repository.bind(ComponentRevisionConflictProcessor.class, componentRevisionConflictProcessor); repository.bind(TerminologyComponents.class, terminologyComponents); repository.activate(); repository.service(RevisionIndex.class).hooks().addHook(hook); manager.put(repositoryId, repository); repository.waitForHealth(Health.GREEN, 3 * 60L ); new RepositoryRequest<>(repositoryId, initializer).execute(env); return repository; }
Source:
public synchronized boolean addMetadataStoreRealm(String realm) { if (_leaderElection.isLeader()) { if (_zkClient.isClosed()) { throw new IllegalStateException("ZkClient is closed!"); } return createZkRealm(realm); } String leaderHostName = _leaderElection.getCurrentLeaderInfo().getId(); String url = leaderHostName + "/admin/v2/namespaces/" + _namespace + "/metadata-store-realms/" + realm; HttpPut putRequest = new HttpPut(url); try { HttpResponse response = _forwardHttpClient.execute(putRequest); if (response.getStatusLine().getStatusCode() != 201) { HttpEntity respEntity = response.getEntity(); LOG.error("the forwarded request to leader has failed for addMetadataStoreRealm: {}", respEntity != null ? EntityUtils.toString(respEntity) : ""); return false; } } catch (IOException e) { LOG.error("the forwarded request to leader raised an exception for addMetadataStoreRealm", e); return false; } return true; }

Target:
public synchronized boolean addMetadataStoreRealm(String realm) { if (_leaderElection.isLeader()) { if (_zkClient.isClosed()) { throw new IllegalStateException("ZkClient is closed!"); } return createZkRealm(realm); } String urlSuffix = constructUrlSuffix(MetadataStoreRoutingConstants.MSDS_GET_ALL_REALMS_ENDPOINT, realm); return forwardRequestToLeader(urlSuffix, HttpConstants.RestVerbs.PUT, Response.Status.CREATED.getStatusCode()); }
Source:
public void testHere() { Geocoder geocoder = new HereGeocoder("<LINK_0>", "", "", null, 0, new AddressFormat()); String address = geocoder.getAddress(48.8575, 2.2944, null); assertEquals("6 Avenue Gustave Eiffel, Paris, Île-de-France, FRA", address); }

Target:
public void testHere() { Geocoder geocoder = new HereGeocoder(null, "", "", null, 0, new AddressFormat()); String address = geocoder.getAddress(48.8575, 2.2944, null); assertEquals("6 Avenue Gustave Eiffel, Paris, Île-de-France, FRA", address); }
Source:
public static ProcessMonitor getInstance() { if(instance == null) { synchronized (lock) { if(instance == null) { if (UIUtil.isLinux) { instance = new LinuxProcessMonitor(); } else if (UIUtil.isWindows) { instance = new WindowsProcessMonitor(); } else { instance = new ProcessMonitor(); } } } } return instance; }

Target:
public static ProcessMonitor getInstance() { if(instance == null) { synchronized (lock) { if(instance == null) { if (UIUtil.isLinux) { instance = new LinuxProcessMonitor(); } else if (UIUtil.isWindows) { instance = new WindowsProcessMonitor(); } else if(UIUtil.isMac) { instance = new MacProcessMonitor(); } else { instance = new ProcessMonitor(); } } } } return instance; }
Source:
public static double[] findCoordinates(String name) { double[] pair = new double[2]; if (name.equals("")) { pair = findCoordinatesByIp(); } else { String query = "<LINK_0>"; String key = "&key=AIzaSyB-_tiO6Z9cJusdLmgQoJ_GOAS7lYy3UHU"; String finalQuery = query + name + key; try { URL url = new URL(finalQuery); URLConnection conn = url.openConnection(); ByteArrayOutputStream output = new ByteArrayOutputStream(MAX_BYTE_STREAM); org.apache.commons.io.IOUtils.copy(conn.getInputStream(), output); output.close(); String result = output.toString(); twitter4j.JSONObject geoData = new twitter4j.JSONObject(result); if (geoData.getString("status").equals("OK")) { twitter4j.JSONArray places = geoData.getJSONArray("results"); twitter4j.JSONObject place = places.getJSONObject(0); twitter4j.JSONObject geometry = place.getJSONObject("geometry"); twitter4j.JSONObject location = geometry.getJSONObject("location"); double lat = Double.parseDouble(location.getString("lat")); double lon = Double.parseDouble(location.getString("lng")); pair[0] = lat; pair[1] = lon; return pair; } else { System.err.println("can't find coordinates"); } } catch (Exception ex) { System.err.println(ex.getMessage()); } } return pair; }

Target:
public static double[] findCoordinates(String name) throws LocationException, PropertiesException { double lat, lon; String key; if (name.equals("")) { return findCoordinatesByIp(); } else { PropertiesLoader prop = new PropertiesLoader(); try { key = "&key=" + prop.loadKey().split("\"")[1]; } catch (PropertiesException e) { throw new PropertiesException(e.getMessage()); } String query = "<LINK_0>"; String finalQuery = query + name + key; try { URL url = new URL(finalQuery); URLConnection conn = url.openConnection(); try (ByteArrayOutputStream output = new ByteArrayOutputStream(MAX_BYTE_STREAM)) { org.apache.commons.io.IOUtils.copy(conn.getInputStream(), output); output.close(); String result = output.toString(); twitter4j.JSONObject geoData = new twitter4j.JSONObject(result); if (geoData.getString("status").equals("OK")) { twitter4j.JSONArray places = geoData.getJSONArray("results"); twitter4j.JSONObject place = places.getJSONObject(0); twitter4j.JSONObject geometry = place.getJSONObject("geometry"); twitter4j.JSONObject location = geometry.getJSONObject("location"); lat = Double.parseDouble(location.getString("lat")); lon = Double.parseDouble(location.getString("lng")); } else { throw new LocationException("can't find coordinates"); } } catch (Exception ex) { throw new LocationException(ex.getMessage()); } } catch (Exception ex) { throw new LocationException(ex.getMessage()); } } return new double[]{lat, lon}; }
Source:
private long getTotalBytesRead(StoreFindToken newToken, List<MessageInfo> messageEntries, long logEndOffsetBeforeFind) { if (newToken.getOffset() == -1) { return newToken.getIndexStartOffset(); } else { if (messageEntries.size() > 0) { MessageInfo lastMsgInfo = messageEntries.get(messageEntries.size() - 1); return newToken.getOffset() + lastMsgInfo.getSize(); } else { return logEndOffsetBeforeFind; } } }

Target:
private long getTotalBytesRead(StoreFindToken newToken, List<MessageInfo> messageEntries, long logEndOffsetBeforeFind) { if (newToken.getOffset() == StoreFindToken.Uninitialized_Offset) { if (newToken.getIndexStartOffset() == StoreFindToken.Uninitialized_Offset) { return 0; } else { return newToken.getIndexStartOffset(); } } else { if (messageEntries.size() > 0) { MessageInfo lastMsgInfo = messageEntries.get(messageEntries.size() - 1); return newToken.getOffset() + lastMsgInfo.getSize(); } else { return logEndOffsetBeforeFind; } } }
Source:
public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } final SsldConverter other = (SsldConverter) obj; if (this.helper == null) { if (other.helper != null) { return false; } } else if (!this.helper.equals(other.helper)) { return false; } if (this.ssldRepository == null) { if (other.ssldRepository != null) { return false; } } else if (!this.ssldRepository.equals(other.ssldRepository)) { return false; } return true; }

Target:
public boolean equals(final Object obj) { return super.equals(obj) && Objects.equals(this.helper, ((SsldConverter) obj).helper) && Objects.equals(this.ssldRepository, ((SsldConverter) obj).ssldRepository); }
Source:
private void loadData(@NonNull CourseComponent courseComponent) { courseComponentId = courseComponent.getId(); if (courseData == null || getActivity() == null) return; if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().registerSticky(this); } if (!isOnCourseOutline) { getActivity().setTitle(courseComponent.getDisplayName()); } adapter.setData(courseComponent); if (adapter.hasCourseData()) { setUpBulkDownloadHeader(courseComponent); errorNotification.hideError(); } else { if (isAdded()) { UiUtil.removeFragmentByTag(getChildFragmentManager(), "bulk_download"); } errorNotification.showError(isVideoMode ? R.string.no_videos_text : R.string.no_chapter_text, null, -1, null); } if (!isOnCourseOutline) { environment.getAnalyticsRegistry().trackScreenView( Analytics.Screens.SECTION_OUTLINE, courseData.getCourse().getId(), courseComponent.getInternalName()); lastAccessManager.setLastAccessed(courseComponent.getCourseId(), courseComponent.getId()); } fetchLastAccessed(); }

Target:
private void loadData(@NonNull CourseComponent courseComponent) { courseComponentId = courseComponent.getId(); if (courseData == null || getActivity() == null) return; if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().registerSticky(this); } if (!isOnCourseOutline) { getActivity().setTitle(courseComponent.getDisplayName()); } adapter.setData(courseComponent); if (adapter.hasCourseData()) { setUpBulkDownloadHeader(courseComponent); errorNotification.hideError(); } else { UiUtil.removeFragmentByTag(CourseOutlineFragment.this, "bulk_download"); errorNotification.showError(isVideoMode ? R.string.no_videos_text : R.string.no_chapter_text, null, -1, null); } if (!isOnCourseOutline) { environment.getAnalyticsRegistry().trackScreenView( Analytics.Screens.SECTION_OUTLINE, courseData.getCourse().getId(), courseComponent.getInternalName()); lastAccessManager.setLastAccessed(courseComponent.getCourseId(), courseComponent.getId()); } fetchLastAccessed(); }
Source:
private void setPreservePathOnForward(Boolean preservePathOnForward) throws Exception { String opName = preservePathOnForward == null ? UNDEFINE_ATTRIBUTE_OPERATION : WRITE_ATTRIBUTE_OPERATION; ModelNode setPreservePathOp = createOpNode("subsystem=undertow/servlet-container=default", WRITE_ATTRIBUTE_OPERATION); setPreservePathOp.get("name").set("preserve-path-on-forward"); if (preservePathOnForward != null) { setPreservePathOp.get("value").set(preservePathOnForward); } CoreUtils.applyUpdate(setPreservePathOp, managementClient.getControllerClient()); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); }

Target:
private void setPreservePathOnForward(Boolean preservePathOnForward) throws Exception { String opName = preservePathOnForward == null ? UNDEFINE_ATTRIBUTE_OPERATION : WRITE_ATTRIBUTE_OPERATION; ModelNode setPreservePathOp = createOpNode("subsystem=undertow/servlet-container=default", opName); setPreservePathOp.get("name").set("preserve-path-on-forward"); if (preservePathOnForward != null) { setPreservePathOp.get("value").set(preservePathOnForward); } CoreUtils.applyUpdate(setPreservePathOp, managementClient.getControllerClient()); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); }
Source:
public void shouldUnRetireAPersonAttributeType() throws Exception { final String nonRetiredAttribute = "a0f5521c-dbbd-4c10-81b2-1b7ab18330df"; PersonAttributeType obj = service.getPersonAttributeTypeByUuid(nonRetiredAttribute); obj.setRetired(true); obj.setRetireReason("random reason"); obj = service.savePersonAttributeType(obj); Assert.assertTrue(obj.isRetired()); String json = "{\"deleted\": \"false\"}"; SimpleObject response = deserialize(handle(newPostRequest(getURI() + "/" + nonRetiredAttribute, json))); obj = service.getPersonAttributeTypeByUuid(nonRetiredAttribute); Assert.assertFalse(obj.isRetired()); Assert.assertEquals("false", PropertyUtils.getProperty(response, "retired").toString()); }

Target:
public void shouldUnRetireAPersonAttributeType() throws Exception { final String nonRetiredAttribute = "a0f5521c-dbbd-4c10-81b2-1b7ab18330df"; PersonAttributeType personAttrType = service.getPersonAttributeTypeByUuid(nonRetiredAttribute); personAttrType.setRetired(true); personAttrType.setRetireReason("random reason"); service.savePersonAttributeType(personAttrType); personAttrType = service.getPersonAttributeTypeByUuid(nonRetiredAttribute); Assert.assertTrue(personAttrType.isRetired()); String json = "{\"deleted\": \"false\"}"; SimpleObject response = deserialize(handle(newPostRequest(getURI() + "/" + nonRetiredAttribute, json))); personAttrType = service.getPersonAttributeTypeByUuid(nonRetiredAttribute); Assert.assertFalse(personAttrType.isRetired()); Assert.assertEquals("false", PropertyUtils.getProperty(response, "retired").toString()); }
Source:
public void replyToChange(Shell shell, RevisionInfo revisionInfo, GerritClient client) { EMap<String, EList<String>> permittedLabels = revisionInfo.getChangeInfo().getPermitted_labels(); EMap<String, LabelInfo> labels = revisionInfo.getChangeInfo().getLabels(); final ReplyDialog replyDialog = new ReplyDialog(shell, permittedLabels, labels); Display.getDefault().syncExec(new Runnable() { public void run() { int ret = replyDialog.open(); if (ret == IDialogConstants.OK_ID) { ReviewInput reviewInput = new ReviewInput(); reviewInput.setMessage(replyDialog.getMessage()); reviewInput.setLabels(replyDialog.getRadiosSelection()); reviewInput.setDrafts(ReviewInput.DRAFT_PUBLISH); SetReviewCommand reviewToEmit = client.setReview(revisionInfo.getChangeInfo().getId(), revisionInfo.getChangeInfo().getCurrent_revision()); reviewToEmit.setCommandInput(reviewInput); try { reviewToEmit.call(); } catch (EGerritException e1) { EGerritCorePlugin.logError(client.getRepository().formatGerritVersion() + e1.getMessage()); } } } }); }

Target:
public void replyToChange(Shell shell, RevisionInfo revisionInfo, GerritClient client) { EMap<String, EList<String>> permittedLabels = revisionInfo.getChangeInfo().getPermitted_labels(); EMap<String, LabelInfo> labels = revisionInfo.getChangeInfo().getLabels(); final ReplyDialog replyDialog = new ReplyDialog(shell, permittedLabels, labels); Display.getDefault().syncExec(new Runnable() { public void run() { int ret = replyDialog.open(); if (ret == IDialogConstants.OK_ID) { ReviewInput reviewInput = new ReviewInput(); reviewInput.setMessage(replyDialog.getMessage()); reviewInput.setLabels(replyDialog.getRadiosSelection()); reviewInput.setDrafts(ReviewInput.DRAFT_PUBLISH); SetReviewCommand reviewToEmit = client.setReview(revisionInfo.getChangeInfo().getId(), revisionInfo.getChangeInfo().getCurrent_revision()); reviewToEmit.setCommandInput(reviewInput); try { reviewToEmit.call(); QueryHelpers.reload(client, revisionInfo.getChangeInfo()); } catch (EGerritException e1) { EGerritCorePlugin.logError(client.getRepository().formatGerritVersion() + e1.getMessage()); } } } }); }
Source:
public void setListProperty(final String key, final List<String> values) { if (values == null) { setProperty(key, null); } else if (values.isEmpty()) { setProperty(key, ""); } else { StringBuilder builder = new StringBuilder(); for (String value : values) { builder.append(value + ", "); } builder.setLength(builder.length() - 2); setProperty(key, builder.toString()); } }

Target:
public void setListProperty(final String key, final List<String> values) { if (values == null) { setProperty(key, null); } else if (values.isEmpty()) { setProperty(key, ""); } else { final StringBuilder builder = new StringBuilder(); for (String value : values) { builder.append(value + ", "); } builder.setLength(builder.length() - 2); setProperty(key, builder.toString()); } }
Source:
public void emptyPartitionOverrideTest() throws Exception { assumeTrue(overrideEnabled); clusterManager.close(); metricRegistry = new MetricRegistry(); ClusterMap clusterManagerWithEmptyRecord = new HelixClusterManager(clusterMapConfig, selfInstanceName, new MockHelixManagerFactory(helixCluster, null, null), metricRegistry); Set<String> writableInClusterManager = new HashSet<>(); for (PartitionId partition : clusterManagerWithEmptyRecord.getWritablePartitionIds(null)) { String partitionStr = useComposite ? partition.toPathString() : partition.toPathString(); writableInClusterManager.add(partitionStr); } Set<String> writableInCluster = helixCluster.getWritablePartitions(); if (writableInCluster.isEmpty()) { writableInCluster = helixCluster.getAllWritablePartitions(); } assertEquals("Mismatch in writable partitions during initialization", writableInCluster, writableInClusterManager); }

Target:
public void emptyPartitionOverrideTest() throws Exception { assumeTrue(overrideEnabled); clusterManager.close(); metricRegistry = new MetricRegistry(); ClusterMap clusterManagerWithEmptyRecord = new HelixClusterManager(clusterMapConfig, selfInstanceName, new MockHelixManagerFactory(helixCluster, null, null), metricRegistry); Set<String> writableInClusterManager = new HashSet<>(); for (PartitionId partition : clusterManagerWithEmptyRecord.getWritablePartitionIds(null)) { String partitionStr = partition.toPathString(); writableInClusterManager.add(partitionStr); } Set<String> writableInCluster = helixCluster.getWritablePartitions(); if (writableInCluster.isEmpty()) { writableInCluster = helixCluster.getAllWritablePartitions(); } assertEquals("Mismatch in writable partitions during initialization", writableInCluster, writableInClusterManager); }
Source:
public boolean containsSubsequence(BootSequence subsequence) { if (subsequence == null) { return false; } boolean subsequenceLonger = subsequence.subsequences.size() > subsequences.size(); boolean subsequenceIsEmpty = subsequence.subsequences.size() == 0; if (subsequenceIsEmpty || subsequenceLonger) { return false; } int firstElementIndex = subsequences.indexOf(subsequence.subsequences.get(0)); boolean firstElementNotPresent = firstElementIndex == -1; boolean subsequenceTooLong = subsequences.size() - firstElementIndex < subsequence.subsequences.size(); if (firstElementNotPresent || subsequenceTooLong) { return false; } List<BootSequence> sublist = subsequences.subList(firstElementIndex, firstElementIndex + subsequence.subsequences.size()); return sublist.equals(subsequence.subsequences); }

Target:
public boolean containsSubsequence(BootSequence subsequence) { if (subsequence == null) { return false; } return components.containsAll(subsequence.components); }
Source:
public static void cleanUpTests(){ String pathToRepo = Config.getStringProperty("es.path.repo","test-resources"); File baseDirectory = new File(pathToRepo); File toDelete = baseDirectory.getParentFile(); try { FileUtil.deleteDir(toDelete.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } }

Target:
public static void cleanUpTests(){ String pathToRepo = Config.getStringProperty("es.path.repo","test-resources"); File baseDirectory = new File(pathToRepo); File toDelete = baseDirectory.getParentFile(); try { FileUtil.deleteDir(toDelete.getAbsolutePath()); } catch (IOException e) { Logger.error(ESIndexAPITest.class,e.getMessage()); } }
Source:
public SegmentStoreDataModel() { fDescriptors = new ArrayList<>(); String start = checkNotNull(Messages.SegmentStoreDataModel_Start); String end = checkNotNull(Messages.SegmentStoreDataModel_End); String length = checkNotNull(Messages.SegmentStoreDataModel_Length); fDescriptors.add(new DataChartTimestampDescriptor<>(start, new StartResolver(), null)); fDescriptors.add(new DataChartTimestampDescriptor<>(end, new EndResolver(), null)); fDescriptors.add(new DataChartDurationDescriptor<>(length, new LengthResolver())); }

Target:
public SegmentStoreDataModel() { String start = checkNotNull(Messages.SegmentStoreDataModel_Start); String end = checkNotNull(Messages.SegmentStoreDataModel_End); String length = checkNotNull(Messages.SegmentStoreDataModel_Length); fDescriptors.add(new DataChartTimestampDescriptor<>(start, new StartResolver())); fDescriptors.add(new DataChartTimestampDescriptor<>(end, new EndResolver())); fDescriptors.add(new DataChartDurationDescriptor<>(length, new LengthResolver())); }
Source:
public void testWithRootUrl_configured() { assertTrue(StringUtils.isNotBlank(JenkinsLocationConfiguration.get().getUrl())); RootUrlNotSetMonitor monitor = j.jenkins.getExtensionList(AdministrativeMonitor.class).get(RootUrlNotSetMonitor.class); assertFalse("Monitor must be activated", monitor.isActivated()); }

Target:
public void testWithRootUrl_configured() { JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); assertTrue(StringUtils.isNotBlank(config.getUrl())); RootUrlNotSetMonitor monitor = j.jenkins.getExtensionList(AdministrativeMonitor.class).get(RootUrlNotSetMonitor.class); assertFalse("Monitor must not be activated", monitor.isActivated()); config.setUrl(null); assertTrue("Monitor must be activated", monitor.isActivated()); config.setUrl("ftp://localhost:8080/jenkins"); assertTrue("Monitor must be activated", monitor.isActivated()); config.setUrl("http://localhost:8080/jenkins"); assertFalse("Monitor must be activated", monitor.isActivated()); }
Source:
public void saveVisit_shouldNotPersistNewEncounter() throws Exception { VisitService vs = Context.getVisitService(); Visit visit = vs.getVisit(1); Encounter encounter = new Encounter(); encounter.setEncounterDatetime(new Date()); encounter.setEncounterType(Context.getEncounterService().getEncounterType(1)); encounter.setPatient(visit.getPatient()); encounter.setLocation(visit.getLocation()); visit.addEncounter(encounter); vs.saveVisit(visit); assertNull(encounter.getEncounterId()); Context.getEncounterService().saveEncounter(encounter); Integer encounterId = encounter.getEncounterId(); Context.flushSession(); Context.clearSession(); visit = Context.getVisitService().getVisit(1); assertEquals(1, visit.getEncounters().size()); assertEquals(encounterId, ((Encounter) visit.getEncounters().toArray()[0]).getEncounterId()); }

Target:
public void saveVisit_shouldNotPersistNewEncounter() throws Exception { VisitService vs = Context.getVisitService(); Visit visit = vs.getVisit(1); Encounter encounter = new Encounter(); encounter.setEncounterDatetime(new Date()); encounter.setEncounterType(Context.getEncounterService().getEncounterType(1)); encounter.setPatient(visit.getPatient()); encounter.setLocation(visit.getLocation()); visit.addEncounter(encounter); vs.saveVisit(visit); Context.flushSession(); }
Source:
public void setRemoteLegendGraphicRequest( org.geotools.ows.wms.request.GetLegendGraphicRequest remoteLegendGraphicRequest) { this.remoteLegendGraphicRequest = remoteLegendGraphicRequest; Map<String, String> params = request.getRawKvp(); params.keySet() .forEach( k -> { if (!k.equalsIgnoreCase("layer")) this.remoteLegendGraphicRequest.setProperty( k, String.valueOf(params.get(k))); }); super.getLegendInfo() .setOnlineResource(this.remoteLegendGraphicRequest.getFinalURL().toExternalForm()); LOGGER.fine( String.format( "Cascaded GetLegend Request URL:%s", super.getLegendInfo().getOnlineResource())); }

Target:
public void setRemoteLegendGraphicRequest( org.geotools.ows.wms.request.GetLegendGraphicRequest remoteLegendGraphicRequest) { this.remoteLegendGraphicRequest = remoteLegendGraphicRequest; Map<String, String> params = request.getRawKvp(); params.keySet() .forEach( k -> { if (!k.equalsIgnoreCase("layer")) this.remoteLegendGraphicRequest.setProperty( k, String.valueOf(params.get(k))); }); super.getLegendInfo() .setOnlineResource(this.remoteLegendGraphicRequest.getFinalURL().toExternalForm()); LOGGER.fine("Cascaded GetLegend Request URL: " + super.getLegendInfo().getOnlineResource()); }
Source:
static boolean isHMSAvailable() { return OSUtils.isHuaweiDeviceType(); }

Target:
static boolean isHMSAvailable() { return OSUtils.isHuaweiDeviceType() && OSUtils.hasHMSLocationLibrary(); }
Source:
protected IStatus run(IProgressMonitor monitor) { RevCommit commit = null; try { commitOperation.execute(monitor); commit = commitOperation.getCommit(); CommitMessageComponentStateManager.deleteState(repository); RepositoryMapping mapping = RepositoryMapping .findRepositoryMapping(repository); if (mapping != null) mapping.fireRepositoryChanged(); } catch (CoreException e) { if (e.getCause() instanceof JGitInternalException) { return Activator.createErrorStatus(e.getLocalizedMessage(), e.getCause()); } if (e.getCause() instanceof AbortedByHookException) { showAbortedByHook(e.getCause()); return Status.CANCEL_STATUS; } else { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } } finally { GitLightweightDecorator.refresh(); } if (commit != null) { commitSucceeded = true; if (openCommitEditor) openCommitEditor(commit); if (pushUpstream) pushUpstream(commit); } return Status.OK_STATUS; }

Target:
protected IStatus run(IProgressMonitor monitor) { RevCommit commit = null; try { commitOperation.execute(monitor); commit = commitOperation.getCommit(); CommitMessageComponentStateManager.deleteState(repository); RepositoryMapping mapping = RepositoryMapping .findRepositoryMapping(repository); if (mapping != null) mapping.fireRepositoryChanged(); } catch (CoreException e) { if (e.getCause() instanceof JGitInternalException) { return Activator.createErrorStatus(e.getLocalizedMessage(), e.getCause()); } if (e.getCause() instanceof AbortedByHookException) { showAbortedByHook(e.getCause()); return Status.CANCEL_STATUS; } else { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } } finally { GitLightweightDecorator.refresh(); } if (commit != null) { if (openCommitEditor) openCommitEditor(commit); if (pushUpstream) pushUpstream(commit); } return Status.OK_STATUS; }
Source:
public static Thread[] findThreadsByName(final String threadName, final ThreadGroup threadGroup) { if (threadName == null) { throw new IllegalArgumentException("The threadName must not be null"); } if (threadGroup == null) { throw new IllegalArgumentException("The threadGroupName must not be null"); } final Thread[] threads = findThreadsByName(threadName); if(threads.length == 0) { return EMPTY_THREAD_ARRAY; } final List<Thread> matchedThreads = new ArrayList<Thread>(); for (int i = 0; i < threads.length; i++) { final Thread thread = threads[i]; if(thread != null && threadGroup.equals(thread.getThreadGroup())) { matchedThreads.add(thread); } } return matchedThreads.toArray(new Thread[matchedThreads.size()]); }

Target:
public static Collection<Thread> findThreadsByName(final String threadName, final ThreadGroup threadGroup) { return selectThreads(threadGroup, false, new NamePredicate(threadName)); }
Source:
default void inputDetail() { optional(network().comment()); optional(network().description()); optional(network().display()); optional(network().ip().address()); optional(network().ip().gateway()); optional(network().ip().netmask()); optional(network().mtu()); optional(network().name()); optional(network().stp()); optional(network().vlan().id()); optional(network().externalProvider().id()); }

Target:
default void inputDetail() { optional(network().comment()); optional(network().description()); optional(network().display()); optional(network().ip().address()); optional(network().ip().gateway()); optional(network().ip().netmask()); optional(network().mtu()); optional(network().name()); optional(network().stp()); optional(network().vlan().id()); }
Source:
public LinkedHashSet<String> getIncludePaths() { return myProperties.myIncludePaths; }

Target:
public List<String> getIncludePaths() { return Collections.unmodifiableList(myProperties.myIncludePaths); }
Source:
public DocumentModel run(DocumentModel doc) { String n = name; if (name == null || name.length() == 0) { n = doc.getName(); } if (Boolean.TRUE.equals(resetLifeCycle)) { return session.copy(doc.getRef(), target, n, CopyOption.RESET_LIFE_CYCLE); } return session.copy(doc.getRef(), target, n); }

Target:
public DocumentModel run(DocumentModel doc) { String n = name; if (StringUtils.isEmpty(name)) { n = doc.getName(); } List<CopyOption> options = new ArrayList<>(); if (resetLifeCycle) { options.add(CopyOption.RESET_LIFE_CYCLE); } return session.copy(doc.getRef(), target, n, options.toArray(CopyOption[]::new)); }
Source:
public void testPkToJsonHash() throws IOException { long timestampMillis = 1496712943447L; List<String> pKeys = new ArrayList<>(); pKeys.add("id"); pKeys.add("name"); Position position = new Position(new BinlogPosition(1L, "binlog-0001"), 0L); RowMap rowMap = new RowMap("insert", "MyDatabase", "MyTable", timestampMillis, pKeys, position); rowMap.putData("id", "9001"); rowMap.putData("name", "example"); String jsonString = rowMap.pkToJson(RowMap.KeyFormat.HASH); Assert.assertEquals("{\"database\":\"MyDatabase\",\"table\":\"MyTable\",\"pk.id\":\"9001\",\"pk.name\":\"example\"}", jsonString); }

Target:
public void testPkToJsonHash() throws IOException { List<String> pKeys = new ArrayList<>(); pKeys.add("id"); pKeys.add("name"); RowMap rowMap = new RowMap("insert", "MyDatabase", "MyTable", TIMESTAMP_MILLISECONDS, pKeys, POSITION); rowMap.putData("id", "9001"); rowMap.putData("name", "example"); String jsonString = rowMap.pkToJson(RowMap.KeyFormat.HASH); Assert.assertEquals("{\"database\":\"MyDatabase\",\"table\":\"MyTable\",\"pk.id\":\"9001\",\"pk.name\":\"example\"}", jsonString); }
Source:
@Override public void onMatch(RelOptRuleCall call) { if (call.rel(0) instanceof VoltLogicalCalc && call.rel(1) instanceof VoltLogicalTableScan) { VoltLogicalCalc calc = call.rel(0); VoltLogicalTableScan tableScan = call.rel(1); RelDistribution tableDist = tableScan.getTable().getDistribution(); if (tableDist.getType() == RelDistribution.Type.RANDOM_DISTRIBUTED) { throw new PlannerFallbackException("MP query not supported in Calcite planner."); } if (tableDist.getType() != RelDistribution.Type.SINGLETON && (calc.getProgram().getCondition() == null || ! isSinglePartitioned(calc.getProgram(), calc.getProgram().getCondition(), tableDist.getKeys()))) { throw new PlannerFallbackException("MP query not supported in Calcite planner."); } RelNode newTableScan = tableScan.copy(tableScan.getTraitSet().replace(tableDist), tableScan.getInputs()); call.transformTo(calc.copy(calc.getTraitSet().replace(tableDist), newTableScan, calc.getProgram())); } else { RelNode child = call.rel(1); RelDistribution childDist = child.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); if (childDist != RelDistributions.ANY) { SingleRel node = call.rel(0); call.transformTo(node.copy(node.getTraitSet().replace(childDist), node.getInputs())); } } }

Target:
@Override public void onMatch(RelOptRuleCall call) { if (call.rel(0) instanceof Calc && call.rel(1) instanceof TableScan) { final Calc calc = call.rel(0); final TableScan tableScan = call.rel(1); final Pair<Boolean, RexNode> r = RelDistributionUtils.isCalcScanSP(tableScan, calc); final RelDistribution tableDist = tableScan.getTable().getDistribution(); call.transformTo(calc.copy(calc.getTraitSet().replace(tableDist.with( tableDist.getType(), RelDistributionUtils.adjustProjection(calc.getProgram(), tableDist.getKeys()), r.getSecond(), r.getFirst())), calc.getInputs())); } else { final RelDistribution childDist = call.rel(1).getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); if (childDist != RelDistributions.ANY) { final SingleRel node = call.rel(0); final RelDistribution dist; if (node instanceof Calc) { dist = childDist.with(childDist.getType(), RelDistributionUtils.adjustProjection(((Calc) node).getProgram(), childDist.getKeys()), childDist.getPartitionEqualValue(), childDist.getIsSP()); } else { dist = childDist; } call.transformTo(node.copy(node.getTraitSet().replace(dist), node.getInputs())); } } }
Source:
public synchronized boolean bridgeLogin() { logger.trace("bridgeLogin() called."); Login bcp = this.bridgeAPI().login(); bcp.setPassword(this.bridgeInstance.veluxBridgeConfiguration().bridgePassword); if (bridgeCommunicate(bcp, false)) { logger.trace("bridgeLogin(): communication succeeded."); if (bcp.isCommunicationSuccessful()) { logger.trace("bridgeLogin(): storing authentication token for further access."); authenticationToken = bcp.getAuthToken(); return true; } } return false; }

Target:
public synchronized boolean bridgeLogin() { logger.trace("bridgeLogin() called."); Login bcp = bridgeAPI().login(); bcp.setPassword(bridgeInstance.veluxBridgeConfiguration().bridgePassword); if (bridgeCommunicate(bcp, false)) { logger.trace("bridgeLogin(): communication succeeded."); if (bcp.isCommunicationSuccessful()) { logger.trace("bridgeLogin(): storing authentication token for further access."); authenticationToken = bcp.getAuthToken(); return true; } } return false; }
Source:
public void acknowledge(OutputBufferId bufferId, long token) { OutputBuffer outputBuffer; synchronized (this) { if (delegate == null) { return; } outputBuffer = delegate; } outputBuffer.acknowledge(bufferId, token); }

Target:
public void acknowledge(OutputBufferId bufferId, long token) { OutputBuffer outputBuffer; synchronized (this) { checkState(delegate != null, "delegate is null"); outputBuffer = delegate; } outputBuffer.acknowledge(bufferId, token); }
Source:
public static ParamConfig fromJSON(JsonReader jsonReader) { if (jsonReader == null) { return null; } ParamConfig paramConfig = new ParamConfig(); jsonReader.readStringIfPresent("name", paramConfig::setName); jsonReader.readStringIfPresent("value", paramConfig::setValue); return paramConfig; }

Target:
private static ParamConfig fromJSON(JsonReader jsonReader) { ParamConfig paramConfig = new ParamConfig(); jsonReader.readStringIfPresent("name", paramConfig::setName); jsonReader.readStringIfPresent("value", paramConfig::setValue); return paramConfig; }
Source:
public void addProject(final String projectName) { File srcRoot = env.getSourceRootFile(); File projDir = new File(srcRoot, projectName); if (!env.getProjects().containsKey(projectName)) { Project project = new Project(projectName, "/" + projectName, env.getConfiguration()); List<RepositoryInfo> repos = getRepositoriesInDir(projDir); env.addRepositories(repos); env.getProjectRepositoriesMap().put(project, repos); env.getProjects().put(projectName, project); Set<Project> projectSet = new TreeSet<>(); projectSet.add(project); env.populateGroups(env.getGroups(), projectSet); } else { Project project = env.getProjects().get(projectName); Map<Project, List<RepositoryInfo>> map = env.getProjectRepositoriesMap(); List<RepositoryInfo> repos = getRepositoriesInDir(projDir); List<RepositoryInfo> allrepos = env.getRepositories(); synchronized (allrepos) { for (RepositoryInfo repo : repos) { if (!allrepos.contains(repo)) { allrepos.add(repo); } } for (RepositoryInfo repo : map.get(project)) { if (!repos.contains(repo)) { allrepos.remove(repo); } } } map.put(project, repos); } }

Target:
public Response addProject(final String projectName) { File srcRoot = env.getSourceRootFile(); File projDir = new File(srcRoot, projectName); if (!env.getProjects().containsKey(projectName)) { Project project = new Project(projectName, "/" + projectName, env.getConfiguration()); List<RepositoryInfo> repos = getRepositoriesInDir(projDir); env.addRepositories(repos); env.getProjectRepositoriesMap().put(project, repos); env.getProjects().put(projectName, project); Set<Project> projectSet = new TreeSet<>(); projectSet.add(project); env.populateGroups(env.getGroups(), projectSet); } else { Project project = env.getProjects().get(projectName); Map<Project, List<RepositoryInfo>> map = env.getProjectRepositoriesMap(); List<RepositoryInfo> repos = getRepositoriesInDir(projDir); List<RepositoryInfo> allrepos = env.getRepositories(); synchronized (allrepos) { for (RepositoryInfo repo : repos) { if (!allrepos.contains(repo)) { allrepos.add(repo); } } for (RepositoryInfo repo : map.get(project)) { if (!repos.contains(repo)) { allrepos.remove(repo); } } } map.put(project, repos); } return Response.status(Response.Status.CREATED).build(); }