Example usage for java.util TreeSet contains

List of usage examples for java.util TreeSet contains

Introduction

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

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:org.deegree.commons.utils.net.HttpUtils.java

private static void handleProxies(String protocol, HttpClient client, String host) {
    TreeSet<String> nops = new TreeSet<String>();

    String proxyHost = getProperty((protocol == null ? "" : protocol + ".") + "proxyHost");

    String proxyUser = getProperty((protocol == null ? "" : protocol + ".") + "proxyUser");
    String proxyPass = getProperty((protocol == null ? "" : protocol + ".") + "proxyPassword");

    if (proxyHost != null) {
        String nop = getProperty((protocol == null ? "" : protocol + ".") + "noProxyHosts");
        if (nop != null && !nop.equals("")) {
            nops.addAll(asList(nop.split("\\|")));
        }/*from  ww  w  . ja v a2s  . co  m*/
        nop = getProperty((protocol == null ? "" : protocol + ".") + "nonProxyHosts");
        if (nop != null && !nop.equals("")) {
            nops.addAll(asList(nop.split("\\|")));
        }

        int proxyPort = parseInt(getProperty((protocol == null ? "" : protocol + ".") + "proxyPort"));

        HostConfiguration hc = client.getHostConfiguration();

        if (LOG.isDebugEnabled()) {
            LOG.debug("Found the following no- and nonProxyHosts: {}", nops);
        }

        if (proxyUser != null) {
            Credentials creds = new UsernamePasswordCredentials(proxyUser, proxyPass);
            client.getState().setProxyCredentials(AuthScope.ANY, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }

        if (!nops.contains(host)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Using proxy {}:{}", proxyHost, proxyPort);
                if (protocol == null) {
                    LOG.debug("This overrides the protocol specific settings, if there were any.");
                }
            }
            hc.setProxy(proxyHost, proxyPort);
            client.setHostConfiguration(hc);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Proxy was set, but {} was contained in the no-/nonProxyList!", host);
                if (protocol == null) {
                    LOG.debug("If a protocol specific proxy has been set, it will be used anyway!");
                }
            }
        }
    }

    if (protocol != null) {
        handleProxies(null, client, host);
    }
}

From source file:ca.oson.json.gson.functional.DefaultTypeAdaptersTest.java

public void testTreeSetDeserialization() {
    String json = "['Value1']";
    Type type = new TypeToken<TreeSet<String>>() {
    }.getType();/*  w w  w  .  ja va2 s. c o  m*/
    TreeSet<String> treeSet = oson.fromJson(json, type);
    assertTrue(treeSet.contains("Value1"));
}

From source file:org.apache.hadoop.hdfs.server.namenode.FileSystemProvider.java

/**
 * ?? ? ?? ? ?  ??  ?.//from  w  w w  .  j  a  v a  2 s . c  o m
 *
 * @param blk LocatedBlock
 * @return ?? 
 */
