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:org.opendatakit.api.forms.FormService.java

static String getDefinitionFromFiles(Map<String, byte[]> files) {
    String definition = null;/*from w ww.j  av a2 s. com*/
    if (files != null && !files.isEmpty()) {
        for (String filename : files.keySet()) {
            if (filename.endsWith("definition.csv")) {

                definition = new String(files.get(filename));
                break;
            }
        }
    }
    if (definition == null) {
        throw new WebApplicationException(ErrorConsts.NO_DEFINITION_FILE, HttpServletResponse.SC_BAD_REQUEST);
    }
    return definition;
}

From source file:com.intuit.tank.service.impl.v1.report.SummaryReportRunner.java

/**
 * @param db//from   www. j a  v a 2s.  c om
 * @param tableName
 */
public static void generateSummary(String jobIdString) {
    synchronized (jobIdString) {
        LOG.info("generateSummary: job " + jobIdString);
        ResultsReader resultsReader = ReportingFactory.getResultsReader();
        if (resultsReader.hasTimingData(jobIdString)) {
            LOG.info("Generating Summary Report for job " + jobIdString + "...");
            SummaryDataDao dao = new SummaryDataDao();
            int jobId = Integer.parseInt(jobIdString);
            if (dao.findByJobId(jobId).size() == 0) {
                MethodTimer mt = new MethodTimer(LOG, SummaryReportRunner.class, "generateSummary");
                MetricsCalculator metricsCalculator = new MetricsCalculator();
                JobInstance jobInstance = new JobInstanceDao().findById(Integer.valueOf(jobIdString));
                metricsCalculator.retrieveAndCalculateTimingData(jobIdString,
                        calculateSteadyStateStart(jobInstance), calculateSteadyStateEnd(jobInstance));
                mt.markAndLog("calculated timing data");
                Map<String, DescriptiveStatistics> timingData = metricsCalculator.getSummaryResults();
                if (!timingData.isEmpty()) {
                    try {
                        List<SummaryData> toStore = new ArrayList<SummaryData>();
                        for (Entry<String, DescriptiveStatistics> entry : timingData.entrySet()) {
                            SummaryData data = getSummaryData(jobId, entry.getKey(), entry.getValue());
                            toStore.add(data);
                        }
                        dao.persistCollection(toStore);
                        LOG.info("Finished Summary Report for job " + jobId);
                    } catch (Exception t) {
                        LOG.error("Error adding Summary Items: " + t, t);
                    }
                }
                mt.markAndLog("stored " + timingData.size() + " summary data items");
                // now store buckets
                Map<String, Map<Date, BucketDataItem>> bucketItems = metricsCalculator.getBucketItems();
                int countItems = 0;
                if (!bucketItems.isEmpty()) {
                    PeriodicDataDao periodicDataDao = new PeriodicDataDao();
                    try {
                        List<PeriodicData> toStore = new ArrayList<PeriodicData>();
                        for (Entry<String, Map<Date, BucketDataItem>> entry : bucketItems.entrySet()) {
                            for (BucketDataItem bucketItem : entry.getValue().values()) {
                                PeriodicData data = getBucketData(jobId, entry.getKey(), bucketItem);
                                toStore.add(data);
                                countItems++;
                            }
                        }
                        periodicDataDao.persistCollection(toStore);
                        LOG.info("Finished Summary Report for job " + jobId);
                    } catch (Exception t) {
                        LOG.error("Error adding Summary Items: " + t, t);
                    }
                }
                mt.markAndLog("stored " + countItems + " periodic data items");
                mt.endAndLog();
            }
        } else {
            LOG.info("generateSummary: job " + jobIdString + " has no data.");
        }
        // now delete timing data
        resultsReader.deleteTimingForJob(jobIdString, true);
    }
}

From source file:de.jaetzold.philips.hue.HueBridgeComm.java

