Example usage for java.util TreeSet add

List of usage examples for java.util TreeSet add

Introduction

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

Prototype

public boolean add(E e) 

Source Link

Document

Adds the specified element to this set if it is not already present.

Usage

From source file:com.webcohesion.enunciate.modules.docs.DocsModule.java

private TreeSet<Artifact> findDocumentationArtifacts() {
    HashSet<String> explicitArtifacts = new HashSet<String>();
    TreeSet<Artifact> artifacts = new TreeSet<Artifact>();
    for (ExplicitDownloadConfig download : getExplicitDownloads()) {
        if (download.getArtifact() != null) {
            explicitArtifacts.add(download.getArtifact());
        } else if (download.getFile() != null) {
            File downloadFile = resolveFile(download.getFile());

            debug("File %s to be added as an extra download.", downloadFile.getAbsolutePath());
            SpecifiedArtifact artifact = new SpecifiedArtifact(getName(), downloadFile.getName(), downloadFile);

            if (download.getName() != null) {
                artifact.setName(download.getName());
            }//from  w w w.ja  va  2 s .c  o  m

            if (download.getDescription() != null) {
                artifact.setDescription(download.getDescription());
            }

            artifact.setShowLink(!"false".equals(download.getShowLink()));

            artifacts.add(artifact);
        }
    }

    for (Artifact artifact : this.enunciate.getArtifacts()) {
        if (artifact.isPublic() || explicitArtifacts.contains(artifact.getId())) {
            artifacts.add(artifact);
            debug("Artifact %s to be added as an extra download.", artifact.getId());
            explicitArtifacts.remove(artifact.getId());
        }
    }

    if (explicitArtifacts.size() > 0) {
        for (String artifactId : explicitArtifacts) {
            warn("WARNING: Unknown artifact '%s'.  Will not be available for download.", artifactId);
        }
    }
    return artifacts;
}

From source file:edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalSubQuery.java

private void parsePanels(List<PanelType> grpList) throws I2B2Exception {
    TreeSet<TemporalPanel> panelSet = new TreeSet<TemporalPanel>();
    for (PanelType panelType : grpList) {
        TemporalPanel panelItem = new TemporalPanel(this, panelType);
        if (panelItem.isPanelInverted())
            invertedPanelCount++;/*from www.jav  a2s.c  om*/
        panelSet.add(panelItem);
    }

    panelList = new ArrayList<TemporalPanel>();
    panelList.addAll(panelSet);
}

From source file:net.spfbl.core.Core.java

public static TreeSet<String> getTreeSet(String text, String demiliter) {
    if (text == null) {
        return null;
    } else if (demiliter == null) {
        return null;
    } else {/*  w w  w  .j  a v  a 2 s  .c o  m*/
        TreeSet<String> resultSet = new TreeSet<String>();
        StringTokenizer tokenizer = new StringTokenizer(text, demiliter);
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            resultSet.add(token);
        }
        return resultSet;
    }
}

From source file:net.spfbl.core.Core.java

