Example usage for java.lang Integer compareTo

List of usage examples for java.lang Integer compareTo

Introduction

In this page you can find the example usage for java.lang Integer compareTo.

Prototype

public int compareTo(Integer anotherInteger) 

Source Link

Document

Compares two Integer objects numerically.

Usage

From source file:org.ambraproject.admin.service.impl.AdminServiceImpl.java

@Override
@Transactional(readOnly = true)/*from  w  ww.java2s .c o m*/
@SuppressWarnings("unchecked")
public List<TOCArticleGroup> getArticleGroupList(final Issue issue) {
    //if the issue doesn't have any dois, return an empty list of groups
    if (issue.getArticleDois() == null || issue.getArticleDois().isEmpty()) {
        return Collections.emptyList();
    }

    //Create a comparator to sort articles in groups depending on if the issue has manual ordering enabled
    Comparator<ArticleInfo> comparator;
    if (issue.isRespectOrder()) {
        comparator = new Comparator<ArticleInfo>() {
            @Override
            public int compare(ArticleInfo left, ArticleInfo right) {
                Integer leftIndex = issue.getArticleDois().indexOf(left.getDoi());
                Integer rightIndex = issue.getArticleDois().indexOf(right.getDoi());
                return leftIndex.compareTo(rightIndex);
            }
        };
    } else {
        comparator = new Comparator<ArticleInfo>() {
            @Override
            public int compare(ArticleInfo left, ArticleInfo right) {
                if (left.getDate().after(right.getDate())) {
                    return -1;
                }
                if (left.getDate().before(right.getDate())) {
                    return 1;
                }
                return left.getDoi().compareTo(right.getDoi());
            }
        };
    }

    //keep track of dois in a separate list so we can remove them as we find articles and then keep track of the orphans at the end
    List<String> dois = new ArrayList<String>(issue.getArticleDois());

    log.debug("Loading up article groups for issue '{}'", issue.getIssueUri());
    List<TOCArticleGroup> groups = new ArrayList<TOCArticleGroup>(
            ArticleType.getOrderedListForDisplay().size());

    List<Object[]> rows = hibernateTemplate.findByNamedParam(
            "select a.doi, a.title, a.date, t from Article a inner join a.types t where a.doi in :dois",
            new String[] { "dois" }, new Object[] { issue.getArticleDois() });

    //results will be row of [doi, title, date, type] with an entry for each type of each article
    //i.e. we'll see duplicate results for articles

    for (ArticleType type : ArticleType.getOrderedListForDisplay()) {
        TOCArticleGroup group = new TOCArticleGroup(type);
        //using an explicit iterator so we can remove rows as we find matches
        Iterator<Object[]> iterator = rows.iterator();
        while (iterator.hasNext()) {
            Object[] row = iterator.next();
            //check if this row is of the correct type, and that we haven't added the article
            if (type.getUri().toString().equals(row[3]) && dois.contains(row[0])) {
                ArticleInfo articleInfo = new ArticleInfo();
                articleInfo.setDoi((String) row[0]);
                articleInfo.setTitle((String) row[1]);
                articleInfo.setDate((Date) row[2]);
                group.addArticle(articleInfo);

                //remove the row so we don't have to check it again later
                iterator.remove();
                //remove the doi so we can keep track of orphans
                dois.remove(articleInfo.getDoi());
            }
        }
        Collections.sort(group.getArticles(), comparator);
        //only add a group if there are articles for it
        if (group.getCount() > 0) {
            groups.add(group);
            log.debug("Found {} articles of type '{}' for issue '{}",
                    new Object[] { group.getCount(), type.getHeading(), issue.getIssueUri() });
        }
    }

    //create a group for orphaned articles
    TOCArticleGroup orphans = new TOCArticleGroup(null);
    orphans.setHeading("Orphaned Article");
    orphans.setPluralHeading("Orphaned Articles");

    //anything left in the doi list is an orphan
    for (String doi : dois) {
        ArticleInfo article = new ArticleInfo();
        article.setDoi(doi);
        article.setDate(Calendar.getInstance().getTime());
        orphans.addArticle(article);
    }
    Collections.sort(orphans.getArticles(), comparator);

    groups.add(orphans);
    return groups;
}

