Example usage for java.util SortedSet add

List of usage examples for java.util SortedSet add

Introduction

In this page you can find the example usage for java.util SortedSet add.

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:io.fabric8.maven.plugin.HelmIndexMojo.java

protected void generateHTML(File outputHtmlFile, Map<String, ChartInfo> charts) throws MojoExecutionException {
    Map<String, SortedSet<ChartInfo>> chartMap = new TreeMap<>();
    for (ChartInfo chartInfo : charts.values()) {
        String key = chartInfo.getName();
        SortedSet<ChartInfo> set = chartMap.get(key);
        if (set == null) {
            set = new TreeSet(createChartComparator());
            chartMap.put(key, set);/* ww  w.  j av a  2 s  .  c o m*/
        }
        set.add(chartInfo);
    }
    try (PrintWriter writer = new PrintWriter(new FileWriter(outputHtmlFile))) {
        writer.println("<html>");
        writer.println("<head>");
        writer.println(getHtmlFileContentOrDefault(headHtmlFile, "<link href='style.css' rel=stylesheet>\n"
                + "<link href='custom.css' rel=stylesheet>\n" + "<title>" + helmTitle + "</title>\n"));
        writer.println("</head>");
        writer.println("<body>");

        writer.println(getHtmlFileContentOrDefault(introductionHtmlFile, "<h1>" + helmTitle + "</h1>"));

        writer.println("<table class='table table-striped table-hover'>");
        writer.println("  <hhead>");
        writer.println("    <tr>");
        writer.println("      <th>Chart</th>");
        writer.println("      <th>Versions</th>");
        writer.println("    </tr>");
        writer.println("  </hhead>");
        writer.println("  <tbody>");
        for (Map.Entry<String, SortedSet<ChartInfo>> entry : chartMap.entrySet()) {
            String key = entry.getKey();
            SortedSet<ChartInfo> set = entry.getValue();
            if (!set.isEmpty()) {
                ChartInfo first = set.first();
                HelmMojo.Chart firstChartfile = first.getChartfile();
                if (firstChartfile == null) {
                    continue;
                }
                String chartDescription = getDescription(firstChartfile);
                writer.println("    <tr>");
                writer.println("      <td title='" + chartDescription + "'>");
                String iconHtml = "";
                String iconUrl = findIconURL(first, set);
                if (Strings.isNotBlank(iconUrl)) {
                    iconHtml = "<img class='logo' src='" + iconUrl + "'>";
                }
                writer.println("        " + iconHtml + "<span class='chart-name'>" + key + "</span>");
                writer.println("      </td>");
                writer.println("      <td class='versions'>");
                for (ChartInfo chartInfo : set) {
                    HelmMojo.Chart chartfile = chartInfo.getChartfile();
                    if (chartfile == null) {
                        continue;
                    }
                    String description = getDescription(chartfile);
                    String version = chartfile.getVersion();
                    String href = chartInfo.getUrl();
                    writer.println(
                            "        <a href='" + href + "' title='" + description + "'>" + version + "</a>");
                }
                writer.println("      </td>");
                writer.println("    </tr>");
            }
        }
        writer.println("  </tbody>");
        writer.println("  </table>");
        writer.println(getHtmlFileContentOrDefault(footerHtmlFile, ""));
        writer.println("</body>");
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to write to " + outputHtmlFile + ". " + e, e);
    }
}