public static synchronized boolean sendMessage(Message message, int timeout) throws Exception {
    if (message == null) {
        return false;
    } else if (isDirectSMTP()) {
        Server.logInfo("sending e-mail message.");
        Server.logSendMTP("authenticate: false.");
        Server.logSendMTP("start TLS: true.");
        Properties props = System.getProperties();
        props.put("mail.smtp.auth", "false");
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.timeout", Integer.toString(timeout));
        props.put("mail.smtp.connectiontimeout", "3000");
        InternetAddress[] recipients = (InternetAddress[]) message.getAllRecipients();
        Exception lastException = null;
        for (InternetAddress recipient : recipients) {
            String domain = Domain.normalizeHostname(recipient.getAddress(), false);
            for (String mx : Reverse.getMXSet(domain)) {
                mx = mx.substring(1);/*from w ww .  java2  s .c  o  m*/
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", mx);
                props.put("mail.smtp.ssl.trust", mx);
                InternetAddress[] recipientAlone = new InternetAddress[1];
                recipientAlone[0] = (InternetAddress) recipient;
                Session session = Session.getDefaultInstance(props);
                SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
                try {
                    transport.setLocalHost(HOSTNAME);
                    Server.logSendMTP("connecting to " + mx + ":25.");
                    transport.connect(mx, 25, null, null);
                    Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipient + ".");
                    transport.sendMessage(message, recipientAlone);
                    Server.logSendMTP("message '" + message.getSubject() + "' sent to " + recipient + ".");
                    Server.logSendMTP("last response: " + transport.getLastServerResponse());
                    lastException = null;
                    break;
                } catch (MailConnectException ex) {
                    Server.logSendMTP("connection failed.");
                    lastException = ex;
                } catch (SendFailedException ex) {
                    Server.logSendMTP("send failed.");
                    throw ex;
                } catch (MessagingException ex) {
                    if (ex.getMessage().contains(" TLS ")) {
                        Server.logSendMTP("cannot establish TLS connection.");
                        if (transport.isConnected()) {
                            transport.close();
                            Server.logSendMTP("connection closed.");
                        }
                        Server.logInfo("sending e-mail message without TLS.");
                        props.put("mail.smtp.starttls.enable", "false");
                        session = Session.getDefaultInstance(props);
                        transport = (SMTPTransport) session.getTransport("smtp");
                        try {
                            transport.setLocalHost(HOSTNAME);
                            Server.logSendMTP("connecting to " + mx + ":25.");
                            transport.connect(mx, 25, null, null);
                            Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipient + ".");
                            transport.sendMessage(message, recipientAlone);
                            Server.logSendMTP(
                                    "message '" + message.getSubject() + "' sent to " + recipient + ".");
                            Server.logSendMTP("last response: " + transport.getLastServerResponse());
                            lastException = null;
                            break;
                        } catch (SendFailedException ex2) {
                            Server.logSendMTP("send failed.");
                            throw ex2;
                        } catch (Exception ex2) {
                            lastException = ex2;
                        }
                    } else {
                        lastException = ex;
                    }
                } catch (Exception ex) {
                    Server.logError(ex);
                    lastException = ex;
                } finally {
                    if (transport.isConnected()) {
                        transport.close();
                        Server.logSendMTP("connection closed.");
                    }
                }
            }
        }
        if (lastException == null) {
            return true;
        } else {
            throw lastException;
        }
    } else if (hasRelaySMTP()) {
        Server.logInfo("sending e-mail message.");
        Server.logSendMTP("authenticate: " + Boolean.toString(SMTP_IS_AUTH) + ".");
        Server.logSendMTP("start TLS: " + Boolean.toString(SMTP_STARTTLS) + ".");
        Properties props = System.getProperties();
        props.put("mail.smtp.auth", Boolean.toString(SMTP_IS_AUTH));
        props.put("mail.smtp.starttls.enable", Boolean.toString(SMTP_STARTTLS));
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", Short.toString(SMTP_PORT));
        props.put("mail.smtp.timeout", Integer.toString(timeout));
        props.put("mail.smtp.connectiontimeout", "3000");
        props.put("mail.smtp.ssl.trust", SMTP_HOST);
        Address[] recipients = message.getAllRecipients();
        TreeSet<String> recipientSet = new TreeSet<String>();
        for (Address recipient : recipients) {
            recipientSet.add(recipient.toString());
        }
        Session session = Session.getDefaultInstance(props);
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        try {
            if (HOSTNAME != null) {
                transport.setLocalHost(HOSTNAME);
            }
            Server.logSendMTP("connecting to " + SMTP_HOST + ":" + SMTP_PORT + ".");
            transport.connect(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD);
            Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipientSet + ".");
            transport.sendMessage(message, recipients);
            Server.logSendMTP("message '" + message.getSubject() + "' sent to " + recipientSet + ".");
            return true;
        } catch (SendFailedException ex) {
            Server.logSendMTP("send failed.");
            throw ex;
        } catch (AuthenticationFailedException ex) {
            Server.logSendMTP("authentication failed.");
            return false;
        } catch (MailConnectException ex) {
            Server.logSendMTP("connection failed.");
            return false;
        } catch (MessagingException ex) {
            Server.logSendMTP("messaging failed.");
            return false;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        } finally {
            if (transport.isConnected()) {
                transport.close();
                Server.logSendMTP("connection closed.");
            }
        }
    } else {
        return false;
    }
}

