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:com.streamsets.pipeline.stage.destination.cassandra.CassandraTarget.java

@Override
protected List<ConfigIssue> init() {
    List<ConfigIssue> issues = super.init();
    errorRecordHandler = new DefaultErrorRecordHandler(getContext());

    Target.Context context = getContext();
    if (addresses.isEmpty()) {
        issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_00));
    }//from w  w w.j  av  a2s.co  m

    for (String address : addresses) {
        if (address.isEmpty()) {
            issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_01));
        }
    }

    contactPoints = new ArrayList<>(addresses.size());
    for (String address : addresses) {
        if (null == address) {
            LOG.warn("A null value was passed in as a contact point.");
            // This isn't valid but InetAddress won't complain so we skip this entry.
            continue;
        }

        try {
            contactPoints.add(InetAddress.getByName(address));
        } catch (UnknownHostException e) {
            issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_04,
                    address));
        }
    }

    if (contactPoints.size() < 1) {
        issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_00));
    }

    if (!qualifiedTableName.contains(".")) {
        issues.add(
                context.createConfigIssue(Groups.CASSANDRA.name(), "qualifiedTableName", Errors.CASSANDRA_02));
    } else {
        if (checkCassandraReachable(issues)) {
            List<String> invalidColumns = checkColumnMappings();
            if (invalidColumns.size() != 0) {
                issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "columnNames",
                        Errors.CASSANDRA_08, Joiner.on(", ").join(invalidColumns)));
            }
        }
    }

    if (issues.isEmpty()) {
        cluster = Cluster.builder().addContactPoints(contactPoints).withCompression(compression).withPort(port)
                // If authentication is disabled on the C* cluster, this method has no effect.
                .withCredentials(username, password).build();

        try {
            session = cluster.connect();

            statementCache = CacheBuilder.newBuilder()
                    // No expiration as prepared statements are good for the entire session.
                    .build(new CacheLoader<SortedSet<String>, PreparedStatement>() {
                        @Override
                        public PreparedStatement load(SortedSet<String> columns) {
                            // The INSERT query we're going to perform (parameterized).
                            SortedSet<String> statementColumns = new TreeSet<>();
                            for (String fieldPath : columnMappings.keySet()) {
                                final String fieldName = fieldPath.replaceAll("/", "");
                                if (columns.contains(fieldName)) {
                                    statementColumns.add(fieldName);
                                }
                            }
                            final String query = String.format("INSERT INTO %s (%s) VALUES (%s);",
                                    qualifiedTableName, Joiner.on(", ").join(statementColumns),
                                    Joiner.on(", ").join(Collections.nCopies(statementColumns.size(), "?")));
                            LOG.trace("Prepared Query: {}", query);
                            return session.prepare(query);
                        }
                    });
        } catch (NoHostAvailableException | AuthenticationException | IllegalStateException e) {
            issues.add(context.createConfigIssue(null, null, Errors.CASSANDRA_03, e.toString()));
        }
    }
    return issues;
}

From source file:io.fabric8.maven.plugin.mojo.internal.ManifestIndexMojo.java

