List of usage examples for java.util List sort
@SuppressWarnings({ "unchecked", "rawtypes" }) default void sort(Comparator<? super E> c)
From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.op.manifest.KubernetesDeployManifestOperation.java
@Override public OperationResult operate(List _unused) { getTask().updateStatus(OP_NAME, "Beginning deployment of manifest..."); List<KubernetesManifest> inputManifests = description.getManifests(); List<KubernetesManifest> deployManifests = new ArrayList<>(); if (inputManifests == null || inputManifests.isEmpty()) { log.warn("Relying on deprecated single manifest input: " + description.getManifest()); inputManifests = Collections.singletonList(description.getManifest()); }/* w ww . java 2s . c om*/ inputManifests = inputManifests.stream().filter(Objects::nonNull).collect(Collectors.toList()); List<Artifact> requiredArtifacts = description.getRequiredArtifacts(); if (requiredArtifacts == null) { requiredArtifacts = new ArrayList<>(); } List<Artifact> optionalArtifacts = description.getOptionalArtifacts(); if (optionalArtifacts == null) { optionalArtifacts = new ArrayList<>(); } List<Artifact> artifacts = new ArrayList<>(); artifacts.addAll(requiredArtifacts); artifacts.addAll(optionalArtifacts); Set<Artifact> boundArtifacts = new HashSet<>(); for (KubernetesManifest manifest : inputManifests) { if (StringUtils.isEmpty(manifest.getNamespace()) && manifest.getKind().isNamespaced()) { manifest.setNamespace(credentials.getDefaultNamespace()); } KubernetesResourceProperties properties = findResourceProperties(manifest); if (properties == null) { throw new IllegalArgumentException("Unsupported Kubernetes object kind '" + manifest.getKind().toString() + "', unable to continue."); } KubernetesHandler deployer = properties.getHandler(); if (deployer == null) { throw new IllegalArgumentException("No deployer available for Kubernetes object kind '" + manifest.getKind().toString() + "', unable to continue."); } getTask().updateStatus(OP_NAME, "Swapping out artifacts in " + manifest.getFullResourceName() + " from context..."); ReplaceResult replaceResult = deployer.replaceArtifacts(manifest, artifacts); deployManifests.add(replaceResult.getManifest()); boundArtifacts.addAll(replaceResult.getBoundArtifacts()); } Set<Artifact> unboundArtifacts = new HashSet<>(requiredArtifacts); unboundArtifacts.removeAll(boundArtifacts); getTask().updateStatus(OP_NAME, "Checking if all requested artifacts were bound..."); if (!unboundArtifacts.isEmpty()) { throw new IllegalArgumentException("The following artifacts could not be bound: '" + unboundArtifacts + "' . Failing the stage as this is likely a configuration error."); } getTask().updateStatus(OP_NAME, "Sorting manifests by priority..."); deployManifests.sort(Comparator.comparingInt(m -> findResourceProperties(m).getHandler().deployPriority())); getTask().updateStatus(OP_NAME, "Deploy order is: " + String.join(", ", deployManifests.stream() .map(KubernetesManifest::getFullResourceName).collect(Collectors.toList()))); OperationResult result = new OperationResult(); for (KubernetesManifest manifest : deployManifests) { KubernetesResourceProperties properties = findResourceProperties(manifest); boolean versioned = description.getVersioned() == null ? properties.isVersioned() : description.getVersioned(); KubernetesArtifactConverter converter = versioned ? properties.getVersionedConverter() : properties.getUnversionedConverter(); KubernetesHandler deployer = properties.getHandler(); Moniker moniker = description.getMoniker(); Artifact artifact = converter.toArtifact(provider, manifest); getTask().updateStatus(OP_NAME, "Annotating manifest " + manifest.getFullResourceName() + " with artifact, relationships & moniker..."); KubernetesManifestAnnotater.annotateManifest(manifest, artifact); namer.applyMoniker(manifest, moniker); manifest.setName(converter.getDeployedName(artifact)); getTask().updateStatus(OP_NAME, "Swapping out artifacts in " + manifest.getFullResourceName() + " from other deployments..."); ReplaceResult replaceResult = deployer.replaceArtifacts(manifest, new ArrayList<>(result.getCreatedArtifacts())); boundArtifacts.addAll(replaceResult.getBoundArtifacts()); manifest = replaceResult.getManifest(); getTask().updateStatus(OP_NAME, "Submitting manifest " + manifest.getFullResourceName() + " to kubernetes master..."); result.merge(deployer.deploy(credentials, manifest)); result.getCreatedArtifacts().add(artifact); } result.getBoundArtifacts().addAll(boundArtifacts); result.removeSensitiveKeys(registry, accountName); return result; }
From source file:org.kitodo.production.metadata.MetadataProcessor.java
/** * alle Seiten des aktuellen Strukturelements ermitteln. */// ww w . ja v a 2s. com private void determinePagesStructure(LegacyDocStructHelperInterface inStrukturelement) { if (inStrukturelement == null) { return; } List<LegacyReferenceHelper> references = inStrukturelement.getAllReferences("to"); int zaehler = 0; int imageNr = 0; if (references != null) { references.sort((firstObject, secondObject) -> { Integer firstPage = 0; int secondPage = 0; LegacyMetadataTypeHelper mdt = this.myPrefs.getMetadataTypeByName("physPageNumber"); List<? extends LegacyMetadataHelper> listMetadata = firstObject.getTarget() .getAllMetadataByType(mdt); if (Objects.nonNull(listMetadata) && !listMetadata.isEmpty()) { LegacyMetadataHelper page = listMetadata.get(0); firstPage = Integer.parseInt(page.getValue()); } listMetadata = secondObject.getTarget().getAllMetadataByType(mdt); if (Objects.nonNull(listMetadata) && !listMetadata.isEmpty()) { LegacyMetadataHelper page = listMetadata.get(0); secondPage = Integer.parseInt(page.getValue()); } return firstPage.compareTo(secondPage); }); /* die Gre der Arrays festlegen */ this.structSeiten = new SelectItem[references.size()]; this.structurePageNew = new MetadataImpl[references.size()]; /* alle Referenzen durchlaufen und deren Metadaten ermitteln */ for (LegacyReferenceHelper ref : references) { LegacyDocStructHelperInterface target = ref.getTarget(); determineSecondPagesStructure(target, zaehler); if (imageNr == 0) { imageNr = determineThirdPagesStructure(target); } zaehler++; } } /* * Wenn eine Verknpfung zwischen Strukturelement und Bildern sein soll, * das richtige Bild anzeigen */ if (this.imageToStructuralElement) { identifyImage(imageNr - this.imageNumber); } }
From source file:jef.database.DbMetaData.java
/** * /* w ww . j a v a2 s.c o m*/ * * @param tableName * ?? * @return Map<String,String> key=?? value=?? */ public Optional<PrimaryKey> getPrimaryKey(String tableName) throws SQLException { tableName = MetaHolder.toSchemaAdjustedName(tableName); tableName = info.profile.getObjectNameToUse(tableName); Connection conn = getConnection(false); DatabaseMetaData databaseMetaData = conn.getMetaData(); ResultSet rs = null; PrimaryKey pk = null; List<PairIS> pkColumns = new ArrayList<PairIS>(); try { rs = databaseMetaData.getPrimaryKeys(null, schema, tableName); while (rs.next()) { String pkName = rs.getString("PK_NAME"); String col = rs.getString("COLUMN_NAME"); int seq = rs.getShort("KEY_SEQ"); if (pk == null) { pk = new PrimaryKey(pkName); } pkColumns.add(new PairIS(seq, col)); } if (pk == null) return Optional.empty(); } finally { DbUtils.close(rs); releaseConnection(conn); } pkColumns.sort((a, b) -> Integer.compare(a.first, b.first)); String[] columns = new String[pkColumns.size()]; for (int i = 0; i < pkColumns.size(); i++) { columns[i] = pkColumns.get(i).second; } pk.setColumns(columns); return Optional.of(pk); }
From source file:org.kitodo.production.metadata.MetadataProcessor.java
private ArrayList<SelectItem> getAddableMetadataTypes(LegacyDocStructHelperInterface myDocStruct, List<MetadataImpl> tempMetadataList) { ArrayList<SelectItem> selectItems = new ArrayList<>(); // determine all addable metadata types List<LegacyMetadataTypeHelper> types = myDocStruct.getAddableMetadataTypes(); if (types == null) { return selectItems; }//from w w w. j a v a2 s .c om // alle Metadatentypen, die keine Person sind, oder mit einem // Unterstrich anfangen rausnehmen for (LegacyMetadataTypeHelper mdt : new ArrayList<>(types)) { if (mdt.isPerson()) { types.remove(mdt); } } // sort the metadata types HelperComparator c = new HelperComparator(); c.setSortType(SortType.METADATA_TYPE); types.sort(c); int counter = types.size(); for (LegacyMetadataTypeHelper mdt : types) { selectItems.add(new SelectItem(mdt.getName(), this.metaHelper.getMetadatatypeLanguage(mdt))); LegacyMetadataHelper md = new LegacyMetadataHelper(mdt); MetadataImpl mdum = new MetadataImpl(md, counter, this.myPrefs, this.process); counter++; if (tempMetadataList != null) { tempMetadataList.add(mdum); } } return selectItems; }
From source file:com.gst.portfolio.savings.domain.SavingsAccount.java
protected List<SavingsAccountTransaction> retreiveOrderedNonInterestPostingTransactions() { final List<SavingsAccountTransaction> listOfTransactionsSorted = retreiveListOfTransactions(); final List<SavingsAccountTransaction> orderedNonInterestPostingTransactions = new ArrayList<>(); for (final SavingsAccountTransaction transaction : listOfTransactionsSorted) { if (!(transaction.isInterestPostingAndNotReversed() || transaction.isOverdraftInterestAndNotReversed()) && transaction.isNotReversed()) { orderedNonInterestPostingTransactions.add(transaction); }// w ww. ja va 2 s . co m } orderedNonInterestPostingTransactions.sort(new SavingsAccountTransactionComparator()); return orderedNonInterestPostingTransactions; }
From source file:org.sleuthkit.autopsy.experimental.autoingest.AutoIngestManager.java
/** * Gets snapshots of the pending jobs queue, running jobs list, and * completed jobs list. Any of these collection can be excluded by passing a * null for the correspioding in/out list parameter. * * @param pendingJobs A list to be populated with pending jobs, can be * null.//from www . jav a2 s. co m * @param runningJobs A list to be populated with running jobs, can be * null. * @param completedJobs A list to be populated with competed jobs, can be * null. */ void getJobs(List<AutoIngestJob> pendingJobs, List<AutoIngestJob> runningJobs, List<AutoIngestJob> completedJobs) { synchronized (jobsLock) { if (null != pendingJobs) { pendingJobs.clear(); pendingJobs.addAll(this.pendingJobs); } if (null != runningJobs) { runningJobs.clear(); if (null != currentJob) { runningJobs.add(currentJob); } for (AutoIngestJob job : hostNamesToRunningJobs.values()) { runningJobs.add(job); runningJobs.sort(new AutoIngestJob.AlphabeticalComparator()); // RJCTODO: This sort should be done in the AID } } if (null != completedJobs) { completedJobs.clear(); completedJobs.addAll(this.completedJobs); } } }
From source file:org.cgiar.ccafs.marlo.action.projects.ProjectOutcomeAction.java
@Override public void prepare() throws Exception { // Get current CRP loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP); loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId()); try {//from w w w .j a v a 2 s. co m projectOutcomeID = Long.parseLong( StringUtils.trim(this.getRequest().getParameter(APConstants.PROJECT_OUTCOME_REQUEST_ID))); ProjectOutcome outcome = projectOutcomeManager.getProjectOutcomeById(projectOutcomeID); if (!outcome.getPhase().equals(this.getActualPhase())) { List<ProjectOutcome> projectOutcomes = outcome.getProject().getProjectOutcomes().stream() .filter(c -> c.isActive() && c.getCrpProgramOutcome().getComposeID() .equals(outcome.getCrpProgramOutcome().getComposeID()) && c.getPhase().equals(this.getActualPhase())) .collect(Collectors.toList()); if (!projectOutcomes.isEmpty()) { projectOutcomeID = projectOutcomes.get(0).getId(); } } } catch (Exception e) { LOG.error("unable to parse projectOutcomeID", e); /** * Original code swallows the exception and didn't even log it. Now we at least log it, * but we need to revisit to see if we should continue processing or re-throw the exception. */ } if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) { transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID)); ProjectOutcome history = (ProjectOutcome) auditLogManager.getHistory(transaction); if (history != null) { projectOutcome = history; } else { this.transaction = null; this.setTransaction("-1"); } } else { projectOutcome = projectOutcomeManager.getProjectOutcomeById(projectOutcomeID); } if (projectOutcome != null) { Path path = this.getAutoSaveFilePath(); if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) { BufferedReader reader = null; reader = new BufferedReader(new FileReader(path.toFile())); Gson gson = new GsonBuilder().create(); JsonObject jReader = gson.fromJson(reader, JsonObject.class); reader.close(); AutoSaveReader autoSaveReader = new AutoSaveReader(); projectOutcome = (ProjectOutcome) autoSaveReader.readFromJson(jReader); this.setDraft(true); project = projectManager.getProjectById(projectOutcome.getProject().getId()); projectID = project.getId(); Project projectDb = projectManager.getProjectById(project.getId()); project.setProjectInfo(projectDb.getProjecInfoPhase(this.getActualPhase())); List<ProjectMilestone> milestones = new ArrayList<>(); if (projectOutcome.getMilestones() != null) { for (ProjectMilestone crpMilestone : projectOutcome.getMilestones()) { if (crpMilestone.getCrpMilestone() != null) { crpMilestone.setCrpMilestone(crpMilestoneManager .getCrpMilestoneById(crpMilestone.getCrpMilestone().getId())); milestones.add(crpMilestone); } } } projectOutcome.setMilestones(milestones); } else { this.setDraft(false); project = projectManager.getProjectById(projectOutcome.getProject().getId()); projectID = project.getId(); project.setProjectInfo(project.getProjecInfoPhase(this.getActualPhase())); projectOutcome.setMilestones(projectOutcome.getProjectMilestones().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); if (this.hasSpecificities(APConstants.CRP_SHOW_PROJECT_OUTCOME_COMMUNICATIONS)) { projectOutcome.setCommunications(projectOutcome.getProjectCommunications().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); } projectOutcome.setNextUsers(projectOutcome.getProjectNextusers().stream().filter(c -> c.isActive()) .collect(Collectors.toList())); projectOutcome.setIndicators(projectOutcome.getProjectOutcomeIndicators().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); if (this.isLessonsActive()) { this.loadLessonsOutcome(loggedCrp, projectOutcome); } } } Set<CrpMilestone> crpMilestones = new HashSet<>(); if (projectOutcome.getMilestones() != null) { for (ProjectMilestone crpMilestone : projectOutcome.getMilestones()) { CrpMilestone milestone = crpMilestoneManager .getCrpMilestoneById(crpMilestone.getCrpMilestone().getId()); milestone.setIndex(crpMilestone.getId()); crpMilestones.add(milestone); } } milestonesProject = new ArrayList<>(); milestonesProject.addAll(crpMilestones); milestonesProject.sort(Comparator.comparing(CrpMilestone::getYear)); // Collections.sort(milestonesProject, (m1, m2) -> m1.getIndex().compareTo(m2.getIndex())); if (projectOutcome != null) { crpProgramOutcome = crpProgramOutcomeManager .getCrpProgramOutcomeById(projectOutcome.getCrpProgramOutcome().getId()); projectOutcome.setCrpProgramOutcome(crpProgramOutcome); milestones = projectOutcome.getCrpProgramOutcome().getCrpMilestones().stream().filter(c -> c.isActive()) .collect(Collectors.toList()); milestones.sort(Comparator.comparing(CrpMilestone::getYear)); } /* * Loading basic List */ targetUnits = srfTargetUnitManager.findAll().stream().filter(c -> c.isActive()) .collect(Collectors.toList()); projectOutcome.setCrpProgramOutcome( crpProgramOutcomeManager.getCrpProgramOutcomeById(projectOutcome.getCrpProgramOutcome().getId())); projectOutcome.getCrpProgramOutcome().setIndicators(projectOutcome.getCrpProgramOutcome() .getCrpProgramOutcomeIndicators().stream().filter(c -> c.isActive()).collect(Collectors.toList())); ; String params[] = { loggedCrp.getAcronym(), project.getId() + "" }; projectOutcomeDB = projectOutcomeManager.getProjectOutcomeById(projectOutcomeID); this.setBasePermission(this.getText(Permission.PROJECT_CONTRIBRUTIONCRP_BASE_PERMISSION, params)); if (this.isHttpPost()) { /** * This might seem very strange what is going on here, but this is due to issue #1124. The Struts2 Prepare * interceptor will set the values on the projectOutcome entity during save, but if we leave the values here and * they ids change then Hibernate will be unhappy. */ if (projectOutcome.getMilestones() != null) { projectOutcome.getMilestones().clear(); } if (projectOutcome.getCommunications() != null) { projectOutcome.getCommunications().clear(); } if (projectOutcome.getNextUsers() != null) { projectOutcome.getNextUsers().clear(); } if (projectOutcome.getIndicators() != null) { projectOutcome.getIndicators().clear(); } /** * Hack to fix ManyToOne issue as a result of issue #1124 */ projectOutcome.setAchievedUnit(null); projectOutcome.setExpectedUnit(null); } }
From source file:org.cgiar.ccafs.marlo.action.projects.DeliverableListAction.java
public List<Deliverable> getDeliverables(boolean open, boolean closed) { try {/* w w w.ja v a 2 s. c om*/ if (open) { if (this.isPlanningActive()) { List<Deliverable> openA = deliverables.stream() .filter(a -> a.isActive() && a.getDeliverableInfo(this.getActualPhase()) != null && ((a.getDeliverableInfo(this.getActualPhase()).getStatus() == null || a.getDeliverableInfo(this.getActualPhase()).getStatus() == Integer .parseInt(ProjectStatusEnum.Ongoing.getStatusId()) || (a.getDeliverableInfo(this.getActualPhase()).getStatus() == Integer .parseInt(ProjectStatusEnum.Extended.getStatusId()) || a.getDeliverableInfo(this.getActualPhase()).getStatus() .intValue() == 0 || a.getDeliverableInfo(this.getActualPhase()).getStatus() .intValue() == -1)))) .collect(Collectors.toList()); return openA; } else { List<Deliverable> openA = deliverables.stream() .filter(a -> a.isActive() && a.getDeliverableInfo(this.getActualPhase()) != null && ((a.getDeliverableInfo(this.getActualPhase()).getStatus() == null || a.getDeliverableInfo(this.getActualPhase()).getStatus() == Integer .parseInt(ProjectStatusEnum.Ongoing.getStatusId()) || (a.getDeliverableInfo(this.getActualPhase()).getStatus() == Integer .parseInt(ProjectStatusEnum.Extended.getStatusId()) || a.getDeliverableInfo(this.getActualPhase()).getStatus() .intValue() == 0)))) .collect(Collectors.toList()); openA.addAll(deliverables.stream().filter(d -> d.isActive() && d.getDeliverableInfo(this.getActualPhase()) != null && d.getDeliverableInfo(this.getActualPhase()).getYear() == this.getCurrentCycleYear() && d.getDeliverableInfo(this.getActualPhase()).getStatus() != null && d.getDeliverableInfo(this.getActualPhase()).getStatus().intValue() == Integer .parseInt(ProjectStatusEnum.Complete.getStatusId())) .collect(Collectors.toList())); openA.addAll(deliverables.stream() .filter(d -> d.isActive() && d.getDeliverableInfo(this.getActualPhase()) != null && d.getDeliverableInfo(this.getActualPhase()).getNewExpectedYear() != null && d.getDeliverableInfo(this.getActualPhase()).getNewExpectedYear() .intValue() == this.getCurrentCycleYear() && d.getDeliverableInfo(this.getActualPhase()).getStatus() != null && d.getDeliverableInfo(this.getActualPhase()).getStatus().intValue() == Integer .parseInt(ProjectStatusEnum.Complete.getStatusId())) .collect(Collectors.toList())); openA.sort((p1, p2) -> p1.getDeliverableInfo(this.getActualPhase()) .isRequieriedReporting(this.getCurrentCycleYear()) .compareTo(p2.getDeliverableInfo(this.getActualPhase()) .isRequieriedReporting(this.getCurrentCycleYear()))); HashSet<Deliverable> deliverables = new HashSet<>(); deliverables.addAll(openA); openA.clear(); openA.addAll(deliverables); return openA; } } else { if (this.isPlanningActive()) { List<Deliverable> openA = new ArrayList<>(); if (closed) { openA = deliverables.stream().filter(a -> a.isActive() && a.getDeliverableInfo(this.getActualPhase()) != null && ((a.getDeliverableInfo(this.getActualPhase()).getStatus() != null && ((a.getDeliverableInfo(this.getActualPhase()).getStatus() == Integer .parseInt(ProjectStatusEnum.Cancelled.getStatusId())))))) .collect(Collectors.toList()); } else { openA = deliverables.stream().filter(a -> a.isActive() && a.getDeliverableInfo(this.getActualPhase()) != null && ((a.getDeliverableInfo(this.getActualPhase()).getStatus() != null && ((a.getDeliverableInfo(this.getActualPhase()).getStatus() == Integer .parseInt(ProjectStatusEnum.Complete.getStatusId())))))) .collect(Collectors.toList()); } return openA; } else { List<Deliverable> openA = new ArrayList<>(); if (closed) { openA = deliverables.stream().filter(a -> a.isActive() && a.getDeliverableInfo(this.getActualPhase()) != null && ((a.getDeliverableInfo(this.getActualPhase()).getStatus() != null && ((a.getDeliverableInfo(this.getActualPhase()).getStatus() == Integer .parseInt(ProjectStatusEnum.Cancelled.getStatusId())))))) .collect(Collectors.toList()); } else { openA = deliverables.stream().filter(a -> a.isActive() && a.getDeliverableInfo(this.getActualPhase()) != null && ((a.getDeliverableInfo(this.getActualPhase()).getStatus() != null && ((a.getDeliverableInfo(this.getActualPhase()).getStatus() == Integer .parseInt(ProjectStatusEnum.Complete.getStatusId())))))) .collect(Collectors.toList()); } openA.removeAll(deliverables.stream().filter(d -> d.isActive() && d.getDeliverableInfo(this.getActualPhase()) != null && d.getDeliverableInfo(this.getActualPhase()).getYear() == this.getCurrentCycleYear() && d.getDeliverableInfo(this.getActualPhase()).getStatus() != null && d.getDeliverableInfo(this.getActualPhase()).getStatus().intValue() == Integer .parseInt(ProjectStatusEnum.Complete.getStatusId())) .collect(Collectors.toList())); openA.removeAll(deliverables.stream() .filter(d -> d.isActive() && d.getDeliverableInfo(this.getActualPhase()) != null && d.getDeliverableInfo(this.getActualPhase()).getNewExpectedYear() != null && d.getDeliverableInfo(this.getActualPhase()).getNewExpectedYear() .intValue() == this.getCurrentCycleYear() && d.getDeliverableInfo(this.getActualPhase()).getStatus() != null && d.getDeliverableInfo(this.getActualPhase()).getStatus().intValue() == Integer .parseInt(ProjectStatusEnum.Complete.getStatusId())) .collect(Collectors.toList())); openA.sort((p1, p2) -> p1.getDeliverableInfo(this.getActualPhase()) .isRequieriedReporting(this.getCurrentCycleYear()) .compareTo(p2.getDeliverableInfo(this.getActualPhase()) .isRequieriedReporting(this.getCurrentCycleYear()))); HashSet<Deliverable> deliverables = new HashSet<>(); deliverables.addAll(openA); openA.clear(); openA.addAll(deliverables); return openA; } } } catch (Exception e) { e.printStackTrace(); return new ArrayList<>(); } }
From source file:com.flipkart.poseidon.internal.ParamValidationFilter.java
private Map<String, Object> validateParams(PoseidonRequest poseidonRequest, ParamPOJO[] params, boolean failOnMissingValue) throws BadRequestException { Map<String, Object> parsedParams = new HashMap<>(); //Initial params that will be passed to hydra to START processing if (params != null) { final List<ParamPOJO> pathParams = new ArrayList<>(); for (ParamPOJO param : params) { String name = param.getName(); String internalName = param.getInternalName(); ParamPOJO.DataType datatype = param.getDatatype(); Object defaultValue = param.getDefaultValue(); String separator = param.getSeparator(); boolean multivalue = param.getMultivalue() || separator != null; boolean isBodyRequest = param.isBody(); boolean isHeader = param.isHeader(); boolean isPathParam = param.isPathparam(); Object value = null;//from w w w. j a v a2 s.c o m if (isHeader) { String attribute = poseidonRequest.getHeader(name); if (failOnMissingValue && attribute == null) { throw new BadRequestException("Missing header : " + name); } if (!failOnMissingValue && attribute == null && defaultValue != null) { // Optional param, value is not present but default is specified value = defaultValue; } else { value = attribute; } } else if (isBodyRequest) { String bodyString = poseidonRequest.getAttribute(RequestConstants.BODY); if (!StringUtils.isEmpty(bodyString)) { try { if ((param.getJavatype() == null || param.getJavatype().isEmpty()) && (param.getDatatype() == null)) { value = bodyString; } else { value = configuration.getObjectMapper().readValue(bodyString, Class.forName(param.getJavatype())); } } catch (IOException e) { logger.error("Error in reading body : {}", e.getMessage()); } catch (ClassNotFoundException e) { logger.error("Error in finding class for body : {}", e.getMessage()); } } if (failOnMissingValue && value == null) { throw new BadRequestException("Request Body is either missing or invalid for : " + name); } } else if (isPathParam) { param.setGreedyPosition(param.getPosition()); pathParams.add(param); } else if (param.isFile()) { value = poseidonRequest.getAttribute(name); if (failOnMissingValue && value == null) { throw new BadRequestException("Missing parameter : " + name); } } else { Object attribute = poseidonRequest.getAttribute(name); if (failOnMissingValue && attribute == null) { throw new BadRequestException("Missing parameter : " + name); } if (multivalue && separator != null && attribute != null) { attribute = ((String[]) attribute)[0].split(separator); } if (!failOnMissingValue && attribute == null && defaultValue != null) { // Optional param, value is not present but default is specified value = defaultValue; } else { value = parseParamValues(name, (String[]) attribute, datatype, multivalue); } } if (internalName != null && !internalName.isEmpty()) { parsedParams.put(internalName, value); } else { parsedParams.put(name, value); } } if (!pathParams.isEmpty()) { pathParams.sort((a, b) -> a.getPosition() - b.getPosition()); for (int i = 0; i < pathParams.size(); i++) { ParamPOJO param = pathParams.get(i); String name = param.getName(); String internalName = param.getInternalName(); Object value = null; int pos = param.getPosition(); int greedyPos = param.getGreedyPosition(); String[] splitUrl = poseidonRequest.getUrl().split("/"); String[] splitActual = ((String) RequestContext.get(RequestConstants.URI)).split("/"); if (pos >= splitUrl.length) { throw new BadRequestException("Missing path parameter : " + name); } boolean isGreedyParam = splitActual[pos].length() >= 2 && splitActual[pos].startsWith("*") && splitActual[pos].endsWith("*"); if (splitUrl.length == splitActual.length || !isGreedyParam) { value = splitUrl[greedyPos]; } else if (isGreedyParam) { int nextPos = greedyPos + 1; if (pos == splitActual.length - 1) { nextPos = splitUrl.length; } else { for (int j = greedyPos + 1; j < splitUrl.length; j++) { if (splitActual[pos + 1].equals(splitUrl[j])) { nextPos = j; break; } } } for (int j = i + 1; j < pathParams.size(); j++) { ParamPOJO nextParam = pathParams.get(j); nextParam.setGreedyPosition(nextParam.getGreedyPosition() + (nextPos - greedyPos - 1)); } value = getGreedyPathParam(greedyPos, nextPos, splitUrl); } if (value == null) { throw new BadRequestException("Missing path parameter : " + name); } if (internalName != null && !internalName.isEmpty()) { parsedParams.put(internalName, value); } else { parsedParams.put(name, value); } } } } return parsedParams; }
From source file:org.cgiar.ccafs.marlo.action.powb.PowbCollaborationAction.java
@Override public void prepare() throws Exception { // Get current CRP loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP); loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId()); Phase phase = this.getActualPhase(); // If there is a history version being loaded if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) { transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID)); PowbSynthesis history = (PowbSynthesis) auditLogManager.getHistory(transaction); if (history != null) { powbSynthesis = history;//from ww w. j a va 2 s.c o m powbSynthesisID = powbSynthesis.getId(); } else { this.transaction = null; this.setTransaction("-1"); } } else { // Get Liaison institution ID Parameter try { liaisonInstitutionID = Long.parseLong(StringUtils .trim(this.getRequest().getParameter(APConstants.LIAISON_INSTITUTION_REQUEST_ID))); } catch (NumberFormatException e) { User user = userManager.getUser(this.getCurrentUser().getId()); if (user.getLiasonsUsers() != null || !user.getLiasonsUsers().isEmpty()) { List<LiaisonUser> liaisonUsers = new ArrayList<>(user.getLiasonsUsers().stream() .filter(lu -> lu.isActive() && lu.getLiaisonInstitution().isActive() && lu.getLiaisonInstitution().getCrp().getId() == loggedCrp.getId() && lu.getLiaisonInstitution().getInstitution() == null) .collect(Collectors.toList())); if (!liaisonUsers.isEmpty()) { boolean isLeader = false; for (LiaisonUser liaisonUser : liaisonUsers) { LiaisonInstitution institution = liaisonUser.getLiaisonInstitution(); if (institution.isActive()) { if (institution.getCrpProgram() != null) { if (institution.getCrpProgram() .getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) { liaisonInstitutionID = institution.getId(); isLeader = true; break; } } else { if (institution.getAcronym().equals("PMU")) { liaisonInstitutionID = institution.getId(); isLeader = true; break; } } } } if (!isLeader) { liaisonInstitutionID = this.firstFlagship(); } } else { liaisonInstitutionID = this.firstFlagship(); } } else { liaisonInstitutionID = this.firstFlagship(); } } try { powbSynthesisID = Long .parseLong(StringUtils.trim(this.getRequest().getParameter(APConstants.POWB_SYNTHESIS_ID))); powbSynthesis = powbSynthesisManager.getPowbSynthesisById(powbSynthesisID); if (!powbSynthesis.getPhase().equals(phase)) { powbSynthesis = powbSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID); if (powbSynthesis == null) { powbSynthesis = this.createPowbSynthesis(phase.getId(), liaisonInstitutionID); } powbSynthesisID = powbSynthesis.getId(); } } catch (Exception e) { powbSynthesis = powbSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID); if (powbSynthesis == null) { powbSynthesis = this.createPowbSynthesis(phase.getId(), liaisonInstitutionID); } powbSynthesisID = powbSynthesis.getId(); } } if (powbSynthesis != null) { PowbSynthesis powbSynthesisDB = powbSynthesisManager.getPowbSynthesisById(powbSynthesisID); powbSynthesisID = powbSynthesisDB.getId(); liaisonInstitutionID = powbSynthesisDB.getLiaisonInstitution().getId(); liaisonInstitution = liaisonInstitutionManager.getLiaisonInstitutionById(liaisonInstitutionID); Path path = this.getAutoSaveFilePath(); // Verify if there is a Draft file if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) { BufferedReader reader; reader = new BufferedReader(new FileReader(path.toFile())); Gson gson = new GsonBuilder().create(); JsonObject jReader = gson.fromJson(reader, JsonObject.class); AutoSaveReader autoSaveReader = new AutoSaveReader(); powbSynthesis = (PowbSynthesis) autoSaveReader.readFromJson(jReader); powbSynthesisID = powbSynthesis.getId(); if (powbSynthesis.getPowbCollaborationGlobalUnitsList() != null) { for (PowbCollaborationGlobalUnit powbCollaborationGlobalUnit : powbSynthesis .getPowbCollaborationGlobalUnitsList()) { if (powbCollaborationGlobalUnit.getGlobalUnit() != null && powbCollaborationGlobalUnit.getGlobalUnit().getId() != -1) { powbCollaborationGlobalUnit.setGlobalUnit(crpManager .getGlobalUnitById(powbCollaborationGlobalUnit.getGlobalUnit().getId())); } } } if (powbSynthesis.getRegions() != null) { for (PowbCollaborationRegion powbCollaborationRegion : powbSynthesis.getRegions()) { if (powbCollaborationRegion.getLiaisonInstitution() != null && powbCollaborationRegion.getLiaisonInstitution().getId() != -1) { powbCollaborationRegion .setLiaisonInstitution(liaisonInstitutionManager.getLiaisonInstitutionById( powbCollaborationRegion.getLiaisonInstitution().getId())); } } powbSynthesis.getRegions().sort((p1, p2) -> p1.getLiaisonInstitution().getAcronym() .compareTo(p2.getLiaisonInstitution().getAcronym())); } this.setDraft(true); reader.close(); } else { this.setDraft(false); // Check if ToC relation is null -create it if (powbSynthesis.getCollaboration() == null) { PowbCollaboration powbCollaboration = new PowbCollaboration(); // create one to one relation powbSynthesis.setCollaboration(powbCollaboration); powbCollaboration.setPowbSynthesis(powbSynthesis); // save the changes powbSynthesis = powbSynthesisManager.savePowbSynthesis(powbSynthesis); } powbSynthesis.setPowbCollaborationGlobalUnitsList(powbSynthesis.getPowbCollaborationGlobalUnits() .stream().filter(c -> c.isActive()).collect(Collectors.toList())); powbSynthesis.setRegions(powbSynthesis.getPowbCollaborationRegions().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); powbSynthesis.getRegions().sort((p1, p2) -> p1.getLiaisonInstitution().getAcronym() .compareTo(p2.getLiaisonInstitution().getAcronym())); } } if (this.isPMU()) { // this.loadLocations(); crpPrograms = loggedCrp.getCrpPrograms().stream() .filter(c -> c.isActive() && c.getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) .collect(Collectors.toList()); for (CrpProgram crpProgram : crpPrograms) { List<LiaisonInstitution> liaisonInstitutions = crpProgram.getLiaisonInstitutions().stream() .filter(c -> c.isActive()).collect(Collectors.toList()); if (!liaisonInstitutions.isEmpty()) { PowbSynthesis powbSynthesisProgram = powbSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutions.get(0).getId()); if (powbSynthesisProgram != null) { powbSynthesisProgram.setPowbCollaborationGlobalUnitsList( powbSynthesisProgram.getPowbCollaborationGlobalUnits().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); crpProgram.setCollaboration(powbSynthesisProgram.getCollaboration()); crpProgram.setSynthesis(powbSynthesisProgram); } } if (crpProgram.getSynthesis() == null) { crpProgram.setSynthesis(new PowbSynthesis()); } if (crpProgram.getCollaboration() == null) { crpProgram.setCollaboration(new PowbCollaboration()); } } crpPrograms.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym())); } if (this.hasSpecificities(APConstants.CRP_HAS_REGIONS)) { regions = liaisonInstitutionManager.findAll().stream() .filter(c -> c.isActive() && c.getCrpProgram() != null && c.getCrpProgram().getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue()) .collect(Collectors.toList()); regions.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym())); } else { regions = new ArrayList<>(); } globalUnits = new ArrayList<>(); List<GlobalUnit> globalUnitsList = crpManager.findAll().stream() .filter(c -> c.isActive() && c.getGlobalUnitType().getId() != 2).collect(Collectors.toList()); for (GlobalUnit globalUnit : globalUnitsList) { if (!globalUnit.getId().equals(loggedCrp.getId())) { if (globalUnit.getAcronym() != null && globalUnit.getAcronym().trim().length() == 0) { globalUnit.setAcronymValid(globalUnit.getName()); } else { globalUnit.setAcronymValid(globalUnit.getAcronym()); } globalUnits.add(globalUnit); } } globalUnits.sort((p1, p2) -> p1.getAcronymValid().compareTo(p2.getAcronymValid())); globalUnits.sort((p1, p2) -> { if (p1.getGlobalUnitType().getId().compareTo(p2.getGlobalUnitType().getId()) == 0) { return p1.getAcronymValid().compareTo(p2.getAcronymValid()); } else { return p1.getGlobalUnitType().getId().compareTo(p2.getGlobalUnitType().getId()); } }); // Get the list of liaison institutions Flagships and PMU. liaisonInstitutions = loggedCrp.getLiaisonInstitutions().stream() .filter(c -> c.getCrpProgram() != null && c.isActive() && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) .collect(Collectors.toList()); liaisonInstitutions.sort(Comparator.comparing(LiaisonInstitution::getAcronym)); liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream() .filter(c -> c.getCrpProgram() == null && c.isActive() && c.getAcronym().equals("PMU")) .collect(Collectors.toList())); powbSynthesisBD = powbSynthesisManager.getPowbSynthesisById(powbSynthesisID); // Base Permission String params[] = { loggedCrp.getAcronym(), powbSynthesis.getId() + "" }; this.setBasePermission(this.getText(Permission.POWB_SYNTHESIS_COLLABORATION_BASE_PERMISSION, params)); if (this.isHttpPost()) { if (powbSynthesis.getPowbCollaborationGlobalUnitsList() != null) { powbSynthesis.getPowbCollaborationGlobalUnitsList().clear(); } if (powbSynthesis.getRegions() != null) { powbSynthesis.getRegions().clear(); } } }