From source file:org.dasein.cloud.openstack.nova.os.ext.rackspace.lb.RackspaceLoadBalancers.java

private @Nonnull Collection<String> mapIPs(@Nonnull String loadBalancerId, @Nullable String[] addresses)
        throws CloudException, InternalException {
    TreeSet<String> nodeIds = new TreeSet<String>();

    if (addresses != null && addresses.length > 0) {
        Collection<Node> nodes = getNodes(loadBalancerId);

        for (String address : addresses) {
            for (Node n : nodes) {
                if (n.address.equals(address)) {
                    nodeIds.add(n.nodeId);
                    break;
                }/*from   ww  w .j a v  a 2s  . c  om*/
            }
        }
    }
    return nodeIds;
}

From source file:com.ecyrd.jspwiki.ReferenceManager.java

/**
 * Finds all references to non-existant pages. This requires a linear
 * scan through m_refersTo values; each value must have a corresponding
 * key entry in the reference Maps, otherwise such a page has never
 * been created./*www.  j a  va2s .com*/
 * <P>
 * Returns a Collection containing Strings of unreferenced page names.
 * Each non-existant page name is shown only once - we don't return information
 * on who referred to it.
 * 
 * @return A Collection of Strings
 */
public synchronized Collection findUncreated() {
    TreeSet<String> uncreated = new TreeSet<String>();

    // Go through m_refersTo values and check that m_refersTo has the corresponding keys.
    // We want to reread the code to make sure our HashMaps are in sync...

    Collection<Collection<String>> allReferences = m_refersTo.values();

    for (Collection<String> refs : allReferences) {
        if (refs != null) {
            for (String aReference : refs) {
                if (m_engine.pageExists(aReference) == false) {
                    uncreated.add(aReference);
                }
            }
        }
    }

    return uncreated;
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method,
        @Nonnull Map<String, String> queryParams) throws CloudException, InternalException {
    fetchKeys();/*  w  ww  . j  av  a 2  s  .c  o  m*/

    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was specified for this request");
    }
    Header h = method.getFirstHeader("content-type");
    String contentType = (h == null ? null : h.getValue());

    if (contentType == null) {
        contentType = "";
    }
    StringBuilder stringToSign = new StringBuilder();

    stringToSign.append(method.getMethod().toUpperCase()).append("\n");
    stringToSign.append("\n"); // content-md5
    stringToSign.append(contentType).append("\n");
    stringToSign.append(method.getFirstHeader("date").getValue()).append("\n");

    Header[] headers = method.getAllHeaders();
    TreeSet<String> keys = new TreeSet<String>();

    for (Header header : headers) {
        if (header.getName().startsWith(Header_Prefix_MS)) {
            keys.add(header.getName().toLowerCase());
        }
    }

    for (String key : keys) {
        Header header = method.getFirstHeader(key);

        if (header != null) {
            Header[] all = method.getHeaders(key);

            stringToSign.append(key.toLowerCase().trim()).append(":");
            if (all != null && all.length > 0) {
                for (Header current : all) {
                    String v = (current.getValue() != null ? current.getValue() : "");

                    stringToSign.append(v.trim().replaceAll("\n", " ")).append(",");
                }
            }
            stringToSign.deleteCharAt(stringToSign.lastIndexOf(","));
        } else {
            stringToSign.append(key.toLowerCase().trim()).append(":");
        }
        stringToSign.append("\n");
    }

    stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath());

    keys.clear();
    for (String key : queryParams.keySet()) {
        if (key.equalsIgnoreCase("comp")) {
            key = key.toLowerCase();
            keys.add(key);
        }
    }
    if (!keys.isEmpty()) {
        stringToSign.append("?");
        for (String key : keys) {
            String value = queryParams.get(key);

            if (value == null) {
                value = "";
            }
            stringToSign.append(key).append("=").append(value).append("&");
        }
        stringToSign.deleteCharAt(stringToSign.lastIndexOf("&"));
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("BEGIN STRING TO SIGN");
            logger.debug(stringToSign.toString());
            logger.debug("END STRING TO SIGN");
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256"));

        String signature = new String(
                Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8"))));

        if (logger.isDebugEnabled()) {
            logger.debug("signature=" + signature);
        }
        return signature;
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 not supported: " + e.getMessage());
        throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("No such algorithm: " + e.getMessage());
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        logger.error("Invalid key: " + e.getMessage());
        throw new InternalException(e);
    }
}