From source file:nl.b3p.viewer.util.SelectedContentCache.java

public JSONObject createSelectedContent(Application app, boolean validXmlTags,
        boolean includeAppLayerAttributes, boolean includeRelations, EntityManager em) throws JSONException {
    Level root = app.getRoot();// w  w w . ja va2 s  .  com
    JSONObject o = new JSONObject();
    if (root != null) {
        o.put("rootLevel", root.getId().toString());

        Application.TreeCache treeCache = app.loadTreeCache(em);
        treeCache.initializeLevels("left join fetch l.documents", em);
        treeCache.initializeApplicationLayers("left join fetch al.details", em);
        Authorizations.ApplicationCache appCache = Authorizations.getApplicationCache(app, em);

        JSONObject levels = new JSONObject();
        o.put("levels", levels);
        JSONObject appLayers = new JSONObject();
        o.put("appLayers", appLayers);
        JSONArray selectedContent = new JSONArray();
        o.put("selectedContent", selectedContent);

        List selectedObjects = new ArrayList();
        walkAppTreeForJSON(levels, appLayers, selectedObjects, root, false, validXmlTags,
                includeAppLayerAttributes, includeRelations, app, treeCache, appCache, em, false);

        Collections.sort(selectedObjects, new Comparator() {
            @Override
            public int compare(Object lhs, Object rhs) {
                Integer lhsIndex, rhsIndex;
                if (lhs instanceof StartLevel) {
                    lhsIndex = ((StartLevel) lhs).getSelectedIndex();
                } else {
                    lhsIndex = ((StartLayer) lhs).getSelectedIndex();
                }
                if (rhs instanceof StartLevel) {
                    rhsIndex = ((StartLevel) rhs).getSelectedIndex();
                } else {
                    rhsIndex = ((StartLayer) rhs).getSelectedIndex();
                }
                return lhsIndex.compareTo(rhsIndex);
            }
        });
        for (Object obj : selectedObjects) {
            JSONObject j = new JSONObject();
            if (obj instanceof StartLevel) {
                j.put("type", "level");
                j.put("id", ((StartLevel) obj).getLevel().getId().toString());
            } else {
                j.put("type", "appLayer");
                j.put("id", ((StartLayer) obj).getApplicationLayer().getId().toString());
            }
            selectedContent.put(j);
        }

        Map<GeoService, Set<String>> usedLayersByService = new HashMap<GeoService, Set<String>>();
        visitLevelForUsedServicesLayers(root, usedLayersByService, app, treeCache);

        if (!usedLayersByService.isEmpty()) {
            JSONObject services = new JSONObject();
            o.put("services", services);
            for (Map.Entry<GeoService, Set<String>> entry : usedLayersByService.entrySet()) {
                GeoService gs = entry.getKey();
                Set<String> usedLayers = entry.getValue();
                String serviceId = gs.getId().toString();
                if (validXmlTags) {
                    serviceId = "service_" + serviceId;
                }
                services.put(serviceId, gs.toJSONObject(false, usedLayers, validXmlTags, true, em));
            }
        }
    }
    return o;
}

From source file:com.redhat.rhn.manager.rhnpackage.PackageManager.java

/**
 * Helper method to compare two epoch strings according to the algorithm contained
 * in: modules/rhn/RHN/DB/Package.pm --> sub vercmp
 * @param epoch1 Epoch 1//from ww  w  .j a v  a 2s.com
 * @param epoch2 Epoch 2
 * @return Returns 1 if epoch1 > epoch2, -1 if epoch1 < epoch2,
 * and 0 if epoch1 == epoch2
 */
private static int compareEpochs(String epoch1, String epoch2) {
    //Trim the epoch strings to null
    epoch1 = StringUtils.trimToNull(epoch1);
    epoch2 = StringUtils.trimToNull(epoch2);

    //Check the epochs
    Integer e1 = null;
    Integer e2 = null;
    if (epoch1 != null && StringUtils.isNumeric(epoch1)) {
        e1 = new Integer(epoch1);
    }
    if (epoch2 != null && StringUtils.isNumeric(epoch2)) {
        e2 = new Integer(epoch2);
    }
    //handle null cases
    if (e1 != null && e2 == null) {
        return 1;
    }
    if (e1 == null && e2 != null) {
        return -1;
    }
    if (e1 == null && e2 == null) {
        return 0;
    }

    // If we made it here, it is safe to do an Integer comparison between the two
    return e1.compareTo(e2);
}