static List<HueBridge> discover() {
    final Logger log = Logger.getLogger(HueBridge.class.getName());
    final SimpleServiceDiscovery serviceDiscovery = new SimpleServiceDiscovery();
    int attempted = 0;
    int maxAttempts = Math.min(4, Math.max(1, HueBridge.discoveryAttempts));
    Map<String, URL> foundBriges = new HashMap<>();
    // if nothing is found the first time try up to maxAttempts times with increasing timeouts
    while (foundBriges.isEmpty() && attempted < maxAttempts) {
        serviceDiscovery.setSearchMx(1 + attempted);
        serviceDiscovery.setSocketTimeout(500 + attempted * 1500);
        final List<? extends SimpleServiceDiscovery.Response> responses = serviceDiscovery
                .discover(SimpleServiceDiscovery.SEARCH_TARGET_ROOTDEVICE);
        try {/*from   w  ww .ja va  2s  . c o m*/
            for (SimpleServiceDiscovery.Response response : responses) {
                String urlBase = null;
                final String usn = response.getHeader("USN");
                if (usn != null && usn.matches("uuid:[-\\w]+")) {
                    if (!foundBriges.containsKey(usn)) {
                        final String server = response.getHeader("SERVER");
                        if (server != null && server.contains("IpBridge")) {
                            final String location = response.getHeader("LOCATION");
                            if (location != null && location.endsWith(".xml")) {
                                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                DocumentBuilder db = dbf.newDocumentBuilder();
                                Document doc = db.parse(new URL(location).openStream());
                                final NodeList modelNames = doc.getElementsByTagName("modelName");
                                for (int i = 0; i < modelNames.getLength(); i++) {
                                    final Node item = modelNames.item(i);
                                    if (item.getParentNode().getNodeName().equals("device") && item
                                            .getTextContent().matches("(?i).*philips\\s+hue\\s+bridge.*")) {
                                        final NodeList urlBases = doc.getElementsByTagName("URLBase");
                                        if (urlBases.getLength() > 0) {
                                            urlBase = urlBases.item(0).getTextContent();
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (urlBase != null) {
                    foundBriges.put(usn, new URL(urlBase));
                }
            }
        } catch (Exception e) {
            HueBridge.lastDiscoveryException = e;
            log.log(Level.INFO, "Exception when dicovering devices", e);
        }
        attempted++;
    }
    List<HueBridge> result = new ArrayList<>();
    for (Map.Entry<String, URL> entry : foundBriges.entrySet()) {
        final HueBridge bridge = new HueBridge(entry.getValue(), null);
        bridge.UDN = entry.getKey();
        result.add(bridge);
    }
    return result;
}

From source file:com.baidubce.util.HttpUtils.java

public static String getCanonicalQueryString(Map<String, String> parameters, boolean forSignature) {
    if (parameters.isEmpty()) {
        return "";
    }// w ww  . jav a2 s . co  m

    List<String> parameterStrings = Lists.newArrayList();
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        if (forSignature && Headers.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) {
            continue;
        }
        String key = entry.getKey();
        checkNotNull(key, "parameter key should not be null");
        String value = entry.getValue();
        if (value == null) {
            if (forSignature) {
                parameterStrings.add(normalize(key) + '=');
            } else {
                parameterStrings.add(normalize(key));
            }
        } else {
            parameterStrings.add(normalize(key) + '=' + normalize(value));
        }
    }
    Collections.sort(parameterStrings);

    return queryStringJoiner.join(parameterStrings);
}

From source file:com.datumbox.framework.core.common.dataobjects.DataframeMatrix.java

/**
 * Parses a testing dataset and converts it to DataframeMatrix by using an already
existing mapping between feature names and column ids. Typically used
 * to parse the testing or validation dataset.
 * //from   w  w w . j  a va  2s  .  c  o m
 * @param newData
 * @param recordIdsReference
 * @param featureIdsReference
 * @return 
 */
public static DataframeMatrix parseDataset(Dataframe newData, Map<Integer, Integer> recordIdsReference,
        Map<Object, Integer> featureIdsReference) {
    if (featureIdsReference.isEmpty()) {
        throw new IllegalArgumentException("The featureIdsReference map should not be empty.");
    }

    setStorageEngine(newData);

    int n = newData.size();
    int d = featureIdsReference.size();

    DataframeMatrix m = new DataframeMatrix(new MapRealMatrix(n, d), new MapRealVector(n));

    if (newData.isEmpty()) {
        return m;
    }

    boolean extractY = (newData.getYDataType() == TypeInference.DataType.NUMERICAL);

    boolean addConstantColumn = featureIdsReference.containsKey(Dataframe.COLUMN_NAME_CONSTANT);

    int rowId = 0;
    for (Map.Entry<Integer, Record> e : newData.entries()) {
        Integer rId = e.getKey();
        Record r = e.getValue();
        if (recordIdsReference != null) {
            recordIdsReference.put(rId, rowId);
        }

        if (extractY) {
            m.Y.setEntry(rowId, TypeInference.toDouble(r.getY()));
        }

        if (addConstantColumn) {
            m.X.setEntry(rowId, 0, 1.0); //add the constant column
        }
        for (Map.Entry<Object, Object> entry : r.getX().entrySet()) {
            Object feature = entry.getKey();
            Double value = TypeInference.toDouble(entry.getValue());
            if (value != null) {
                Integer featureId = featureIdsReference.get(feature);
                if (featureId != null) {//if the feature exists
                    m.X.setEntry(rowId, featureId, value);
                }
            } //else the X matrix maintains the 0.0 default value
        }
        ++rowId;
    }

    return m;
}

From source file:com.helger.httpclient.HttpClientHelper.java

@Nullable
public static HttpEntity createParameterEntity(@Nullable final Map<String, String> aMap,
        @Nonnull final Charset aCharset) {
    ValueEnforcer.notNull(aCharset, "Charset");
    if (aMap == null || aMap.isEmpty())
        return null;

    try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream(1024)) {
        final URLCodec aURLCodec = new URLCodec();
        boolean bFirst = true;
        for (final Map.Entry<String, String> aEntry : aMap.entrySet()) {
            if (bFirst)
                bFirst = false;//from   w  w  w .  ja v a  2s . c  o  m
            else
                aBAOS.write('&');

            // Key must be present
            final String sKey = aEntry.getKey();
            aURLCodec.encode(sKey.getBytes(aCharset), aBAOS);

            // Value is optional
            final String sValue = aEntry.getValue();
            if (StringHelper.hasText(sValue)) {
                aBAOS.write('=');
                aURLCodec.encode(sValue.getBytes(aCharset), aBAOS);
            }
        }
        return new InputStreamEntity(aBAOS.getAsInputStream());
    }
}

From source file:edu.umass.cs.reconfiguration.reconfigurationpackets.CreateServiceName.java

protected static JSONArray getNameStateJSONArray(Map<String, String> nameStates) throws JSONException {
    if (nameStates != null && !nameStates.isEmpty()) {
        JSONArray jsonArray = new JSONArray();
        for (String name : nameStates.keySet()) {
            JSONObject nameState = new JSONObject();
            nameState.put(Keys.NAME.toString(), name);
            nameState.put(Keys.STATE.toString(), nameStates.get(name));
            jsonArray.put(nameState);/*from  w w  w. j  a  va  2  s. co  m*/
        }
        return jsonArray;
    }
    return null;
}

From source file:com.github.itoshige.testrail.store.SyncManager.java

/**
 * get junit test result from testResultStore.
 * /*from   w ww  .j av  a  2 s . c o m*/
 * @param runId2Class
 * @return
 */
public static Map<String, List<Map<String, Object>>> getJunitTestResults(TestResultStoreKey runId2Class) {
    Map<String, List<Map<String, Object>>> results = TestResultStore.getIns().getResults(runId2Class);
    if (results == null || results.isEmpty() || results.get("results").isEmpty())
        return new HashMap<String, List<Map<String, Object>>>();

    return results;
}

From source file:lt.emasina.resthub.server.factory.MetadataFactory.java

public static JSONObject mapToJSONObject(Map<?, ?> map) {
    if (map == null || map.isEmpty()) {
        return null;
    }//  w ww .  j a v a 2s. c  o m
    return new JSONObject(map);
}

From source file:Main.java

/**
 * Adds a new {@link Element} with multiple attributes to the given parent
 * {@link Element}. The attribute data should be passed in via a {@link Map},
 * with each entry containing an attribute name as key and attribute value as the value.
 * //from  w  w  w .j av  a 2s  .c o  m
 * @param doc
 * @param parent
 * @param name
 * @param attributeData
 * @return
 */
public static Element addElement(Document doc, Node parent, String name, Map<String, String> attributeData) {
    if (doc == null) {
        doc = parent.getOwnerDocument();
    }
    final Element elem = addElement(doc, parent, name);
    if (null != attributeData && !attributeData.isEmpty()) {
        Iterator<Map.Entry<String, String>> iter = attributeData.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = iter.next();
            elem.setAttribute(entry.getKey(), entry.getValue());
        }
    }
    return elem;
}