Example usage for java.util Map isEmpty

List of usage examples for java.util Map isEmpty

Introduction

In this page you can find the example usage for java.util Map isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:Main.java

public static String request(String url, Map<String, String> cookies, Map<String, String> parameters)
        throws Exception {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36");
    if (cookies != null && !cookies.isEmpty()) {
        StringBuilder cookieHeader = new StringBuilder();
        for (String cookie : cookies.values()) {
            if (cookieHeader.length() > 0) {
                cookieHeader.append(";");
            }/*  www . j a  v  a2 s .  c  o m*/
            cookieHeader.append(cookie);
        }
        connection.setRequestProperty("Cookie", cookieHeader.toString());
    }
    connection.setDoInput(true);
    if (parameters != null && !parameters.isEmpty()) {
        connection.setDoOutput(true);
        OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
        osw.write(parametersToWWWFormURLEncoded(parameters));
        osw.flush();
        osw.close();
    }
    if (cookies != null) {
        for (Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) {
            if (headerEntry != null && headerEntry.getKey() != null
                    && headerEntry.getKey().equalsIgnoreCase("Set-Cookie")) {
                for (String header : headerEntry.getValue()) {
                    for (HttpCookie httpCookie : HttpCookie.parse(header)) {
                        cookies.put(httpCookie.getName(), httpCookie.toString());
                    }
                }
            }
        }
    }
    Reader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringWriter w = new StringWriter();
    char[] buffer = new char[1024];
    int n = 0;
    while ((n = r.read(buffer)) != -1) {
        w.write(buffer, 0, n);
    }
    r.close();
    return w.toString();
}

From source file:com.vmware.identity.rest.core.client.URIFactory.java

@SuppressWarnings("unchecked")
public static URI buildURI(HostRetriever host, String path, Object... args) throws ClientException {
    Map<String, Object> parameters = null;

    if (args != null) {
        if (args[args.length - 1] instanceof Map) {
            parameters = (Map<String, Object>) args[args.length - 1];
            args = Arrays.copyOf(args, args.length - 1);
        }//from  ww  w  .  j a v a  2  s . co  m
    }

    URIBuilder builder = host.getURIBuilder().setPath(String.format(path, args));

    if (parameters != null && !parameters.isEmpty()) {
        for (Entry<String, Object> param : parameters.entrySet()) {
            if (param.getValue() instanceof Collection) {
                Collection<Object> list = (Collection<Object>) param.getValue();
                Iterator<Object> iter = list.iterator();

                while (iter.hasNext()) {
                    builder.setParameter(param.getKey(), iter.next().toString());
                }

            } else {
                builder.setParameter(param.getKey(), param.getValue().toString());
            }
        }
    }

    try {
        return builder.build();
    } catch (URISyntaxException e) {
        throw new ClientException("An error occurred while building the URI", e);
    }
}

From source file:springfox.documentation.swagger2.web.ForwardedHeader.java

/**
 * Creates a new {@link ForwardedHeader} from the given source.
 *
 * @param source can be {@literal null}.
 * @return/*from w ww.  j a va  2  s  . com*/
 */
public static ForwardedHeader of(String source) {

    if (!StringUtils.hasText(source)) {
        return NO_HEADER;
    }

    Map<String, String> elements = new HashMap<String, String>();

    for (String part : source.split(";")) {

        String[] keyValue = part.split("=");

        if (keyValue.length != 2) {
            continue;
        }

        elements.put(keyValue[0].trim(), keyValue[1].trim());
    }

    Assert.notNull(elements, "Forwarded elements must not be null!");
    Assert.isTrue(!elements.isEmpty(), "At least one forwarded element needs to be present!");

    return new ForwardedHeader(elements);
}

From source file:gridool.db.partitioning.phihash.csv.normal.CsvHashPartitioningJob.java

private static GridNode mapPrimaryFragment(final byte[] distkey, final Map<GridNode, MutableInt> mappedNodes,
        final int tablePartitionNo, final GridRouter router) throws GridException {
    assert (mappedNodes.isEmpty());
    GridNode mappedNode = router.selectNode(distkey);
    if (mappedNode == null) {
        throw new GridException("Could not find any node in cluster.");
    }//  w w  w . j  a v  a2s  .c o m
    MutableInt newHidden = new MutableInt(tablePartitionNo);
    mappedNodes.put(mappedNode, newHidden);
    return mappedNode;
}