From source file:org.xwiki.contrib.githubstats.internal.DefaultGitHubStatsManager.java

@Override
public Map<String, Map<String, Object>> aggregateCommitsPerAuthor(UserCommitActivity[] userCommitActivity,
        Map<Author, Map<String, Object>> authors) {
    if (authors == null) {
        return Collections.emptyMap();
    }//from   ww  w.  ja v  a 2 s  . co m

    Map<String, Map<String, Object>> result = new HashMap<>();

    Map<String, Set<Author>> authorsByName = extractAuthorsByName(authors);
    for (UserCommitActivity userCommit : userCommitActivity) {
        Author author = new Author(userCommit.getName(), userCommit.getEmail());
        Map<String, Object> authorData = authors.get(author);
        if (authorData == null) {
            // If we don't know this author, we skip it
            continue;
        }
        String authorName = (String) authorData.get("name");
        if (StringUtils.isEmpty(authorName)) {
            authorName = userCommit.getName();
        }
        // Create a result entry if none exist for the name already
        Map<String, Object> authorResult = result.get(authorName);
        if (authorResult == null) {
            authorResult = new HashMap<>();
            result.put(authorName, authorResult);
            // Add all the authors with the same name as duplicates
            Set<Author> contributingAuthors = authorsByName.get(authorName);
            authorResult.put("authors", contributingAuthors);
            // Save the email too
            authorResult.put("email", author.getEmail());
        } else {
            // Add this author as an aggregated author
            Set<Author> contributingAuthors = (Set<Author>) authorResult.get("authors");
            contributingAuthors.add(author);
        }
        // If the avatar or company fields are not set already, set them!
        String avatar = (String) authorResult.get("avatar");
        if (StringUtils.isEmpty(avatar)) {
            authorResult.put("avatar", authorData.get("avatar"));
        }
        String company = (String) authorResult.get("company");
        if (StringUtils.isEmpty(company)) {
            authorResult.put("company", authorData.get("company"));
        }
        // Overwrite committer info if true
        if ((Boolean) authorData.get("committer")) {
            authorResult.put("committer", true);
        } else {
            authorResult.put("committer", false);
        }
        // Increase counter and store aggregated result
        Integer counter = (Integer) authorResult.get("count");
        if (counter == null) {
            counter = 0;
        }
        counter += userCommit.getCount();
        authorResult.put("count", counter);
    }

    // Also add all authors with same email addresses as aggregated authors.
    Map<String, Set<Author>> authorsByEmail = extractAuthorsByEmail(authors);
    for (Map.Entry<String, Map<String, Object>> entry : result.entrySet()) {
        Map<String, Object> resultData = entry.getValue();
        String email = (String) resultData.get("email");
        Set<Author> authorByEmail = authorsByEmail.get(email);
        Set<Author> contributingAuthors = (Set<Author>) resultData.get("authors");
        contributingAuthors.addAll(authorByEmail);
    }

    // Sort Map
    List<Map.Entry<String, Map<String, Object>>> list = new ArrayList<>(result.entrySet());
    Collections.sort(list, (e1, e2) -> {
        // Highest count first!
        Integer count1 = (Integer) e1.getValue().get("count");
        Integer count2 = (Integer) e2.getValue().get("count");
        return count2.compareTo(count1);
    });
    Map<String, Map<String, Object>> sortedResult = new LinkedHashMap<>();
    for (Map.Entry<String, Map<String, Object>> entry : list) {
        sortedResult.put(entry.getKey(), entry.getValue());
    }

    return sortedResult;
}

From source file:org.akaza.openclinica.dao.submit.EventCRFDAO.java