public static DatanodeInfo bestNode(LocatedBlock blk) {
    TreeSet<DatanodeInfo> deadNodes = new TreeSet<>();
    DatanodeInfo chosenNode = null;
    int failures = 0;
    Socket socket = null;
    DatanodeInfo[] nodes = blk.getLocations();

    if (nodes == null || nodes.length == 0) {
        throw new ServiceException("No nodes contain this block");
    }

    while (socket == null) {
        if (chosenNode == null) {
            do {
                chosenNode = nodes[rand.nextInt(nodes.length)];
            } while (deadNodes.contains(chosenNode));
        }
        int index = rand.nextInt(nodes.length);
        chosenNode = nodes[index];

        //just ping to check whether the node is alive
        InetSocketAddress address = NetUtils
                .createSocketAddr(chosenNode.getIpAddr() + ":" + chosenNode.getInfoPort());

        try {
            socket = new Socket();
            socket.connect(address, HdfsServerConstants.READ_TIMEOUT);
            socket.setSoTimeout(HdfsServerConstants.READ_TIMEOUT);
        } catch (IOException e) {
            deadNodes.add(chosenNode);
            try {
                socket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            socket = null;
            failures++;
        }

        if (failures == nodes.length) {
            throw new ServiceException("Could not reach the block containing the data. Please try again");
        }
    }
    try {
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return chosenNode;
}

From source file:org.geowebcache.service.wms.WMSGetCapabilities.java

private void capabilityLayerInner(XMLBuilder xml, TileLayer layer) throws GeoWebCacheException, IOException {
    xml.indentElement("Layer");

    if (layer.isQueryable()) {
        xml.attribute("queryable", "1");
    }/*from  ww w.  j a v  a 2  s.  c o m*/

    xml.simpleElement("Name", layer.getName(), true);

    if (layer.getMetaInformation() != null) {
        LayerMetaInformation metaInfo = layer.getMetaInformation();
        xml.simpleElement("Title", metaInfo.getTitle(), true);
        xml.simpleElement("Abstract", metaInfo.getDescription(), true);
    } else {
        xml.simpleElement("Title", layer.getName(), true);
    }

    if (layer.getMetadataURLs() != null) {
        for (MetadataURL metadataURL : layer.getMetadataURLs()) {
            xml.indentElement("MetadataURL");
            xml.attribute("type", metadataURL.getType());
            xml.simpleElement("Format", metadataURL.getFormat(), true);
            onlineResource(xml, metadataURL.getUrl().toString()); // TODO should this be URLEncoded?
            xml.endElement();
        }
    }

    {
        TreeSet<SRS> srsSet = new TreeSet<>();
        HashSet<GridSubset> gridSubsetSet = new HashSet<>();
        for (String gridSetId : layer.getGridSubsets()) {
            GridSubset curGridSubSet = layer.getGridSubset(gridSetId);
            SRS curSRS = curGridSubSet.getSRS();
            if (!srsSet.contains(curSRS)) {
                srsSet.add(curSRS);
                gridSubsetSet.add(curGridSubSet);
            }
        }
        for (SRS curSRS : srsSet) {
            xml.simpleElement("SRS", curSRS.toString(), true);
        }

        GridSubset epsg4326GridSubSet = layer.getGridSubsetForSRS(SRS.getEPSG4326());
        if (null != epsg4326GridSubSet) {
            String[] bs = boundsPrep(epsg4326GridSubSet.getCoverageBestFitBounds());
            xml.latLonBoundingBox(bs[0], bs[1], bs[2], bs[3]);
        }

        for (GridSubset curGridSubSet : gridSubsetSet) {
            String[] bs = boundsPrep(curGridSubSet.getCoverageBestFitBounds());
            xml.boundingBox(curGridSubSet.getSRS().toString(), bs[0], bs[1], bs[2], bs[3]);
        }
    }

    // WMS 1.1 Dimensions
    // TODO change API to not use string builder.  Pass an XML Builder, or ask for a model
    // object. KS
    if (layer.getParameterFilters() != null) {
        StringBuilder dims = new StringBuilder();
        StringBuilder extents = new StringBuilder();
        for (ParameterFilter parameterFilter : layer.getParameterFilters()) {
            if (parameterFilter instanceof WMSDimensionProvider) {
                ((WMSDimensionProvider) parameterFilter).appendDimensionElement(dims, "      ");
                ((WMSDimensionProvider) parameterFilter).appendExtentElement(extents, "      ");
            }
        }

        if (dims.length() > 0 && extents.length() > 0) {
            xml.appendUnescaped(dims.toString());
            xml.appendUnescaped(extents.toString());
        }
    }

    // TODO style?
    xml.endElement();
}

From source file:org.opendatakit.api.odktables.TableService.java

@POST
@Path("offices")
public Response postOfficeList(List<String> regionalOffices)
        throws ODKDatastoreException, ODKTaskLockException, PermissionDeniedException,
        TableAlreadyExistsException, AppNameMismatchException, TableNotFoundException {
    TablesUserPermissions userPermissions = new TablesUserPermissionsImpl(callingContext);

    TableManager tm = new TableManager(appId, userPermissions, callingContext);

    TreeSet<GrantedAuthorityName> ui = SecurityServiceUtil.getCurrentUserSecurityInfo(callingContext);
    if (!ui.contains(GrantedAuthorityName.ROLE_ADMINISTER_TABLES)) {
        throw new PermissionDeniedException("User does not belong to the 'Administer Tables' group");
    }//from   w  ww  .  java  2  s  .co m
    tm.updateOffices(tableId, regionalOffices);
    return Response.ok().header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
            .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
            .build();
}

From source file:org.opendatakit.api.odktables.TableService.java

@GET
@Path("offices")
public Response getOfficeList() throws ODKDatastoreException, ODKTaskLockException, PermissionDeniedException,
        TableAlreadyExistsException, AppNameMismatchException, TableNotFoundException {
    TablesUserPermissions userPermissions = new TablesUserPermissionsImpl(callingContext);

    TableManager tm = new TableManager(appId, userPermissions, callingContext);

    TreeSet<GrantedAuthorityName> ui = SecurityServiceUtil.getCurrentUserSecurityInfo(callingContext);
    if (!ui.contains(GrantedAuthorityName.ROLE_ADMINISTER_TABLES)) {
        throw new PermissionDeniedException("User does not belong to the 'Administer Tables' group");
    }//from  w ww . j  a v a  2  s. c o  m
    String officeList = tm.getOffices(tableId);
    List<String> offices = Arrays.asList(officeList.split(","));

    return Response.ok().entity(offices).encoding(BasicConsts.UTF8_ENCODE)
            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
            .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
            .build();
}

From source file:com.murati.oszk.audiobook.model.MusicProvider.java

public Iterable<String> getEbooksByQueryString(String query) {
    if (mCurrentState != State.INITIALIZED) {
        return Collections.emptyList();
    }//w w  w .j  av  a2 s. c o  m

    TreeSet<String> sortedEbookTitles = new TreeSet<String>();
    //TODO: Handle accents
    query = query.toLowerCase(Locale.US);

    for (MutableMediaMetadata track : mTrackListById.values()) {
        String title = track.metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM);
        if (!sortedEbookTitles.contains(title)) {
            String search_fields = track.metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM) + "|"
                    + track.metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE) + "|"
                    + track.metadata.getString(MediaMetadataCompat.METADATA_KEY_WRITER) + "|"
                    + track.metadata.getString(MediaMetadataCompat.METADATA_KEY_GENRE);

            if (search_fields.toLowerCase(Locale.US).contains(query)) {
                sortedEbookTitles.add(title);
            }
        }
    }

    return sortedEbookTitles;
}