From source file:com.jd.survey.web.settings.QuestionController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid Question question, BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("update(): handles PUT");
    try {//w  ww. j a  va  2s  . com
        //User user = userService.user_findByLogin(principal.getName());
        String login = principal.getName();
        User user = userService.user_findByLogin(login);

        //SurveyDefinitionPage surveyDefinitionPage = surveySettingsService.surveyDefinitionPage_findById(surveyDefinitionPageId); surveySettingsService.question_findById(question.getId()).getPage().getSurveyDefinition().getId()
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(question.getPage().getSurveyDefinition().getId(),
                user)
                && !securityService.userBelongsToDepartment(
                        question.getPage().getSurveyDefinition().getDepartment().getId(), user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }
        if (proceed != null) {
            if (bindingResult.hasErrors()) {
                populateEditForm(uiModel, question, user);
                log.info("-------------------------------------------"
                        + bindingResult.getFieldErrors().toString());
                return "settings/questions/update";
            }
            if (!surveySettingsService.question_ValidateDateRange(question)) {
                populateEditForm(uiModel, question, user);
                bindingResult.rejectValue("dateMinimum", "date_format_validation_range");
                return "settings/questions/update";
            }
            if (!surveySettingsService.question_ValidateMinMaxDoubleValues(question)) {
                populateEditForm(uiModel, question, user);
                bindingResult.rejectValue("decimalMinimum", "field_min_invalid");
                return "settings/questions/update";
            }
            if (!surveySettingsService.question_ValidateMinMaxValues(question)) {
                populateEditForm(uiModel, question, user);
                bindingResult.rejectValue("integerMinimum", "field_min_invalid");
                return "settings/questions/update";
            }
            if (question.getSuportsOptions()) {
                //If user wants to modify and existent question without options to Rating type, then use the default values
                int NumberOfQuestionOptions = 0;
                Set<QuestionOption> qOpts = surveySettingsService
                        .questionOption_findByQuestionId(question.getId());
                for (QuestionOption q : qOpts) {
                    NumberOfQuestionOptions++;
                }
                if ((question.getType().toString() == "SMILEY_FACES_RATING"
                        || question.getType().toString() == "STAR_RATING") && NumberOfQuestionOptions != 5) {
                    log.info(
                            "Removing Question Options since the amount of Questions Options for Rating Type cannot be longer than 5 Qoptions");
                    surveySettingsService.questionOption_removeQuestionOptionsByQuestionId(question.getId());
                    SortedSet<QuestionOption> options = new TreeSet<QuestionOption>();
                    options.add(new QuestionOption(question, (short) 1, "1", messageSource
                            .getMessage(EXTREMELY_UNSATISFIED_LABEL, null, LocaleContextHolder.getLocale())));
                    options.add(new QuestionOption(question, (short) 2, "2", messageSource
                            .getMessage(UNSATISFIED_LABEL, null, LocaleContextHolder.getLocale())));
                    options.add(new QuestionOption(question, (short) 3, "3",
                            messageSource.getMessage(NEUTRAL_LABEL, null, LocaleContextHolder.getLocale())));
                    options.add(new QuestionOption(question, (short) 4, "4",
                            messageSource.getMessage(SATISFIED_LABEL, null, LocaleContextHolder.getLocale())));
                    options.add(new QuestionOption(question, (short) 5, "5", messageSource
                            .getMessage(EXTREMELY_SATISFIED_LABEL, null, LocaleContextHolder.getLocale())));
                    //Adding default values to Rating Type Question
                    log.info("Adding default values to Rating Type Question");
                    question = surveySettingsService.question_merge(question, options);
                    uiModel.asMap().clear();
                    return "settings/questions/saved";
                } else {
                    Policy questionTextPolicy = Policy
                            .getInstance(this.getClass().getResource(POLICY_FILE_LOCATION));
                    AntiSamy emailAs = new AntiSamy();
                    CleanResults crQuestionText = emailAs.scan(question.getQuestionText(), questionTextPolicy);
                    question.setQuestionText(crQuestionText.getCleanHTML());

                    Policy questionTipPolicy = Policy
                            .getInstance(this.getClass().getResource(POLICY_FILE_LOCATION));
                    AntiSamy completedSurveyAs = new AntiSamy();
                    CleanResults crQuestionTip = completedSurveyAs.scan(question.getTip(), questionTipPolicy);
                    question.setTip(crQuestionTip.getCleanHTML());

                    question = surveySettingsService.question_merge(question);
                    uiModel.asMap().clear();
                    return "settings/questions/saved";
                }
            }

            question = surveySettingsService.question_merge(question);
            uiModel.asMap().clear();
            return "settings/questions/saved";

        } else {
            return "redirect:/settings/surveyDefinitions/" + encodeUrlPathSegment(
                    question.getPage().getSurveyDefinition().getId().toString(), httpServletRequest);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.zigabyte.stock.stratplot.StockMarketHistoryViewer.java

/** Refresh the stock list after the stock market history is changed. **/
private void refreshList() {
    if (this.stockMarketHistory != null && this.stockMarketHistory.size() > 0) {
        SortedSet<StockHistory> sortedStockHistories = new TreeSet<StockHistory>(TO_STRING_COMPARATOR);
        int index = 0;
        Calendar calendar = new GregorianCalendar();
        for (StockHistory stockHistory : stockMarketHistory) {
            if (stockHistory.size() > 0) {
                calendar.clear();/*from w w w. ja va2  s  .c o m*/
                calendar.setTime(stockHistory.get(0).getDate());
                sortedStockHistories.add(stockHistory);
            }
        }
        stockList.setListData(sortedStockHistories.toArray());
    } else {
        stockList.setListData(new Object[] {});
    }
}

From source file:nz.co.senanque.workflowui.LaunchWizard.java

private SortedSet<ProcessDefinitionHolder> getVisibleProcesses() {
    SortedSet<ProcessDefinitionHolder> ret = new TreeSet<>(new ProcessDefinitionHolderComparator());
    for (ProcessDefinition processDefinition : m_queueProcessManager.getVisibleProcesses(m_permissionManager)) {
        if (StringUtils.hasText(processDefinition.getLaunchForm())) {
            ret.add(new ProcessDefinitionHolder(processDefinition));
        }// w  w w . j  a v  a 2  s . c o  m
    }
    return ret;
}

From source file:org.geoserver.geofence.gui.server.service.impl.WorkspacesManagerServiceImpl.java

public PagingLoadResult<Layer> getLayers(int offset, int limit, String baseURL, GSInstanceModel gsInstance,
        String workspace, String service) throws ApplicationException {

    List<Layer> layersListDTO = new ArrayList<Layer>();
    layersListDTO.add(new Layer("*"));

    if ((baseURL != null) && !baseURL.equals("*") && !baseURL.contains("?") && (workspace != null)
            && (workspace.length() > 0)) {
        try {//from  www  . j  a  v a  2  s  .c  o  m
            GeoServerRESTReader gsreader = new GeoServerRESTReader(baseURL, gsInstance.getUsername(),
                    gsInstance.getPassword());

            if (workspace.equals("*") && workspaceConfigOpts.isShowDefaultGroups() && service.equals("WMS")) {
                RESTAbstractList<NameLinkElem> layerGroups = gsreader.getLayerGroups();

                if ((layerGroups != null)) {
                    for (NameLinkElem lg : layerGroups) {
                        //                            RESTLayerGroup group = gsreader.getLayerGroup(lg.getName());
                        //                            if (group != null)
                        //                            {
                        //                                layersListDTO.add(new Layer(group.getName()));
                        //                            }
                        layersListDTO.add(new Layer(lg.getName()));
                    }
                }
            } else {
                SortedSet<String> sortedLayerNames = new TreeSet<String>();
                RESTAbstractList<NameLinkElem> layers = gsreader.getLayers();

                if (workspace.equals("*")) { // load all layers
                    if (layers != null)
                        for (NameLinkElem layerLink : layers) {
                            sortedLayerNames.add(layerLink.getName());
                        }
                } else {
                    if ((layers != null) && !layers.isEmpty()) {

                        for (NameLinkElem layerNL : layers) {
                            // next block is really too slow
                            RESTLayer layer = gsreader.getLayer(layerNL.getName());
                            if (layer.getResourceUrl().contains("workspaces/" + workspace + "/")) {
                                sortedLayerNames.add(layerNL.getName());
                                //layersListDTO.add(new Layer(layerNL.getName()));
                            }
                        }
                    }
                }
                // return the sorted layers list
                for (String layerName : sortedLayerNames) {
                    layersListDTO.add(new Layer(layerName));
                }
            }
        } catch (MalformedURLException e) {
            logger.error(e.getLocalizedMessage(), e);
            throw new ApplicationException(e.getLocalizedMessage(), e);
        }
    }

    return new RpcPageLoadResult<Layer>(layersListDTO, 0, layersListDTO.size());
}

From source file:com.yahoo.pulsar.common.naming.NamespaceBundlesTest.java

@SuppressWarnings("unchecked")
@Test/*w w  w.j  av a  2 s  .  c  o m*/
public void testConstructor() throws Exception {
    try {
        new NamespaceBundles(null, (SortedSet<Long>) null, null);
        fail("Should fail w/ null pointer exception");
    } catch (NullPointerException npe) {
        // OK, expected
    }

    try {
        new NamespaceBundles(new NamespaceName("pulsar/use/ns2"), (SortedSet<Long>) null, null);
        fail("Should fail w/ null pointer exception");
    } catch (NullPointerException npe) {
        // OK, expected
    }

    try {
        new NamespaceBundles(new NamespaceName("pulsar.use.ns2"), (SortedSet<Long>) null, null);
        fail("Should fail w/ illegal argument exception");
    } catch (IllegalArgumentException iae) {
        // OK, expected
    }

    try {
        new NamespaceBundles(new NamespaceName("pulsar/use/ns2"), (SortedSet<Long>) null, factory);
        fail("Should fail w/ null pointer exception");
    } catch (NullPointerException npe) {
        // OK, expected
    }

    SortedSet<Long> partitions = Sets.newTreeSet();
    try {
        new NamespaceBundles(new NamespaceName("pulsar/use/ns2"), partitions, factory);
        fail("Should fail w/ illegal argument exception");
    } catch (IllegalArgumentException iae) {
        // OK, expected
    }

    partitions.add(0l);
    partitions.add(0x10000000l);
    partitions.add(0x40000000l);
    partitions.add(0xffffffffl);
    NamespaceBundles bundles = new NamespaceBundles(new NamespaceName("pulsar/use/ns2"), partitions, factory);
    Field partitionField = NamespaceBundles.class.getDeclaredField("partitions");
    Field nsField = NamespaceBundles.class.getDeclaredField("nsname");
    Field bundlesField = NamespaceBundles.class.getDeclaredField("bundles");
    partitionField.setAccessible(true);
    nsField.setAccessible(true);
    bundlesField.setAccessible(true);
    long[] partFld = (long[]) partitionField.get(bundles);
    // the same instance
    assertEquals(partitions.size(), partFld.length);
    NamespaceName nsFld = (NamespaceName) nsField.get(bundles);
    assertTrue(nsFld.toString().equals("pulsar/use/ns2"));
    ArrayList<NamespaceBundle> bundleList = (ArrayList<NamespaceBundle>) bundlesField.get(bundles);
    assertEquals(bundleList.size(), 3);
    assertEquals(bundleList.get(0),
            factory.getBundle(nsFld, Range.range(0l, BoundType.CLOSED, 0x10000000l, BoundType.OPEN)));
    assertEquals(bundleList.get(1),
            factory.getBundle(nsFld, Range.range(0x10000000l, BoundType.CLOSED, 0x40000000l, BoundType.OPEN)));
    assertEquals(bundleList.get(2), factory.getBundle(nsFld,
            Range.range(0x40000000l, BoundType.CLOSED, 0xffffffffl, BoundType.CLOSED)));
}

From source file:cross.datastructures.pipeline.ResultAwareCommandPipeline.java

/**
 * Used to check, whether any files have changed compared to the last
 * invocation./*from w  w w  .ja va2 s  .  c  o m*/
 *
 * @param inputFiles
 * @return
 */
protected String getRecursiveFileHash(Collection<File> inputFiles) {
    //list files below input and output
    SortedSet<File> files = new TreeSet<>();
    for (File file : inputFiles) {
        if (file.isDirectory()) {
            files.addAll(FileUtils.listFiles(file, new String[] { "*" }, true));
        } else {
            files.add(file);
        }
    }
    return digest(files);
}

From source file:BoundedPriorityQueue.java

/**
 * Return the set of elements in this queue strictly less than the
 * specified element according to the comparator for this queue.
 *
 * <p>In violation of the {@link SortedSet} interface
 * specification, the result of this method is <b>not</b> a view
 * onto this queue, but rather a static snapshot of the queue.
 *
 * @param toElement Exclusive upper bound on returned elements.
 * @return The set of elements less than the upper bound.
 * @throws ClassCastException If the upper bound is not compatible with
 * this queue's comparator.//  w w w .jav a  2 s . c  om
 * @throws NullPointerException If the upper bound is null.
 */
public SortedSet<E> headSet(E toElement) {
    SortedSet<E> result = new TreeSet<E>();
    for (E e : this) {
        if (mComparator.compare(e, toElement) < 0)
            result.add(e);
        else
            break;
    }
    return result;
}

From source file:net.solarnetwork.central.dras.dao.ibatis.DrasIbatisGenericDaoSupport.java

/**
 * Get a set of members for a given class and parent ID.
 * //from w  ww .j a v  a  2  s.  c o m
 * <p>Use this method to get the complete set of members. The query
 * used will be based on {@link #getRelationQueryForParent()}
 * with {@link #getMemberDomainKey(Class)} appended.</p>
 * 
 * <p>This method will pass the following query properties:</p>
 * 
 * <dl>
 *   <dt>{@link #ID_PROPERTY}</dt>
 *   <dd>The {@code parentId} value.</dd>
 *   
 *   <dt>{@link #DATE_PROPERTY}</dt>
 *   <dd>The {@code effectiveDate} value.</dd>
 * </dl>
 * 
 * @param parentId the parent ID
 * @param memberClass the member class type
 * @param effectiveDate the effective date
 * @return the found members, never <em>null</em>
 * @see #storeMemberSet(Long, Class, Set, Long)
 */
protected <E> SortedSet<E> getRelatedSortedSet(Long parentId, Class<? extends E> memberClass,
        DateTime effectiveDate) {
    final String memberDomain = getMemberDomainKey(memberClass);
    final String query = getRelationQueryForParent() + memberDomain;
    Map<String, Object> sqlProps = new HashMap<String, Object>(2);
    sqlProps.put(ID_PROPERTY, parentId);
    if (effectiveDate != null) {
        sqlProps.put(DATE_PROPERTY, effectiveDate);
    }
    final SortedSet<E> members = new TreeSet<E>();
    getSqlMapClientTemplate().queryWithRowHandler(query, sqlProps, new RowHandler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleRow(Object valueObject) {
            members.add((E) valueObject);
        }
    });
    return members;
}

From source file:org.terasoluna.gfw.common.codelist.ExistInCodeListTest.java

@Test
public void test_invalidMultipleExistInCodeList() {
    {/*from  w w w.j a  v  a2  s  . co m*/
        Order order = new Order("1");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(2));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("2");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(1));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("4");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(1));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("5");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(2));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("7");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(2));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("8");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(1));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("9");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(1));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
    }
    {
        Order order = new Order("10");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(1));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("11");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(2));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        // out of range!
        Order order = new Order("18");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(2));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
}