public Map<Integer, SortedSet<EventCRFBean>> buildEventCrfListByStudyEvent(Integer studySubjectId) {
    this.setTypesExpected(); // <== Must be called first

    Map<Integer, SortedSet<EventCRFBean>> result = new HashMap<Integer, SortedSet<EventCRFBean>>();

    HashMap<Integer, Object> param = new HashMap<Integer, Object>();
    int i = 1;/*from  w w w  .  ja  va  2  s  . c o  m*/
    param.put(i++, studySubjectId);

    List selectResult = select(digester.getQuery("buildEventCrfListByStudyEvent"), param);

    Iterator it = selectResult.iterator();

    while (it.hasNext()) {
        EventCRFBean bean = (EventCRFBean) this.getEntityFromHashMap((HashMap) it.next());

        Integer studyEventId = bean.getStudyEventId();
        if (!result.containsKey(studyEventId)) {
            result.put(studyEventId, new TreeSet<EventCRFBean>(new Comparator<EventCRFBean>() {
                public int compare(EventCRFBean o1, EventCRFBean o2) {
                    Integer id1 = o1.getId();
                    Integer id2 = o2.getId();
                    return id1.compareTo(id2);
                }
            }));
        }
        result.get(studyEventId).add(bean);
    }

    return result;
}

From source file:eu.comsode.unifiedviews.plugins.transformer.generatedtorelational.GeneratedToRelational.java

@Override
protected void innerExecute() throws DPUException {
    Connection conn = null;/*from w  w w .  j  av  a 2s . c  o  m*/
    try {
        createOutputTable();
        //Retrieves data from CKAN resource
        fillInputTableFromCKAN();
        LOG.debug("{} records retrieved from CKAN.", inputFromCkan.size());
        Collections.sort(inputFromCkan, new Comparator<GenTableRow>() {
            @Override
            public int compare(GenTableRow o1, GenTableRow o2) {
                return Long.compare(o1.id, o2.id);
            }
        });
        this.output.addExistingDatabaseTable(GENERATED_TABLE_NAME.toUpperCase(),
                GENERATED_TABLE_NAME.toUpperCase());
        //If there are no data on input, create first row, else update table in CKAN
        if (inputFromCkan.size() == 0) {
            LOG.debug("No input table found!");
            String dateToInsert = fmt.format(new Date());
            String insertIntoQuery = String.format("INSERT INTO %s VALUES (0, '%s');", GENERATED_TABLE_NAME,
                    dateToInsert);
            LOG.debug("Inserting first data to Output table with query: " + insertIntoQuery);
            DatabaseHelper.executeUpdate(insertIntoQuery, output);
        } else {
            Integer todayInt = Integer.decode(intFmt.format(new Date()));
            PreparedStatement psInsert = null;
            PreparedStatement ps = null;
            int counter = 0;
            conn = output.getDatabaseConnection();
            //Iterate throgh data retrieved from CKAN
            for (GenTableRow currentRow : inputFromCkan) {
                counter++;
                Integer lastRunInt = Integer
                        .decode(currentRow.data.substring(0, 10).replaceAll("-", "").trim());
                LOG.debug(String.format("Last run date is: %d, today is: %d", lastRunInt, todayInt));
                //If the record is not deleted and it is from previous day, delete it
                if (currentRow.deletedTimestamp != null) {
                    //Create new record in database
                    if (counter == inputFromCkan.size() && lastRunInt.compareTo(todayInt) < 0) {
                        LOG.debug("Starting to insert record.");
                        String dateToInsert = fmt.format(new Date());
                        String insertIntoQuery = String.format("INSERT INTO %s VALUES (%d,'%s');",
                                GENERATED_TABLE_NAME, currentRow.id + 1, dateToInsert);
                        LOG.debug("Inserting data to Output table with query: " + insertIntoQuery);
                        DatabaseHelper.executeUpdate(insertIntoQuery, output);
                    }
                    LOG.debug("Commiting changes in output table.");
                    conn.commit();
                    continue;
                } else if (lastRunInt.compareTo(todayInt) < 0) {
                    if (counter == inputFromCkan.size() && lastRunInt.compareTo(todayInt) < 0) {
                        LOG.debug("Starting to insert record.");
                        String dateToInsert = fmt.format(new Date());
                        String insertIntoQuery = String.format("INSERT INTO %s VALUES (%d,'%s');",
                                GENERATED_TABLE_NAME, currentRow.id + 1, dateToInsert);
                        LOG.debug("Inserting data to Output table with query: " + insertIntoQuery);
                        DatabaseHelper.executeUpdate(insertIntoQuery, output);
                    }
                    LOG.debug("Commiting changes in output table.");
                    conn.commit();
                    continue;
                }
                String insertRecQuery = insertRecordForPrepStmt(GENERATED_TABLE_NAME, currentRow.id,
                        currentRow.data);
                LOG.debug("Executing query: {}", insertRecQuery);
                psInsert = conn.prepareStatement(insertRecQuery);
                psInsert.execute();
                conn.commit();
                //If record is created today, update it
                if (lastRunInt.compareTo(todayInt) == 0 && currentRow.deletedTimestamp == null) {
                    LOG.debug("Starting to update records.");
                    String queryModify = updateModifyRecordForPrepStmt(GENERATED_TABLE_NAME.toUpperCase(),
                            "data", fmt.format(new Date()));
                    ps = conn.prepareStatement(queryModify);
                    ps.setLong(1, currentRow.id);
                    LOG.debug("Executing query: {} for ID: {}", queryModify, currentRow.id.toString());
                    ps.execute();
                }
                LOG.debug("Commiting changes in output table.");
                conn.commit();
            }
        }
        this.faultTolerance.execute(new FaultTolerance.Action() {

            @Override
            public void action() throws Exception {
                eu.unifiedviews.helpers.dataunit.resource.Resource resource = ResourceHelpers
                        .getResource(GeneratedToRelational.this.output, GENERATED_TABLE_NAME);
                Date now = new Date();
                resource.setCreated(now);
                resource.setLast_modified(now);
                ResourceHelpers.setResource(GeneratedToRelational.this.output, GENERATED_TABLE_NAME, resource);
            }
        });

    } catch (DataUnitException | SQLException ex) {
        ContextUtils.sendError(this.ctx, "errors.dpu.failed", ex, "errors.dpu.failed");
        return;
    } finally {
        DatabaseHelper.tryCloseConnection(conn);
    }

}