From source file:br.bireme.tb.RIPSA.java

/**
 * Given a cell, uses its info tho fill the holes of the template String.
 * @param cell a cell having the data to fill the holes
 * @return a String with holes replaced/*from   ww  w . j a v  a  2 s  . co  m*/
 * @throws IOException 
 */
static String cell2html(final Cell cell) throws IOException {
    assert cell != null;

    if (TEMPLATE == null) {
        throw new IOException("TEMPLATE is null");
    }
    final String qualifRec = cell.getElem().qualifRec.toString();
    final Matcher mat = EDITION_PAT.matcher(qualifRec);
    if (!mat.find()) {
        throw new IOException("out of pattern url [" + qualifRec + "]");
    }
    final String edition = mat.group(2);
    final String father = cell.getElem().father.toString();
    final Matcher matf = Pattern.compile("idb(\\d{4})").matcher(father);
    if (!matf.find()) {
        throw new IOException("out of pattern url [" + father + "]");
    }
    final String year = matf.group(1);

    String str = TEMPLATE;
    final StringBuilder builder = new StringBuilder();
    boolean first;

    final String title = cell.getTitle();
    final String title2 = (title == null) ? "" : title;
    str = str.replace("$$title$$", title2);

    final String subtitle = cell.getSubtitle();
    if ((subtitle != null) && (!subtitle.isEmpty())) {
        str = str.replace("$$subtitle$$", "<h2>" + subtitle + "</h2>");
    } else {
        str = str.replace("$$subtitle$$", "");
    }

    str = str.replace("$$description$$",
            "Clulas IDB - " + edition + " - " + year + " - " + title2 + " - " + subtitle);

    final StringBuilder aux = new StringBuilder(title);
    final Map<String, String> tableOptions = cell.getElem().tableOptions;

    if ((tableOptions != null) && (!tableOptions.isEmpty())) {
        for (String opt : tableOptions.values()) {
            if ((!opt.equals("No ativa")) && (!opt.equals("Todas as categorias"))) {
                aux.append(", ");
                aux.append(StringEscapeUtils.unescapeHtml4(opt));
            }
        }
    }
    str = str.replace("$$keywords$$", aux.toString());

    final List<String> scope = cell.getScope();
    builder.setLength(0);
    first = true;
    if ((scope != null) && (!scope.isEmpty())) {
        builder.append("<h3>");
        for (String scp : scope) {
            if (first) {
                first = false;
            } else {
                builder.append("<br/>\n");
            }
            builder.append(scp);
        }
        builder.append("</h3>");
        str = str.replace("$$scope$$", builder.toString());
    } else {
        str = str.replace("$$scope$$", "");
    }

    final List<String> header = cell.getHeader();
    builder.setLength(0);
    first = true;
    if ((header != null) && (!header.isEmpty())) {
        for (String hdr : header) {
            if (first) {
                first = false;
            } else {
                builder.append("<br/>\n");
            }
            builder.append(hdr);
        }
        str = str.replace("$$celheader$$", builder.toString());
    } else {
        str = str.replace("$$celheader$$", "");
    }

    final String row = cell.getRow();
    if ((row != null) && (!row.isEmpty())) {
        str = str.replace("$$celrow$$", row);
    } else {
        str = str.replace("$$celrow$$", "");
    }

    final String value = cell.getValue();
    if ((value != null) && (!value.isEmpty())) {
        String celVal;
        try {
            celVal = NFMT.format(NFMT.parse(value).floatValue());
        } catch (ParseException ex) {
            celVal = value;
        }
        str = str.replace("$$celval$$", celVal);
    } else {
        str = str.replace("$$celval$$", "");
    }

    final List<String> sources = cell.getSources();
    builder.setLength(0);
    if ((sources != null) && (!sources.isEmpty())) {
        builder.append("<div class=\"note\">\n");
        builder.append("\t\t\t\t\t\t\t<label>Fonte(s):</label>\n");
        for (String source : sources) {
            builder.append("\t\t\t\t\t\t\t<p>");
            builder.append(source);
            builder.append("</p>\n");
        }
        builder.append("\t\t\t\t\t\t</div>\n");
        str = str.replace("$$sources$$", builder.toString());
    } else {
        str = str.replace("$$sources$$", "");
    }

    final List<String> labels = cell.getLabels();
    builder.setLength(0);
    if ((labels != null) && (!labels.isEmpty())) {
        builder.append("<div class=\"note\">\n");
        builder.append("\t\t\t\t\t\t\t<label>Legenda(s):</label>\n");
        for (String label : labels) {
            builder.append("\t\t\t\t\t\t\t<p>");
            builder.append(label);
            builder.append("</p>\n");
        }
        builder.append("\t\t\t\t\t\t</div>\n");
        str = str.replace("$$labels$$", builder.toString());
    } else {
        str = str.replace("$$labels$$", "");
    }

    final List<String> notes = cell.getNotes();
    builder.setLength(0);
    if ((notes != null) && (!notes.isEmpty())) {
        builder.append("<div class=\"note\">\n");
        builder.append("\t\t\t\t\t\t\t<label>Nota(s):</label>\n");
        for (String note : notes) {
            builder.append("\t\t\t\t\t\t\t<p>");
            builder.append(note);
            builder.append("</p>\n");
        }
        builder.append("\t\t\t\t\t\t</div>\n");
        str = str.replace("$$notes$$", builder.toString());
    } else {
        str = str.replace("$$notes$$", "");
    }

    str = str.replace("$$father$$", cell.getElem().father.toString());
    str = str.replace("$$qualifRec$$", cell.getElem().qualifRec.toString());

    builder.setLength(0);
    if ((tableOptions != null) && (!tableOptions.isEmpty())) {
        str = str.replace("$$tableHeader$$",
                "<strong>Filtros usados para a" + " gerao da tabela de dados do TabNet</strong>\n<ul>\n");
        /*str = str.replace("$$tableHeader$$", "<strong>Tabela de dados do "
              + "TabNet gerada com os seguintes filtros:</strong><br/><br/>");*/
        for (Map.Entry<String, String> option : tableOptions.entrySet()) {
            builder.append("\t\t\t\t\t\t<li><label>");
            builder.append(option.getKey());
            builder.append(":</label> ");
            builder.append(option.getValue());
            builder.append("</li>\n");
        }
        str = str.replace("$$tableOptions$$", builder.toString() + "\n</ul>");
    } else {
        str = str.replace("$$tableHeader$$", "");
        str = str.replace("$$tableOptions$$", "");
    }

    return str;
}

