List of usage examples for java.util Comparator comparing
public static <T, U extends Comparable<? super U>> Comparator<T> comparing( Function<? super T, ? extends U> keyExtractor)
From source file:com.diversityarrays.kdxplore.KDXploreFrame.java
private void initialiseKdxApps() throws IOException { String[] classNames = KdxploreConfig.getInstance().getMainPluginClassNames(); if (classNames != null && classNames.length > 0) { List<String> classNamesToLoad = new ArrayList<>(); Collections.addAll(classNamesToLoad, classNames); if (!classNamesToLoad.contains(OFFLINE_DATA_APP_SERVICE_CLASS_NAME)) { classNamesToLoad.add(0, OFFLINE_DATA_APP_SERVICE_CLASS_NAME); classNames = classNamesToLoad.toArray(new String[classNamesToLoad.size()]); }//from w w w .j a v a 2s . co m } Map<KdxApp, Component> componentByApp = collectKdxApps(classNames); appByComponent.clear(); for (KdxApp app : componentByApp.keySet()) { Component comp = componentByApp.get(app); if (comp != null) { appByComponent.put(comp, app); } } allKdxApps.clear(); allKdxApps.addAll(componentByApp.keySet()); // Initialise the apps in initialisation order. allKdxApps.sort(Comparator.comparing(KdxApp::getInitialisationOrder)); // And while we're initialising them we collect // those that can perform a databaseBackup (i.e. have a BackupProvider). backupProviders.clear(); List<KdxApp> wantedAppsWithUi = new ArrayList<>(); for (KdxApp app : allKdxApps) { BackupProvider bp = app.getBackupProvider(); if (bp != null) { backupProviders.add(bp); } /** * See {@link com.diversityarrays.kdxplore.prefs.KdxplorePreferences#SHOW_ALL_APPS} */ if (appIsWanted(app)) { try { app.initialiseAppBeforeUpdateCheck(appInitContext); } catch (Exception e) { String msg = Msg.MSG_KDXAPP_INIT_PROBLEM(app.getAppName()); Shared.Log.w(TAG, msg, e); messagesPanel.println(msg); messagesPanel.println(e.getMessage()); } } if (appIsWanted(app) && null != componentByApp.get(app)) { wantedAppsWithUi.add(app); } } // - - - - - - - - - - - - - - - - - - - - - // Display the apps in display order. wantedAppsWithUi.sort(Comparator.comparing(KdxApp::getDisplayOrder)); backupProviders.sort(Comparator.comparing(BackupProvider::getDisplayOrder)); switch (wantedAppsWithUi.size()) { case 0: JLabel label = new JLabel(Msg.MSG_NO_KDXPLORE_APPS_AVAILABLE()); label.setHorizontalAlignment(JLabel.CENTER); cardPanel.add(label, CARD_KDXAPPS); break; case 1: KdxApp kdxApp = wantedAppsWithUi.get(0); Component uiComponent = componentByApp.get(kdxApp); Component appComponent = makeComponentForTab(kdxApp, uiComponent); cardPanel.add(appComponent, CARD_KDXAPPS); getRootPane().setDefaultButton(kdxApp.getDefaultButton()); String msg = Msg.MSG_SHOWING_KDXAPP(kdxApp.getAppName()); messagesPanel.println(msg); System.err.println(msg + " uiClass=" //$NON-NLS-1$ + uiComponent.getClass().getName()); break; default: kdxAppTabs = new JTabbedPane(JTabbedPane.LEFT); cardPanel.add(kdxAppTabs, CARD_KDXAPPS); Bag<String> tabsSeen = new HashBag<>(); for (KdxApp app : wantedAppsWithUi) { Component ui = componentByApp.get(app); String tabName = app.getAppName(); DevelopmentState devState = app.getDevelopmentState(); switch (devState) { case ALPHA: tabName = tabName + " (\u03b1)"; // TODO move to UnicodeChars break; case BETA: tabName = tabName + " (\u03b2)"; // TODO move to UnicodeChars break; case PRODUCTION: break; default: tabName = tabName + " " + devState.name(); break; } tabsSeen.add(tabName); int count = tabsSeen.getCount(tabName); if (count > 1) { tabName = tabName + "_" + count; //$NON-NLS-1$ } Component tabComponent = makeComponentForTab(app, ui); kdxAppTabs.addTab(tabName, tabComponent); if (macapp == null) { int index = kdxAppTabs.indexOfTab(tabName); if (index >= 0) { JLabel tabLabel = new JLabel(tabName); tabLabel.setBorder(new EmptyBorder(2, 2, 2, 2)); tabLabel.setUI(new VerticalLabelUI(VerticalLabelUI.UPWARDS)); kdxAppTabs.setTabComponentAt(index, tabLabel); } } messagesPanel.println(Msg.MSG_SHOWING_KDXAPP(tabName)); } kdxAppTabs.addChangeListener(kdxAppTabsChangeListener); kdxAppTabs.setSelectedIndex(0); break; } }
From source file:sbu.srl.rolextract.SpockDataReader.java
public void generateSEMAFORFrameAnnotation(String frameElementsFileName, String rawSentencesFileName, int offset) throws FileNotFoundException { Set<String> roles = getRoleLabels(); // without NONE! PrintWriter writer = new PrintWriter(frameElementsFileName); PrintWriter sentWriter = new PrintWriter(rawSentencesFileName); int sentCounter = 0; //int offset = 2780; for (int i = 0; i < sentences.size(); i++) { Sentence currentSentence = sentences.get(i); if (currentSentence.isAnnotated()) { // Is there a positive role? int cntRole = 0; // Number of roles String frame = currentSentence.getProcessName(); String lexicalUnitFrames = currentSentence.getLexicalUnitFrame(); String lexicalUnitIndexRange = currentSentence.getLexicalUnitFrameRange(); String formLexicalUnitFrame = currentSentence.getLexicalUnitFormFrame(); StringBuilder roleSpanStrBuilder = new StringBuilder(); for (String role : roles) { ArrayList<ArgumentSpan> spans = currentSentence.getMultiClassAnnotatedArgumentSpan(role, -1); if (!spans.isEmpty()) { cntRole++;// w w w . j a v a 2 s . co m ArgumentSpan maxSpan = spans.stream() .max(Comparator.comparing(arg -> arg.getEndIdx() - arg.getStartIdx() + 1)).get(); if (maxSpan.getStartIdx() != maxSpan.getEndIdx()) { roleSpanStrBuilder.append(role).append("\t") .append((maxSpan.getStartIdx() - 1) + ":" + (maxSpan.getEndIdx() - 1)) .append("\t"); } else { roleSpanStrBuilder.append(role).append("\t").append((maxSpan.getStartIdx() - 1)) .append("\t"); } } // if there is more than one then select the longer one // group by start + end id // count number of roles // lexical unit == process name // sentence number // role span pairs } if (cntRole > 0) { StringBuilder frameElementsStrB = new StringBuilder(); frameElementsStrB.append(cntRole + +1).append("\t").append(frame).append("\t") .append(lexicalUnitFrames).append("\t").append(lexicalUnitIndexRange).append("\t") .append(formLexicalUnitFrame).append("\t").append((sentCounter + offset)).append("\t") .append(roleSpanStrBuilder.toString().trim()); writer.println(frameElementsStrB.toString()); sentWriter.println(currentSentence.getRawText().trim()); sentCounter++; } } } writer.close(); sentWriter.close(); }
From source file:org.cgiar.ccafs.marlo.action.annualReport.ExternalPartnershipsAction.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)); ReportSynthesis history = (ReportSynthesis) auditLogManager.getHistory(transaction); if (history != null) { reportSynthesis = history;/*from ww w .j a v a 2s. co m*/ synthesisID = reportSynthesis.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 { synthesisID = Long.parseLong( StringUtils.trim(this.getRequest().getParameter(APConstants.REPORT_SYNTHESIS_ID))); reportSynthesis = reportSynthesisManager.getReportSynthesisById(synthesisID); if (!reportSynthesis.getPhase().equals(phase)) { reportSynthesis = reportSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID); if (reportSynthesis == null) { reportSynthesis = this.createReportSynthesis(phase.getId(), liaisonInstitutionID); } synthesisID = reportSynthesis.getId(); } } catch (Exception e) { reportSynthesis = reportSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID); if (reportSynthesis == null) { reportSynthesis = this.createReportSynthesis(phase.getId(), liaisonInstitutionID); } synthesisID = reportSynthesis.getId(); } } if (reportSynthesis != null) { ReportSynthesis reportSynthesisDB = reportSynthesisManager .getReportSynthesisById(reportSynthesis.getId()); synthesisID = reportSynthesisDB.getId(); liaisonInstitutionID = reportSynthesisDB.getLiaisonInstitution().getId(); liaisonInstitution = liaisonInstitutionManager.getLiaisonInstitutionById(liaisonInstitutionID); // Fill Flagship Expected Studies if (this.isFlagship()) { this.partnerShipList(phase.getId(), liaisonInstitution); } 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); reader.close(); AutoSaveReader autoSaveReader = new AutoSaveReader(); reportSynthesis = (ReportSynthesis) autoSaveReader.readFromJson(jReader); synthesisID = reportSynthesis.getId(); this.setDraft(true); } else { this.setDraft(false); // Check if relation is null -create it if (reportSynthesis.getReportSynthesisExternalPartnership() == null) { ReportSynthesisExternalPartnership externalPartnership = new ReportSynthesisExternalPartnership(); // create one to one relation reportSynthesis.setReportSynthesisExternalPartnership(externalPartnership); externalPartnership.setReportSynthesis(reportSynthesis); // save the changes reportSynthesis = reportSynthesisManager.saveReportSynthesis(reportSynthesis); } if (this.isFlagship()) { // External PartnerShips reportSynthesis.getReportSynthesisExternalPartnership() .setPartnerPartnerships(new ArrayList<>()); if (reportSynthesis.getReportSynthesisExternalPartnership() .getReportSynthesisExternalPartnershipProjects() != null && !reportSynthesis.getReportSynthesisExternalPartnership() .getReportSynthesisExternalPartnershipProjects().isEmpty()) { for (ReportSynthesisExternalPartnershipProject externalPartnership : reportSynthesis .getReportSynthesisExternalPartnership() .getReportSynthesisExternalPartnershipProjects().stream() .filter(ro -> ro.isActive()).collect(Collectors.toList())) { reportSynthesis.getReportSynthesisExternalPartnership().getPartnerPartnerships() .add(externalPartnership.getProjectPartnerPartnership()); } } } } } // 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)); if (this.isPMU()) { // Table G flagshipPlannedList = reportSynthesisExternalPartnershipManager.getPlannedPartnershipList( liaisonInstitutions, phase.getId(), loggedCrp, this.liaisonInstitution); // Flagship External Partnership Synthesis Progress flagshipExternalPartnerships = reportSynthesisExternalPartnershipManager .getFlagshipCExternalPartnership(liaisonInstitutions, phase.getId()); } // ADD PMU as liasion Institution too liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream() .filter(c -> c.getCrpProgram() == null && c.isActive() && c.getAcronym().equals("PMU")) .collect(Collectors.toList())); // Base Permission String params[] = { loggedCrp.getAcronym(), reportSynthesis.getId() + "" }; this.setBasePermission( this.getText(Permission.REPORT_SYNTHESIS_EXTERNAL_PARTNERSHIP_BASE_PERMISSION, params)); if (this.isHttpPost()) { if (reportSynthesis.getReportSynthesisExternalPartnership().getPartnerPartnerships() != null) { reportSynthesis.getReportSynthesisExternalPartnership().getPartnerPartnerships().clear(); } } }
From source file:org.apache.nifi.authorization.FileUserGroupProvider.java
@Override public String getFingerprint() throws AuthorizationAccessException { final UserGroupHolder usersAndGroups = userGroupHolder.get(); final List<User> users = new ArrayList<>(usersAndGroups.getAllUsers()); Collections.sort(users, Comparator.comparing(User::getIdentifier)); final List<Group> groups = new ArrayList<>(usersAndGroups.getAllGroups()); Collections.sort(groups, Comparator.comparing(Group::getIdentifier)); XMLStreamWriter writer = null; final StringWriter out = new StringWriter(); try {/*from w w w. ja v a 2 s . c o m*/ writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out); writer.writeStartDocument(); writer.writeStartElement("tenants"); for (User user : users) { writeUser(writer, user); } for (Group group : groups) { writeGroup(writer, group); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); } catch (XMLStreamException e) { throw new AuthorizationAccessException("Unable to generate fingerprint", e); } finally { if (writer != null) { try { writer.close(); } catch (XMLStreamException e) { // nothing to do here } } } return out.toString(); }
From source file:org.egov.tl.entity.TradeLicense.java
public BigDecimal getLatestAmountPaid() { Optional<EgDemandDetails> demandDetails = this.getCurrentDemand().getEgDemandDetails().stream() .sorted(Comparator.comparing(EgDemandDetails::getInstallmentEndDate).reversed()) .filter(demandDetail -> demandDetail.getEgDemandReason().getEgDemandReasonMaster().getReasonMaster() .equals(LICENSE_FEE_TYPE)) .filter(demandDetail -> demandDetail.getAmount().subtract(demandDetail.getAmtCollected()) .doubleValue() <= 0) .findFirst();//www .j a v a 2 s. c o m return demandDetails.isPresent() ? demandDetails.get().getAmtCollected() : BigDecimal.ZERO; }
From source file:de.metas.ui.web.window.descriptor.factory.standard.LayoutFactory.java
/** * Build the layout for advanced view (for header documents). * * @task https://github.com/metasfresh/metasfresh-webui/issues/26 *//*from ww w .j a va 2s .co m*/ public DocumentLayoutDetailDescriptor.Builder layoutAdvancedView() { // NOTE, according to (FRESH-686 #26), we are putting all elements in one list, one after another, no sections, no columns etc final DocumentEntityDescriptor.Builder entityDescriptor = documentEntity(); logger.trace("Generating advanced view layout for {}", entityDescriptor); // If the detail is never displayed then don't add it to layout final ILogicExpression tabDisplayLogic = descriptorsFactory.getTabDisplayLogic(); if (tabDisplayLogic.isConstantFalse()) { logger.trace("Skip adding advanced view layout because it's never displayed: {}, tabDisplayLogic={}", entityDescriptor, tabDisplayLogic); return null; } final Stream<DocumentLayoutElementDescriptor.Builder> layoutElements = streamAD_UI_Elements() .filter(uiElement -> uiElement.isDisplayed()) .sorted(Comparator.comparing(I_AD_UI_Element::getSeqNo)) .map(uiElement -> layoutElement(uiElement).setNotGridElement()) .filter(uiElement -> uiElement != null); final DocumentLayoutDetailDescriptor.Builder advancedViewLayout = DocumentLayoutDetailDescriptor.builder() .setDetailId(entityDescriptor.getDetailId()).setCaption(entityDescriptor.getCaption()) .setDescription(entityDescriptor.getDescription()) .setEmptyResultText(HARDCODED_TAB_EMPTY_RESULT_TEXT) .setEmptyResultHint(HARDCODED_TAB_EMPTY_RESULT_HINT).addElements(layoutElements); return advancedViewLayout; }
From source file:org.apache.nifi.registry.service.extension.StandardExtensionService.java
@Override public SortedSet<ExtensionBundleVersionMetadata> getExtensionBundleVersions(final Set<String> bucketIdentifiers, final ExtensionBundleVersionFilterParams filterParams) { if (bucketIdentifiers == null) { throw new IllegalArgumentException("Bucket identifiers cannot be null"); }// ww w . j av a 2s. c o m final SortedSet<ExtensionBundleVersionMetadata> sortedVersions = new TreeSet<>( Comparator.comparing(ExtensionBundleVersionMetadata::getExtensionBundleId) .thenComparing(ExtensionBundleVersionMetadata::getVersion)); final List<ExtensionBundleVersionEntity> bundleVersionEntities = metadataService.getExtensionBundleVersions( bucketIdentifiers, filterParams == null ? ExtensionBundleVersionFilterParams.empty() : filterParams); if (bundleVersionEntities != null) { bundleVersionEntities.forEach(bv -> sortedVersions.add(DataModelMapper.map(bv))); } return sortedVersions; }
From source file:org.keycloak.models.jpa.JpaRealmProvider.java
@Override public List<GroupModel> searchForGroupByName(RealmModel realm, String search, Integer first, Integer max) { TypedQuery<String> query = em.createNamedQuery("getGroupIdsByNameContaining", String.class) .setParameter("realm", realm.getId()).setParameter("search", search); if (Objects.nonNull(first) && Objects.nonNull(max)) { query = query.setFirstResult(first).setMaxResults(max); }/* w w w . j a v a 2 s . c om*/ List<String> groups = query.getResultList(); if (Objects.isNull(groups)) return Collections.EMPTY_LIST; List<GroupModel> list = new ArrayList<>(); for (String id : groups) { GroupModel groupById = session.realms().getGroupById(id, realm); while (Objects.nonNull(groupById.getParentId())) { groupById = session.realms().getGroupById(groupById.getParentId(), realm); } if (!list.contains(groupById)) { list.add(groupById); } } list.sort(Comparator.comparing(GroupModel::getName)); return Collections.unmodifiableList(list); }
From source file:io.spring.initializr.generator.ProjectGenerator.java
private static List<Dependency> filterDependencies(List<Dependency> dependencies, String scope) { return dependencies.stream().filter(dep -> scope.equals(dep.getScope())) .sorted(Comparator.comparing(MetadataElement::getId)).collect(Collectors.toList()); }
From source file:de.metas.ui.web.window.descriptor.factory.standard.LayoutFactory.java
public final DocumentViewLayout layoutSideListView() { final DocumentViewLayout.Builder layoutBuilder = DocumentViewLayout.builder() .setAD_Window_ID(getAD_Window_ID()).setEmptyResultText(HARDCODED_TAB_EMPTY_RESULT_TEXT) .setEmptyResultHint(HARDCODED_TAB_EMPTY_RESULT_HINT); ///* w w w. j a v a2s .co m*/ // Create UI elements from AD_UI_Elements which were marked as DisplayedGrid streamAD_UI_Elements() // .peek((uiElement)->System.out.println("UI ELEMENT: "+uiElement + ", SIDE="+uiElement.isDisplayed_SideList())) .filter(uiElement -> uiElement.isDisplayed_SideList()) .sorted(Comparator.comparing(I_AD_UI_Element::getSeqNo_SideList)) .map(uiElement -> layoutElement(uiElement).setGridElement()).filter(uiElement -> uiElement != null) .forEach(layoutBuilder::addElement); // // Fallback: when no elements were found: creating the view using the single row layout if (!layoutBuilder.hasElements()) { logger.warn( "No side list layout was found for {}. Trying to create one based on single row layout elements", this); streamAD_UI_Elements() .filter(adUIElement -> adUIElement.isDisplayed() && !adUIElement.isAdvancedField()) .map(adUIElement -> layoutElement(adUIElement)).filter(uiElement -> uiElement != null) .peek(uiElement -> uiElement.setGridElement()).forEach(layoutBuilder::addElement); } // // Fallback: if (!layoutBuilder.hasElements()) { logger.warn("No side list layout found for {}. Continuing", this); } // // Make sure all added elements have the SideListField characteristic descriptorsFactory.addFieldsCharacteristic(layoutBuilder.getFieldNames(), Characteristic.SideListField); return layoutBuilder.build(); }