From source file:org.opendatakit.api.odktables.TableService.java

/**
 * Create a particular tableId (supplied in implementation constructor)
 *
 * @param definition/*  ww w .j av  a  2s.c o  m*/
 * @return {@link TableResource} of the table. This may already exist (with identical schema) or be newly created.
 * @throws ODKDatastoreException
 * @throws TableAlreadyExistsException
 * @throws PermissionDeniedException
 * @throws ODKTaskLockException
 * @throws IOException
 */
@PUT
@Consumes({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })

public Response createTable(TableDefinition definition) throws ODKDatastoreException,
        TableAlreadyExistsException, PermissionDeniedException, ODKTaskLockException, IOException {

    TreeSet<GrantedAuthorityName> ui = SecurityServiceUtil.getCurrentUserSecurityInfo(callingContext);
    if (!ui.contains(GrantedAuthorityName.ROLE_ADMINISTER_TABLES)) {
        throw new PermissionDeniedException("User does not belong to the 'Administer Tables' group");
    }

    TablesUserPermissions userPermissions = new TablesUserPermissionsImpl(callingContext);

    TableManager tm = new TableManager(appId, userPermissions, callingContext);
    // NOTE: the only access control restriction for
    // creating the table is the Administer Tables role.
    List<Column> columns = definition.getColumns();

    TableEntry entry = tm.createTable(tableId, columns, null);
    TableResource resource = getResource(info, appId, entry);

    // set the table-level manifest ETag if known...
    try {
        resource.setTableLevelManifestETag(
                FileManifestService.getTableLevelManifestETag(entry.getTableId(), callingContext));
    } catch (ODKDatastoreException e) {
        // ignore
    }

    logger.info(String.format("createTable: tableId: %s, definition: %s", tableId, definition));

    return Response.ok(resource)
            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
            .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
            .build();
}

From source file:net.spfbl.data.White.java