From source file:com.siemens.sw360.datahandler.common.CommonUtils.java

public static boolean atLeastOneIsNotEmpty(Map... maps) {
    for (Map map : maps) {
        if (map != null && !map.isEmpty())
            return true;
    }//from www .  jav  a  2  s .  c o m
    return false;
}

From source file:org.apache.ignite.yardstick.IgniteNode.java

/**
 * @param springCfgPath Spring configuration file path.
 * @return Grid configuration.//from w  w w . jav  a2s. co  m
 * @throws Exception If failed.
 */
protected static IgniteConfiguration loadConfiguration(String springCfgPath) throws Exception {
    URL url;

    try {
        url = new URL(springCfgPath);
    } catch (MalformedURLException e) {
        url = IgniteUtils.resolveIgniteUrl(springCfgPath);

        if (url == null)
            throw new IgniteCheckedException("Spring XML configuration path is invalid: " + springCfgPath
                    + ". Note that this path should be either absolute or a relative local file system path, "
                    + "relative to META-INF in classpath or valid URL to IGNITE_HOME.", e);
    }

    GenericApplicationContext springCtx;

    try {
        springCtx = new GenericApplicationContext();

        new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(url));

        springCtx.refresh();
    } catch (BeansException e) {
        throw new Exception("Failed to instantiate Spring XML application context [springUrl=" + url + ", err="
                + e.getMessage() + ']', e);
    }

    Map<String, IgniteConfiguration> cfgMap;

    try {
        cfgMap = springCtx.getBeansOfType(IgniteConfiguration.class);
    } catch (BeansException e) {
        throw new Exception("Failed to instantiate bean [type=" + IgniteConfiguration.class + ", err="
                + e.getMessage() + ']', e);
    }

    if (cfgMap == null || cfgMap.isEmpty())
        throw new Exception("Failed to find ignite configuration in: " + url);

    return cfgMap.values().iterator().next();
}