protected void generateHTML(File outputHtmlFile, Map<String, ManifestInfo> manifests, boolean kubernetes,
        File introductionHtmlFile, File headHtmlFile, File footerHtmlFile) throws MojoExecutionException {
    Map<String, SortedSet<ManifestInfo>> manifestMap = new TreeMap<>();
    for (ManifestInfo manifestInfo : manifests.values()) {
        String key = manifestInfo.getName();
        SortedSet<ManifestInfo> set = manifestMap.get(key);
        if (set == null) {
            set = new TreeSet<>(createManifestComparator());
            manifestMap.put(key, set);//from   w w  w .  jav  a  2 s .c om
        }
        set.add(manifestInfo);
    }
    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>" + manifestTitle + "</title>\n"));
        writer.println("</head>");
        writer.println("<body>");

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

        writer.println("<table class='table table-striped table-hover'>");
        writer.println("  <hhead>");
        writer.println("    <tr>");
        writer.println("      <th>Manifest</th>");
        writer.println("      <th>Versions</th>");
        writer.println("    </tr>");
        writer.println("  </hhead>");
        writer.println("  <tbody>");
        for (Map.Entry<String, SortedSet<ManifestInfo>> entry : manifestMap.entrySet()) {
            String key = entry.getKey();
            SortedSet<ManifestInfo> set = entry.getValue();
            if (!set.isEmpty()) {
                ManifestInfo first = set.first();
                first.configure(this);
                if (!first.isValid()) {
                    continue;
                }

                String manifestDescription = getDescription(first);
                writer.println("    <tr>");
                writer.println("      <td title='" + manifestDescription + "'>");
                String iconHtml = "";
                String iconUrl = findIconURL(set);
                if (Strings.isNotBlank(iconUrl)) {
                    iconHtml = "<img class='logo' src='" + iconUrl + "'>";
                }
                writer.println("        " + iconHtml + "<span class='manifest-name'>" + key + "</span>");
                writer.println("      </td>");
                writer.println("      <td class='versions'>");
                int count = 0;
                for (ManifestInfo manifestInfo : set) {
                    if (maxVersionsPerApp > 0 && ++count > maxVersionsPerApp) {
                        break;
                    }
                    String description = getDescription(manifestInfo);
                    String version = manifestInfo.getVersion();
                    String href = kubernetes ? manifestInfo.getKubernetesUrl() : manifestInfo.getOpenShiftUrl();
                    String versionId = manifestInfo.getId();
                    String command = kubernetes ? "kubectl" : "oc";
                    writer.println(
                            "        <a class='btn btn-default' role='button' data-toggle='collapse' href='#"
                                    + versionId + "' aria-expanded='false' aria-controls='" + versionId
                                    + "' title='" + description + "'>\n" + version + "\n" + "</a>\n"
                                    + "<div class='collapse' id='" + versionId + "'>\n"
                                    + "  <div class='well'>\n" + "    <p>To install version <b>" + version
                                    + "</b> of <b>" + key + "</b> type the following command:</p>\n"
                                    + "    <code>" + command + " apply -f " + href + "</code>\n"
                                    + "    <div class='version-buttons'><a class='btn btn-primary' title='Download the YAML manifest for "
                                    + key + " version " + version + "' href='" + href
                                    + "'><i class='fa fa-download' aria-hidden='true'></i> Download Manifest</a> "
                                    + "<a class='btn btn-primary' target='gofabric8' title='Run this application via the go.fabric8.io website' href='https://go.fabric8.io/?manifest="
                                    + href
                                    + "'><i class='fa fa-external-link' aria-hidden='true'></i> Run via browser</a></div>\n"
                                    + "  </div>\n" + "</div>");
                }
                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.revetkn.ios.analyzer.ArtworkAnalyzer.java

protected SortedSet<File> extractImageFilesWithIncorrectDeviceSuffix(Iterable<File> imageFiles) {
    SortedSet<File> imageFilesWithIncorrectDeviceSuffix = new TreeSet<File>();

    for (File imageFile : imageFiles)
        if (imageFile.getName().contains("~iphone"))
            imageFilesWithIncorrectDeviceSuffix.add(imageFile);

    return imageFilesWithIncorrectDeviceSuffix;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.department.PublicDepartmentSiteDA.java

private void setupTeachersCategories(HttpServletRequest request, Department department) {

    SortedSet<ProfessionalCategory> categories = new TreeSet<ProfessionalCategory>();
    Map<String, SortedSet<Teacher>> teachers = new Hashtable<String, SortedSet<Teacher>>();

    for (Teacher teacher : department.getAllCurrentTeachers()) {
        ProfessionalCategory professionalCategory = teacher.getCategory();
        if (professionalCategory != null) {
            String category = professionalCategory.getExternalId();
            categories.add(professionalCategory);
            addListTeacher(teachers, category, teacher);
        }/*from  ww  w  .j av  a2s  .c o m*/
    }

    request.setAttribute("categories", categories);
    request.setAttribute("teachers", teachers);
}

From source file:org.jenkins.tools.test.PluginCompatTester.java

private SortedSet<MavenCoordinates> coreVersionFromWAR(UpdateSite.Data data) {
    SortedSet<MavenCoordinates> result = new TreeSet<MavenCoordinates>();
    result.add(new MavenCoordinates(PluginCompatTesterConfig.DEFAULT_PARENT_GROUP,
            PluginCompatTesterConfig.DEFAULT_PARENT_ARTIFACT, data.core.version));
    return result;
}

From source file:net.sourceforge.fenixedu.domain.Shift.java

public SortedSet<ShiftType> getSortedTypes() {
    SortedSet<ShiftType> result = new TreeSet<ShiftType>();
    for (CourseLoad courseLoad : getCourseLoadsSet()) {
        result.add(courseLoad.getType());
    }/*from ww  w .j  a  v  a  2 s. c o  m*/
    return result;
}

From source file:de.fhg.igd.mapviewer.view.ExtendedMapKit.java

/**
 * Constructor// w w  w  . ja  va2 s. com
 * 
 * @param view the map view
 */
public ExtendedMapKit(final AbstractMapView view) {
    super(getCache());

    this.view = view;

    // tile cache
    ITileCacheService cacheService = PlatformUI.getWorkbench().getService(ITileCacheService.class);
    cacheService.addListener(new ExclusiveExtensionListener<TileCache, ITileCacheFactory>() {

        @Override
        public void currentObjectChanged(TileCache current, ITileCacheFactory definition) {
            setTileCache(current);
        }

    });

    // map painters
    IMapPainterService mapPainters = PlatformUI.getWorkbench().getService(IMapPainterService.class);
    List<MapPainter> painterList = new ArrayList<MapPainter>();
    for (MapPainter mapPainter : mapPainters.getActiveObjects()) {
        painterList.add(mapPainter);
    }
    setCustomPainters(painterList);

    mapPainters.addListener(new SelectiveExtensionListener<MapPainter, MapPainterFactory>() {

        @Override
        public void deactivated(MapPainter object, MapPainterFactory definition) {
            removeCustomPainter(object);
        }

        @Override
        public void activated(MapPainter object, MapPainterFactory definition) {
            addCustomPainter(object);
        }
    });

    // tile overlays
    ITileOverlayService tileOverlays = PlatformUI.getWorkbench().getService(ITileOverlayService.class);
    SortedSet<TileOverlayPainter> mainOverlays = new TreeSet<TileOverlayPainter>();
    SortedSet<TileOverlayPainter> miniOverlays = new TreeSet<TileOverlayPainter>();
    for (TileOverlayPainter tileOverlay : tileOverlays.getActiveObjects()) {
        if (tileOverlay instanceof MapKitTileOverlayPainter) {
            ((MapKitTileOverlayPainter) tileOverlay).setMapKit(this);
        }

        mainOverlays.add(tileOverlay);

        if (tileOverlays.getDefinition(tileOverlay).showInMiniMap()) {
            miniOverlays.add(tileOverlay);
        }
    }
    getMainMap().setTileOverlays(mainOverlays);
    getMiniMap().setTileOverlays(miniOverlays);

    tileOverlays.addListener(new SelectiveExtensionListener<TileOverlayPainter, TileOverlayFactory>() {

        @Override
        public void deactivated(TileOverlayPainter object, TileOverlayFactory definition) {
            getMainMap().removeTileOverlay(object);
            if (definition.showInMiniMap()) {
                getMiniMap().removeTileOverlay(object);
            }
        }

        @Override
        public void activated(TileOverlayPainter object, TileOverlayFactory definition) {
            if (object instanceof MapKitTileOverlayPainter) {
                ((MapKitTileOverlayPainter) object).setMapKit(ExtendedMapKit.this);
            }

            getMainMap().addTileOverlay(object);
            if (definition.showInMiniMap()) {
                getMiniMap().addTileOverlay(object);
            }
        }
    });

    // map server
    IMapServerService mapServers = PlatformUI.getWorkbench().getService(IMapServerService.class);
    setServer(mapServers.getCurrent(), true);

    mapServers.addListener(new ExclusiveExtensionListener<MapServer, MapServerFactory>() {

        @Override
        public void currentObjectChanged(MapServer current, MapServerFactory definition) {
            setServer(current, false);
        }
    });
}

From source file:de.skubware.opentraining.activity.settings.sync.WgerJSONParser.java

/**
 * Constructor. Will start download immediately.
 * /*  ww w.  j  a v a2  s  .  com*/
 * @param exerciseJSONString
 *            The exercises as JSON-String
 * @param languageJSONString
 *            The languages as JSON-String
 * @param muscleJSONString
 *            The muscles as JSON-String
 * @param dataProvider
 * @throws JSONException
 */
public WgerJSONParser(String exerciseJSONString, String languageJSONString, String muscleJSONString,
        String equipmentJSONString, String licenseJSONString, IDataProvider dataProvider) throws JSONException {
    mDataProvider = dataProvider;

    // parse languages
    SparseArray<Locale> localeSparseArray = parseLanguages(languageJSONString);
    // parse muscles
    SparseArray<Muscle> muscleSparseArray = parseMuscles(muscleJSONString);
    // parse licenses
    SparseArray<LicenseType> licenseSparseArray = parseLicenses(licenseJSONString);

    // parse equipment (not required until REST-API supports this)
    // SparseArray<SportsEquipment> equipmentSparseArray = parseEquipment(equipmentJSONString);

    JSONObject mainObject = new JSONObject(exerciseJSONString);
    Log.d(TAG, mainObject.toString());
    JSONArray exerciseArray = mainObject.getJSONArray("objects");

    // parse each exercise of the JSON Array
    for (int i = 0; i < exerciseArray.length(); i++) {

        JSONObject jsonExercise = exerciseArray.getJSONObject(i);
        // get name and check if exercise already exists
        String name = jsonExercise.getString("name");
        if (dataProvider.exerciseExists(name))
            continue;

        ExerciseType.Builder builder = new ExerciseType.Builder(name, ExerciseSource.SYNCED);

        // category (unused)
        // String category = jsonExercise.getString("category");

        // comments (unused)
        // JSONArray commentArray = jsonExercise.getJSONArray("comments");
        // for (int k = 0; k < commentArray.length(); k++) {
        //   String comment = commentArray.getString(k);
        //}

        // description
        String description = jsonExercise.getString("description");
        builder.description(description);

        // id (unused)
        //String id = jsonExercise.getString("id");

        // language
        // the json-language String might look like this:
        // '/api/v1/language/1/'
        // only the number at the end is required
        String language = jsonExercise.getString("language");
        int languageNumber = getLastNumberOfJson(language);

        Map<Locale, String> translationMap = new HashMap<Locale, String>();
        translationMap.put(localeSparseArray.get(languageNumber), name);
        builder.translationMap(translationMap);

        // resource_uri (unused)
        //String resource_uri = jsonExercise.getString("resource_uri");

        // muscles
        SortedSet<Muscle> muscleSet = new TreeSet<Muscle>();
        JSONArray muscleArray = jsonExercise.getJSONArray("muscles");
        for (int l = 0; l < muscleArray.length(); l++) {
            String muscleString = muscleArray.getString(l);
            Muscle muscle = muscleSparseArray.get(getLastNumberOfJson(muscleString));
            muscleSet.add(muscle);
        }
        builder.activatedMuscles(muscleSet);

        // licenses
        // the json-language String might look like this:
        // '/api/v1/license/1/'
        // only the number at the end is required

        if (jsonExercise.has("license")) {
            int licenseNumber = getLastNumberOfJson(jsonExercise.getString("license"));
            LicenseType licenseType = licenseSparseArray.get(licenseNumber);
            String license_author = jsonExercise.getString("license_author");
            Log.v(TAG, "license=" + licenseType + " license_author=" + license_author);
        }

        // equipment
        // not yet supported by REST-API
        /*SortedSet<SportsEquipment> equipmentSet = new TreeSet<SportsEquipment>();
        JSONArray equipmentArray = jsonExercise.getJSONArray("equipment");
        for (int l = 0; l < equipmentArray.length(); l++) {
           String equipmentString = equipmentArray.getString(l);
           SportsEquipment equipment = equipmentSparseArray.get(getLastNumberOfJson(equipmentString));
           equipmentSet.add(equipment);
        }*/

        builder.activatedMuscles(muscleSet);
        // images
        List<File> imageList = new ArrayList<File>();
        JSONArray imageArray = jsonExercise.getJSONArray("images");
        for (int l = 0; l < imageArray.length(); l++) {
            String imageString = imageArray.getString(l);
            imageList.add(new File(imageString));
        }
        builder.imagePath(imageList);

        mNewExerciseList.add(builder.build());
        mNewExerciseBuilderList.add(builder);
    }

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.scientificalArea.PublicScientificAreaSiteDA.java

public ActionForward viewTeachers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/*from   ww  w.  j  a  v a  2s.  c o m*/
    ScientificAreaUnit scientificArea = (ScientificAreaUnit) getUnit(request);

    YearMonthDay today = new YearMonthDay();
    YearMonthDay tomorrow = today.plusDays(1);

    SortedSet<ProfessionalCategory> categories = new TreeSet<ProfessionalCategory>();
    Map<String, SortedSet<Person>> teachers = new Hashtable<String, SortedSet<Person>>();

    for (Teacher teacher : scientificArea.getDepartmentUnit().getDepartment().getAllTeachers(today, tomorrow)) {
        if (teacher.getCurrentSectionOrScientificArea() == scientificArea) {
            ProfessionalCategory professionalCategory = teacher.getCategory();
            if (professionalCategory != null) {
                String category = professionalCategory.getExternalId();
                categories.add(professionalCategory);
                addListTeacher(teachers, category, teacher);
            }
        }
    }

    request.setAttribute("categories", categories);
    request.setAttribute("teachers", teachers);

    return mapping.findForward("view-teachers");
}

From source file:com.spotify.heroic.filter.AndFilter.java

static Filter optimize(final SortedSet<Filter> filters) {
    final SortedSet<Filter> result = new TreeSet<>();

    for (final Filter f : filters) {
        if (f instanceof NotFilter) {
            // Optimize away expressions which are always false.
            // Example: foo = bar and !(foo = bar)

            if (filters.contains(((NotFilter) f).getFilter())) {
                return FalseFilter.get();
            }//  w  ww  .j a va  2s.  c o  m
        } else if (f instanceof StartsWithFilter) {
            // Optimize away prefixes which encompass each other.
            // Example: foo ^ hello and foo ^ helloworld -> foo ^ helloworld

            if (FilterUtils.containsPrefixedWith(filters, (StartsWithFilter) f,
                    (inner, outer) -> FilterUtils.prefixedWith(inner.getValue(), outer.getValue()))) {
                continue;
            }
        } else if (f instanceof MatchTagFilter) {
            // Optimize matchTag expressions which are always false.
            // Example: foo = bar and foo = baz

            if (FilterUtils.containsConflictingMatchTag(filters, (MatchTagFilter) f)) {
                return FalseFilter.get();
            }
        } else if (f instanceof MatchKeyFilter) {
            // Optimize matchTag expressions which are always false.
            // Example: $key = bar and $key = baz

            if (FilterUtils.containsConflictingMatchKey(filters, (MatchKeyFilter) f)) {
                return FalseFilter.get();
            }
        }

        result.add(f);
    }

    if (result.isEmpty()) {
        return FalseFilter.get();
    }

    if (result.size() == 1) {
        return result.iterator().next();
    }

    return new AndFilter(ImmutableList.copyOf(result));
}