From source file:com.ecyrd.jspwiki.providers.WikiVersioningFileProvider.java

/**
 * Iterates through all WikiPages, matches them against the given query, and returns a Collection
 * of SearchResult objects./*www .ja  v  a  2 s  . c o m*/
 * @param query
 * @return
 */
@Override
public Collection findPages(QueryItem[] query) {
    File wikipagedir = new File(getPageDirectory());
    TreeSet res = new TreeSet(new SearchResultComparator());
    SearchMatcher matcher = new SearchMatcher(m_engine, query);

    File[] wikipages = wikipagedir.listFiles(new WikiFileFilter());

    for (int i = 0; i < wikipages.length; i++) {
        FileInputStream input = null;
        String filename = wikipages[i].getName();
        int cutpoint = filename.lastIndexOf(FILE_EXT);
        String wikiname = filename.substring(0, cutpoint);

        wikiname = unmangleName(wikiname);

        try {
            input = new FileInputStream(wikipages[i]);
            String pagetext = FileUtil.readContents(input, m_encoding);
            SearchResult comparison = matcher.matchPageContent(wikiname, pagetext);
            if (comparison != null) {
                res.add(comparison);
            }
        } catch (IOException e) {
            SilverTrace.error("wiki", "WikiVersioningFileProvider.findPages()", "wiki.EX_FIND_PAGES_FAILED",
                    "Failed to read " + filename, e);
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
            } // It's fine to fail silently.
        }
    }
    return res;
}

From source file:net.spfbl.core.Peer.java

public TreeSet<Peer> getRepassSet() {
    TreeSet<Peer> peerSet = new TreeSet<Peer>();
    for (Peer peer : getSet()) {
        if (!peer.equals(this)) {
            switch (peer.getSendStatus()) {
            case REPASS:
                peerSet.add(peer);
                break;
            }//w  w  w .j a  v a  2  s .  c o  m
        }
    }
    return peerSet;
}

From source file:net.spfbl.core.Peer.java

private TreeSet<String> getAllReputations(String value) {
    TreeSet<String> blockSet = new TreeSet<String>();
    if (Subnet.isValidIP(value)) {
        String ip = Subnet.normalizeIP(value);
        if (containsReputationExact(ip)) {
            blockSet.add(ip);
        }/*from w  w  w .  j  a  v  a2  s  .  c o  m*/
    } else if (Subnet.isValidCIDR(value)) {
        String cidr = Subnet.normalizeCIDR(value);
        for (String ip : subSet("0", ":")) {
            if (Subnet.containsIP(cidr, ip)) {
                blockSet.add(ip);
            }
        }
        for (String ip : subSet("a", "g")) {
            if (SubnetIPv6.containsIP(cidr, ip)) {
                blockSet.add(ip);
            }
        }
    } else if (value.startsWith(".")) {
        String hostname = value;
        for (String key : subSet(".", "/")) {
            if (key.endsWith(hostname)) {
                blockSet.add(key);
            }
        }
        for (String mx : subSet("@", "A")) {
            String hostKey = '.' + mx.substring(1);
            if (hostKey.endsWith(hostname)) {
                blockSet.add(hostKey);
            }
        }
    } else if (containsReputationExact(value)) {
        blockSet.add(value);
    }
    return blockSet;
}