From source file:org.kuali.kra.protocol.personnel.ProtocolPersonnelServiceImplBase.java

@Override
public boolean isValidStudentFacultyMatch(List<ProtocolPersonBase> protocolPersons) {
    boolean validInvestigator = true;
    HashMap<Integer, Integer> investigatorAffiliation = new HashMap<Integer, Integer>();
    for (ProtocolPersonBase protocolPerson : protocolPersons) {
        if (isAffiliationStudentInvestigatorOrFacultySupervisor(protocolPerson)) {
            updateAffiliationCount(protocolPerson, investigatorAffiliation);
        }// ww  w .j  av  a 2s .  c om
    }
    Integer studentAffiliationCount = investigatorAffiliation.get(getStudentAffiliationType()) == null ? 0
            : investigatorAffiliation.get(getStudentAffiliationType());
    Integer facultySupervisorAffiliationCount = investigatorAffiliation
            .get(getFacultySupervisorAffiliationType()) == null ? 0
                    : investigatorAffiliation.get(getFacultySupervisorAffiliationType());
    if (studentAffiliationCount > 0
            && studentAffiliationCount.compareTo(facultySupervisorAffiliationCount) != 0) {
        validInvestigator = false;
    }
    return validInvestigator;
}

From source file:org.paxle.filter.robots.impl.RobotsTxtManager.java