public static void clear(Client client, User user, String ip, String sender, String hostname, String qualifier,
        String recipient) throws ProcessException {
    String userEmail = null;//from   w  ww.j  a v a2  s.  c  o  m
    if (user != null) {
        userEmail = user.getEmail();
    } else if (client != null) {
        userEmail = client.getEmail();
    }
    String white;
    int mask = SubnetIPv4.isValidIPv4(ip) ? 32 : 64;
    if ((white = White.clearCIDR(ip, mask)) != null) {
        if (userEmail == null) {
            Server.logInfo("false negative WHITE '" + white + "' detected.");
        } else {
            Server.logInfo("false negative WHITE '" + white + "' detected by '" + userEmail + "'.");
        }
    }
    TreeSet<String> whiteSet = new TreeSet<String>();
    while ((white = find(client, user, ip, sender, hostname, qualifier, recipient)) != null) {
        if (whiteSet.contains(white)) {
            throw new ProcessException("FATAL WHITE ERROR " + white);
        } else if (dropExact(white)) {
            if (user != null) {
                Server.logInfo("false negative WHITE '" + white + "' detected by '" + user.getEmail() + "'.");
            } else if (client != null && client.hasEmail()) {
                Server.logInfo("false negative WHITE '" + white + "' detected by '" + client.getEmail() + "'.");
            } else {
                Server.logInfo("false negative WHITE '" + white + "' detected.");
            }
        }
        whiteSet.add(white);
    }
}

From source file:org.opendatakit.api.odktables.TableService.java

public Response putInternalTableProperties(String odkClientVersion, PropertyEntryXmlList propertiesList)
        throws ODKDatastoreException, PermissionDeniedException, ODKTaskLockException, TableNotFoundException {

    TreeSet<GrantedAuthorityName> ui = SecurityServiceUtil.getCurrentUserSecurityInfo(callingContext);
    if (!ui.contains(GrantedAuthorityName.ROLE_ADMINISTER_TABLES)) {
        throw new PermissionDeniedException("User does not belong to the 'Administer Tables' group");
    }//from  w  w w  .  ja  v  a  2  s.c  om

    TablesUserPermissions userPermissions = new TablesUserPermissionsImpl(callingContext);

    String appRelativePath = FileManager.getPropertiesFilePath(tableId);

    String contentType = WebConsts.CONTENT_TYPE_CSV_UTF8;

    // DbTableFileInfo.NO_TABLE_ID -- means that we are working with app-level
    // permissions
    userPermissions.checkPermission(appId, tableId, TablePermission.WRITE_PROPERTIES);

    ByteArrayOutputStream bas = new ByteArrayOutputStream();
    Writer wtr = null;
    RFC4180CsvWriter csvWtr = null;

    try {
        wtr = new OutputStreamWriter(bas, CharEncoding.UTF_8);
        csvWtr = new RFC4180CsvWriter(wtr);
        String[] entry = new String[5];
        entry[0] = "_partition";
        entry[1] = "_aspect";
        entry[2] = "_key";
        entry[3] = "_type";
        entry[4] = "_value";
        csvWtr.writeNext(entry);
        for (PropertyEntryXml e : propertiesList.getProperties()) {
            entry[0] = e.getPartition();
            entry[1] = e.getAspect();
            entry[2] = e.getKey();
            entry[3] = e.getType();
            entry[4] = e.getValue();
            csvWtr.writeNext(entry);
        }
        csvWtr.flush();
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
        throw new IllegalStateException("Unrecognized UTF-8 charset!");
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new IllegalStateException("Unable to write into a byte array!");
    } finally {
        if (csvWtr != null) {
            try {
                csvWtr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (wtr != null) {
            try {
                wtr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    byte[] content = bas.toByteArray();

    FileManager fm = new FileManager(appId, callingContext);

    FileContentInfo fi = new FileContentInfo(appRelativePath, contentType, Long.valueOf(content.length), null,
            content);

    @SuppressWarnings("unused")
    ConfigFileChangeDetail outcome = fm.putFile(odkClientVersion, tableId, fi, userPermissions);
    return Response.status(Status.ACCEPTED)
            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
            .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
            .build();
}