From source file:net.opentsdb.ConfigReader.java

public static String[] load(final Config config, final String[] args) {
    InputStream is = null;//w w w . j a  v  a2s.  c  om
    String[] noConfigArgs = {};
    try {

        is = ConfigReader.class.getClassLoader().getResourceAsStream(CONFIG_PATH);
        ArrayNode an = (ArrayNode) JSON.getMapper().readTree(is);
        final LinkedHashMap<String, ConfigurationItem> citems = new LinkedHashMap<String, ConfigurationItem>(
                an.size());
        final HashMap<String, ConfigurationItem> clOptions = new HashMap<String, ConfigurationItem>();
        for (int i = 0; i < an.size(); i++) {
            JsonNode jn = an.get(i);
            ConfigurationItem ci = JSON.getMapper().convertValue(jn, ConfigurationItem.class);
            ci.resolve();
            if (ci.getCl() != null) {
                clOptions.put(ci.getCl(), ci);
            }
            if (ci.getValue() != null) {
                //config.overrideConfig(ci.getKey(), ci.getValue().toString());
                ci.validate();
                citems.put(ci.getKey(), ci);
            }
            //System.out.println(ci.dump());
        }

        final ArgP argp = newArgP();
        noConfigArgs = argp.parse(args);
        final Map<String, String> argpOptions = argp.getParsed();
        if (!argpOptions.isEmpty()) {
            for (Map.Entry<String, String> entry : argpOptions.entrySet()) {
                ConfigurationItem argCi = clOptions.get(entry.getKey());
                if (argCi != null) {
                    argCi.setValueAsText(entry.getValue());
                    citems.put(argCi.getKey(), argCi);
                }
            }
        }
        // Write the configuration to an OpenTSDB config         
        for (ConfigurationItem configItem : citems.values()) {
            config.overrideConfig(configItem.getKey(), configItem.getValueStr());
        }
        return noConfigArgs;
    } catch (Exception ex) {
        throw new RuntimeException("Failed to load resource [" + CONFIG_PATH + "]", ex);
    }
}

From source file:core.Web.java

public static String httpRequest(URL url, Map<String, String> properties, JSONObject message) {
    //        System.out.println(url);
    try {//ww w. j  av a 2 s .  c  o m
        // Create connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //connection.addRequestProperty("Authorization", API_KEY);
        // Set properties if needed
        if (properties != null && !properties.isEmpty()) {
            properties.forEach(connection::setRequestProperty);
        }
        // Post message
        if (message != null) {
            // Maybe somewhere
            connection.setDoOutput(true);
            //                connection.setRequestProperty("Accept", "application/json");
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(connection.getOutputStream()))) {
                writer.write(message.toString());
            }
        }
        // Establish connection
        connection.connect();
        int responseCode = connection.getResponseCode();

        if (responseCode != 200) {
            System.err.println("Error " + responseCode + ":" + url);
            return null;
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            String content = "";
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            return content;
        }

    } catch (IOException ex) {
        Logger.getLogger(Web.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:core.Web.java

public static JSONObject httpsRequest(URL url, Map<String, String> properties, JSONObject message) {
    //        System.out.println(url);
    try {//from   w w  w.  j a  v a2  s.  c o m
        // Create connection
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        //connection.addRequestProperty("Authorization", API_KEY);
        // Set properties if needed
        if (properties != null && !properties.isEmpty()) {
            properties.forEach(connection::setRequestProperty);
        }
        // Post message
        if (message != null) {
            // Maybe somewhere
            connection.setDoOutput(true);
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(connection.getOutputStream()))) {
                writer.write(message.toString());
            }
        }
        // Establish connection
        connection.connect();
        int responseCode = connection.getResponseCode();

        if (responseCode != 200) {
            throw new RuntimeException("Response code was not 200. Detected response was " + responseCode);
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            String content = "";
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            return new JSONObject(content);
        }

    } catch (IOException ex) {
        Logger.getLogger(Web.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}