void init(Map<String, Object> props) {
    // configure caching manager
    this.manager = CacheManager.getInstance();

    /* =================================================================================
     * init a new cache/*from w w w . java 2s . c  o m*/
     * ================================================================================= */
    Integer maxCacheSize = (Integer) props.get(PROP_MAX_CACHE_SIZE);
    if (maxCacheSize == null)
        maxCacheSize = Integer.valueOf(1000);
    this.cache = new Cache(CACHE_NAME, maxCacheSize.intValue(), false, false, 60 * 60, 30 * 60);
    this.manager.addCache(this.cache);

    /* =================================================================================
     * init threadpool
     * ================================================================================= */
    Integer maxIdle = (Integer) props.get(PROP_WORKER_MAX_IDLE);
    if (maxIdle == null)
        maxIdle = Integer.valueOf(20);

    Integer maxAlive = (Integer) props.get(PROP_WORKER_MAX_ALIVE);
    if (maxAlive == null)
        maxAlive = Integer.valueOf(20);
    if (maxAlive.compareTo(maxIdle) < 0)
        maxAlive = maxIdle;

    this.execService = new ThreadPoolExecutor(maxIdle.intValue(), maxAlive.intValue(), 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

    /* =================================================================================
     * init http-client
     * ================================================================================= */
    this.connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = this.connectionManager.getParams();

    final Integer connectionTimeout = (Integer) props.get(PROP_CONNECTION_TIMEOUT);
    if (connectionTimeout != null)
        params.setConnectionTimeout(connectionTimeout.intValue());
    final Integer socketTimeout = (Integer) props.get(PROP_SOCKET_TIMEOUT);
    if (socketTimeout != null)
        params.setSoTimeout(socketTimeout.intValue());
    final Integer maxConnections = (Integer) props.get(PROP_MAXCONNECTIONS_TOTAL);
    if (maxConnections != null)
        params.setMaxTotalConnections(maxConnections.intValue());

    this.httpClient = new HttpClient(this.connectionManager);

    /* =================================================================================
     * proxy configuration
     * ================================================================================= */
    final Boolean useProxyVal = (Boolean) props.get(PROP_PROXY_USE);
    final boolean useProxy = (useProxyVal == null) ? false : useProxyVal.booleanValue();
    final String host = (String) props.get(PROP_PROXY_HOST);
    final Integer portVal = (Integer) props.get(PROP_PROXY_PORT);

    if (useProxy && host != null && host.length() > 0 && portVal != null) {
        final int port = portVal.intValue();
        this.logger.info(String.format("Proxy is enabled: %s:%d", host, Integer.valueOf(port)));
        final ProxyHost proxyHost = new ProxyHost(host, port);
        this.httpClient.getHostConfiguration().setProxyHost(proxyHost);

        final String user = (String) props.get(PROP_PROXY_HOST);
        final String pwd = (String) props.get(PROP_PROXY_PASSWORD);

        if (user != null && user.length() > 0 && pwd != null && pwd.length() > 0)
            this.httpClient.getState().setProxyCredentials(new AuthScope(host, port),
                    new UsernamePasswordCredentials(user, pwd));
    } else {
        this.logger.info("Proxy is disabled");
        this.httpClient.getHostConfiguration().setProxyHost(null);
        this.httpClient.getState().clearCredentials();
    }

    /* =================================================================================
     * the user-agent name that should be used
     * ================================================================================= */
    final String userAgent = (String) props.get(PROP_USER_AGENT);
    if (userAgent != null) {
        final StringBuffer buf = new StringBuffer();
        Pattern pattern = Pattern.compile("\\$\\{[^\\}]*}");
        Matcher matcher = pattern.matcher(userAgent);

        // replacing property placeholders with system-properties
        while (matcher.find()) {
            String placeHolder = matcher.group();
            String propName = placeHolder.substring(2, placeHolder.length() - 1);
            String propValue = System.getProperty(propName);
            if (propValue != null)
                matcher.appendReplacement(buf, propValue);
        }
        matcher.appendTail(buf);

        this.userAgent = buf.toString();
    } else {
        // Fallback
        this.userAgent = "PaxleFramework";
    }

    this.logger
            .info(String.format("Robots.txt manager initialized. Using '%s' rule-store with %d stored entries.",
                    loader.getClass().getSimpleName(), Integer.valueOf(loader.size())));
}

From source file:org.nuclos.client.wizard.steps.NuclosEntityNameStep.java

@Override
public void applyState() throws InvalidStateException {
    if (this.model.getUserRights().size() < 1) {
        loadUserRights(null);//from  w ww. j  av  a  2  s . com
    }

    Object obj = cmbEntity.getSelectedItem();
    if (obj instanceof EntityWrapper) {
        try {
            EntityMetaDataVO vo = ((EntityWrapper) obj).getWrappedEntity();
            NuclosEntityNameStep.this.model.resetModel();
            if (!vo.isVirtual()) {
                NuclosEntityNameStep.this.model.setHasRows(hasEntityRows(vo));
            } else {
                NuclosEntityNameStep.this.model.setHasRows(true);
            }
            NuclosEntityNameStep.this.model.setEditMode(true);
            NuclosEntityNameStep.this.model.setEntityName(vo.getEntity());
            NuclosEntityNameStep.this.model.setLabelSingular(
                    SpringLocaleDelegate.getInstance().getResource(vo.getLocaleResourceIdForLabel(), ""));
            NuclosEntityNameStep.this.model.setEditable(vo.isEditable());
            NuclosEntityNameStep.this.model.setSearchable(vo.isSearchable());
            NuclosEntityNameStep.this.model.setLogbook(vo.isLogBookTracking());
            NuclosEntityNameStep.this.model.setMenuPath(
                    SpringLocaleDelegate.getInstance().getResource(vo.getLocaleResourceIdForMenuPath(), ""));
            NuclosEntityNameStep.this.model.setCachable(vo.isCacheable());
            NuclosEntityNameStep.this.model.setImExport(vo.isImportExport());
            NuclosEntityNameStep.this.model.setShowRelation(vo.isTreeRelation());
            NuclosEntityNameStep.this.model.setShowGroups(vo.isTreeGroup());
            NuclosEntityNameStep.this.model.setStateModel(vo.isStateModel());
            NuclosEntityNameStep.this.model.setTableOrViewName(vo.getDbEntity());
            String sNodeLabel = vo.getLocaleResourceIdForTreeView() == null ? ""
                    : SpringLocaleDelegate.getInstance()
                            .getTextForStaticLabel(vo.getLocaleResourceIdForTreeView());
            NuclosEntityNameStep.this.model.setNodeLabel(
                    sNodeLabel.startsWith("[Missing resource id=null, locale") ? null : sNodeLabel);
            String sNodeTooltip = vo.getLocaleResourceIdForTreeViewDescription() == null ? ""
                    : SpringLocaleDelegate.getInstance()
                            .getTextForStaticLabel(vo.getLocaleResourceIdForTreeViewDescription());
            NuclosEntityNameStep.this.model.setNodeTooltip(
                    sNodeTooltip.startsWith("[Missing resource id=null, locale") ? null : sNodeTooltip);
            NuclosEntityNameStep.this.model.setMultiEditEquation(vo.getFieldsForEquality());
            NuclosEntityNameStep.this.model.setLabelSingularResource(vo.getLocaleResourceIdForLabel());
            NuclosEntityNameStep.this.model.setMenuPathResource(vo.getLocaleResourceIdForMenuPath());
            NuclosEntityNameStep.this.model.setNodeLabelResource(vo.getLocaleResourceIdForTreeView());
            NuclosEntityNameStep.this.model
                    .setNodeTooltipResource(vo.getLocaleResourceIdForTreeViewDescription());
            NuclosEntityNameStep.this.model.setDocumentPath(vo.getDocumentPath());
            NuclosEntityNameStep.this.model.setReportFilename(vo.getReportFilename());
            NuclosEntityNameStep.this.model.setVirtualentity(vo.getVirtualentity());
            NuclosEntityNameStep.this.model.setIdFactory(vo.getIdFactory());
            NuclosEntityNameStep.this.model.setRowColorScript(vo.getRowColorScript());

            if (vo.getResourceId() != null) {
                NuclosEntityNameStep.this.model.setResourceName(
                        ResourceCache.getInstance().getResourceById(vo.getResourceId()).getName());
            }

            NuclosEntityNameStep.this.model.setSystemIdPrefix(vo.getSystemIdPrefix());

            NuclosEntityNameStep.this.model.setAccelerator(vo.getAccelerator());
            NuclosEntityNameStep.this.model.setModifier(vo.getAcceleratorModifier());

            NuclosEntityNameStep.this.model.setResourceId(vo.getResourceId());
            NuclosEntityNameStep.this.model.setNuclosResourceName(vo.getNuclosResource());

            loadUserRights(vo);
            loadTreeView();
            if (model.isStateModel()) {
                loadProcesses(vo.getId());
            }
            loadEntityMenus(vo.getId());

            EntityAttributeTableModel attributeModel = new EntityAttributeTableModel();
            Collection<EntityFieldMetaDataVO> lstFields = MetaDataClientProvider.getInstance()
                    .getAllEntityFieldsByEntity(vo.getEntity()).values();
            for (EntityFieldMetaDataVO fieldVO : CollectionUtils.sorted(lstFields,
                    new Comparator<EntityFieldMetaDataVO>() {
                        @Override
                        public int compare(EntityFieldMetaDataVO o1, EntityFieldMetaDataVO o2) {
                            Integer order1 = (o1.getOrder() == null) ? 0 : o1.getOrder();
                            Integer order2 = (o2.getOrder() == null) ? 0 : o2.getOrder();
                            return order1.compareTo(order2);
                        }
                    })) {
                if (fieldVO.getEntityId() == -100)
                    continue;
                Attribute attr = new Attribute();

                attr = wrapEntityMetaFieldVO(fieldVO);

                attributeModel.addAttribute(attr);
            }
            NuclosEntityNameStep.this.model.setAttributeModel(attributeModel);
        } catch (CommonFinderException e1) {
            Errors.getInstance().showExceptionDialog(NuclosEntityNameStep.this, e1);
        } catch (CommonPermissionException e1) {
            Errors.getInstance().showExceptionDialog(NuclosEntityNameStep.this, e1);
        }
    }

    model.getParentFrame().setTitle(SpringLocaleDelegate.getInstance().getMessage("wizard.step.entityname.5",
            "Nucleus Entit\u00e4tenwizard") + " " + model.getEntityName());
    super.applyState();
}

From source file:org.jwebsocket.util.Tools.java

/**
 * Compare 2 'Major.Minor.Fix' codified versions. Where Major, Minor, Fix values require to be
 * non-negative integer values./* w w  w .j av a  2  s.c  om*/
 *
 * @param aVersion1
 * @param aVersion2
 * @return Return 1 if 'version1', 0 if equals and -1 if lower.
 */
public static Integer compareVersions(String aVersion1, String aVersion2) {
    Assert.isTrue(null != aVersion1 && !aVersion1.isEmpty(),
            "The argument 'version1' cannot be null or empty!");
    Assert.isTrue(null != aVersion2 && !aVersion2.isEmpty(),
            "The argument 'version2' cannot be null or empty!");

    aVersion1 = aVersion1.split(" ")[0];
    aVersion2 = aVersion2.split(" ")[0];
    String[] lVNumbers1 = StringUtils.split(aVersion1, ".");
    String[] lVNumbers2 = StringUtils.split(aVersion2, ".");

    Assert.isTrue(lVNumbers1.length >= 3, "The argument 'version1' has"
            + " invalid jWebSocket version codification! " + "Expecting: 'Major.Minor.Fix'");
    Assert.isTrue(lVNumbers2.length >= 3, "The argument 'version2' has "
            + "invalid jWebSocket version codification! " + "Expecting: 'Major.Minor.Fix'");

    String lErrorMsg = "The argument 'version1' has invalid value. " + "Expecting non-negative integer values!";
    Integer lMayor1 = Integer.parseInt(lVNumbers1[0]);
    Assert.isTrue(lMayor1 >= 0, lErrorMsg);
    Integer lMinor1 = Integer.parseInt(lVNumbers1[1]);
    Assert.isTrue(lMinor1 >= 0, lErrorMsg);
    Integer lFix1 = Integer.parseInt(lVNumbers1[2]);
    Assert.isTrue(lFix1 >= 0, lErrorMsg);

    lErrorMsg = "The argument 'version2' has invalid value. " + "Expecting non-negative integer values!";
    Integer lMayor2 = Integer.parseInt(lVNumbers2[0]);
    Assert.isTrue(lMayor2 >= 0, lErrorMsg);
    Integer lMinor2 = Integer.parseInt(lVNumbers2[1]);
    Assert.isTrue(lMinor2 >= 0, lErrorMsg);
    Integer lFix2 = Integer.parseInt(lVNumbers2[2]);
    Assert.isTrue(lFix2 >= 0, lErrorMsg);

    int lCMayor = lMayor1.compareTo(lMayor2);
    int lCMinor = lMinor1.compareTo(lMinor2);
    int lCFix = lFix1.compareTo(lFix2);

    if (lCMayor != 0) {
        return lCMayor;
    }
    if (lCMinor != 0) {
        return lCMinor;
    }

    return lCFix;
}