Example usage for java.util HashMap isEmpty

List of usage examples for java.util HashMap isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

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

Usage

From source file:mx.org.cedn.avisosconagua.engine.processors.Init.java

/**
 * Updates selected areas in the google map displayed in the web form.
 * @param nuevo new advice properties/*  w  w w  . j a  v a2  s  . c o m*/
 * @param anterior previous advice properties
 */
private void procesaAreas(HashMap<String, String> nuevo, BasicDBObject anterior) {
    if (null != anterior) {
        HashMap<String, String> cambios = new HashMap<>();
        for (String key : nuevo.keySet()) {
            if (key.startsWith("area-")) {
                String states = "states" + key.substring(4);
                String municipalities = "municipalities" + key.substring(4);
                if (null == nuevo.get(states) || null == nuevo.get(municipalities)) {
                    if (((String) nuevo.get(key)).equals(anterior.get(key))) {
                        if (null != anterior.get(states)) {
                            cambios.put(states, (String) anterior.get(states));
                        }
                        if (null != anterior.get(municipalities)) {
                            cambios.put(municipalities, (String) anterior.get(municipalities));
                        }
                    }
                }

            }
        }
        if (!cambios.isEmpty()) {
            nuevo.putAll(cambios);
        }
    }
}

From source file:org.carrot2.core.Document.java

@ElementMap(entry = "field", key = "key", attribute = true, inline = true, required = false)
private HashMap<String, SimpleXmlWrapperValue> getOtherFieldsXml() {
    final HashMap<String, SimpleXmlWrapperValue> otherFieldsForSerialization;
    synchronized (this) {
        otherFieldsForSerialization = MapUtils.asHashMap(SimpleXmlWrappers.wrap(fields));
    }/*from   w  ww . j  av a2 s.c o m*/
    otherFieldsForSerialization.remove(TITLE);
    otherFieldsForSerialization.remove(SUMMARY);
    otherFieldsForSerialization.remove(CONTENT_URL);
    otherFieldsForSerialization.remove(SOURCES);
    otherFieldsForSerialization.remove(LANGUAGE);
    otherFieldsForSerialization.remove(SCORE);
    fireSerializationListeners(otherFieldsForSerialization);
    return otherFieldsForSerialization.isEmpty() ? null : otherFieldsForSerialization;
}

From source file:org.apache.usergrid.rest.applications.ServiceResource.java

private JSONWithPadding executeMultiPart(UriInfo ui, String callback, FormDataMultiPart multiPart,
        ServiceAction serviceAction) throws Exception {

    // collect form data values
    List<BodyPart> bodyParts = multiPart.getBodyParts();
    HashMap<String, Object> data = new HashMap<String, Object>();
    for (BodyPart bp : bodyParts) {
        FormDataBodyPart bodyPart = (FormDataBodyPart) bp;
        if (bodyPart.getMediaType().equals(MediaType.TEXT_PLAIN_TYPE)) {
            data.put(bodyPart.getName(), bodyPart.getValue());
        } else {/*  w ww.  jav  a 2  s  .co m*/
            LOG.info("skipping bodyPart {} of media type {}", bodyPart.getName(), bodyPart.getMediaType());
        }
    }

    FormDataBodyPart fileBodyPart = multiPart.getField(FILE_FIELD_NAME);

    if (data.isEmpty() && fileBodyPart != null) { // ensure entity is created even if there are no properties
        data.put(AssetUtils.FILE_METADATA, new HashMap());
    }

    // process entity
    ApiResponse response = createApiResponse();
    response.setAction(serviceAction.name().toLowerCase());
    response.setApplication(services.getApplication());
    response.setParams(ui.getQueryParameters());
    ServicePayload payload = getPayload(data);
    ServiceResults serviceResults = executeServiceRequest(ui, response, serviceAction, payload);

    // process file part
    if (fileBodyPart != null) {
        InputStream fileInput = ((BodyPartEntity) fileBodyPart.getEntity()).getInputStream();
        if (fileInput != null) {
            Entity entity = serviceResults.getEntity();
            EntityManager em = emf.getEntityManager(getApplicationId());
            binaryStore.write(getApplicationId(), entity, fileInput);
            em.update(entity);
            serviceResults.setEntity(entity);
        }
    }

    return new JSONWithPadding(response, callback);
}

From source file:de.unibi.techfak.bibiserv.web.beans.session.AbstractCloudInputBean.java

public void getS3ObjectList() {
    resetValidated();//  ww w.j av a 2 s.  c  o  m

    //set new Data
    selectedData.setBucket(selected_item_bucket);

    if (selected_item_bucket.isEmpty()) {
        return;
    }

    // load the data, an error might occur
    HashMap<Integer, String> validationMessage = awsbean.loadS3ObjectList(selectedData.getBucket());
    throwFacesMessage(validationMessage, getId() + "_msg_browse");
    if (!validationMessage.isEmpty()) {
        return;
    }
    // no error, get data
    displayBucketLocation();
    itemlist_objects = awsbean.getS3ObjectList(selectedData.getBucket());
}

From source file:de.hbz.lobid.helper.CompareJsonMaps.java

public boolean writeFileAndTestJson(final JsonNode actual, final JsonNode expected) {
    // generated data to map
    final HashMap<String, String> actualMap = new HashMap<>();
    extractFlatMapFromJsonNode(actual, actualMap);
    // expected data to map
    final HashMap<String, String> expectedMap = new HashMap<>();
    extractFlatMapFromJsonNode(expected, expectedMap);
    CompareJsonMaps.logger.debug("\n##### remove good entries ###");
    Iterator<String> it = actualMap.keySet().iterator();
    removeContext(it);/*from www  .  jav a  2  s  . c om*/
    it = expectedMap.keySet().iterator();
    removeContext(it);
    for (final Entry<String, String> e : expectedMap.entrySet()) {
        CompareJsonMaps.logger.debug("Trying to remove " + e.getKey() + "...");
        if (!actualMap.containsKey(e.getKey())) {
            CompareJsonMaps.logger.warn("At least this element is missing in actual: " + e.getKey());
            return false;
        }
        if (e.getKey().endsWith("Order]")) {
            handleOrderedValues(actualMap, e);
        } else {
            handleUnorderedValues(actualMap, e);
        }
    }
    if (!actualMap.isEmpty()) {
        CompareJsonMaps.logger.warn("Fail - no Equality! These keys/values were NOT expected:");
        actualMap.forEach((key, val) -> CompareJsonMaps.logger.warn("KEY=" + key + " VALUE=" + val));
    } else
        CompareJsonMaps.logger.info("Succeeded - resources are equal");
    return actualMap.size() == 0;
}

From source file:au.org.ala.layers.dao.ObjectDAOImpl.java

@Override
public Objects getObjectByPid(String pid) {
    logger.info("Getting object info for pid = " + pid);
    String sql = "select o.pid, o.id, o.name, o.desc as description, o.fid as fid, f.name as fieldname, "
            + "o.bbox, o.area_km from objects o, fields f where o.pid = ? and o.fid = f.id";
    List<Objects> l = jdbcTemplate.query(sql, ParameterizedBeanPropertyRowMapper.newInstance(Objects.class),
            pid);//from   w w w.j a  v a 2s . com

    updateObjectWms(l);

    // get grid classes
    if ((l == null || l.isEmpty()) && pid.length() > 0) {
        // grid class pids are, 'layerPid:gridClassNumber'
        try {
            String[] s = pid.split(":");
            if (s.length >= 2) {
                int n = Integer.parseInt(s[1]);
                IntersectionFile f = layerIntersectDao.getConfig().getIntersectionFile(s[0]);
                if (f != null && f.getClasses() != null) {
                    GridClass gc = f.getClasses().get(n);
                    if (gc != null) {
                        Objects o = new Objects();
                        o.setPid(pid);
                        o.setId(pid);
                        o.setName(gc.getName());
                        o.setFid(f.getFieldId());
                        o.setFieldname(f.getFieldName());

                        if (f.getType().equals("a") || s.length == 2) {
                            o.setBbox(gc.getBbox());
                            o.setArea_km(gc.getArea_km());
                            o.setWmsurl(getGridClassWms(f.getLayerName(), gc));
                        } else {
                            HashMap<String, Object> map = getGridIndexEntry(
                                    f.getFilePath() + File.separator + s[1], s[2]);
                            if (!map.isEmpty()) {
                                o.setBbox("POLYGON(" + map.get("minx") + " " + map.get("miny") + ","
                                        + map.get("minx") + " " + map.get("maxy") + "," + map.get("maxx") + " "
                                        + map.get("maxy") + "," + map.get("maxx") + " " + map.get("miny") + ","
                                        + map.get("minx") + " " + map.get("miny") + ")");

                                o.setArea_km(((Float) map.get("area")).doubleValue());

                                o.setWmsurl(getGridPolygonWms(f.getLayerName(), Integer.parseInt(s[2])));
                            }
                        }

                        l.add(o);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    if (l.size() > 0) {
        return l.get(0);
    } else {
        return null;
    }
}

From source file:Controladores.controladorSprint.java

@RequestMapping(value = "salvar-sprint-restrito", produces = "application/json; charset=UTF-8")
@ResponseBody/*from w  ww . ja  v  a 2 s.  c o m*/
public String salvarSprint(Sprint sprint, BindingResult result, HttpSession sessao, HttpServletRequest request,
        String operacao) {

    try {
        HashMap<String, String> erros = new HashMap<String, String>();

        if (sprint.getNome().trim().length() == 0) {
            erros.put("erroNomeSprint", "Informe o nome do modulo a ser desenvolvido");
        }
        if (sprint.getDescricao().trim().length() == 0) {
            erros.put("erroDescricaoSprint", "Informe a descrio do modulo");
        }

        String projetoId = request.getParameter("projetoId");
        String sitsprint = request.getParameter("sitsprint");

        if (projetoId != "") {
            Projeto p = new Projeto();
            p.setId(Integer.parseInt(projetoId));
            sprint.setProjeto(p);
        }

        if (!sitsprint.equalsIgnoreCase("") & !sitsprint.equalsIgnoreCase("0")) {
            Sitsprint sit = new Sitsprint();
            sit.setId(Integer.parseInt(sitsprint));
            sprint.setSitsprint(sit);
        } else {
            erros.put("erroSitSprint", "Selecione a situao do sprint");
        }

        if (erros.isEmpty()) {
            if (operacao.equalsIgnoreCase("I")) {
                sprint.setDtcriacao(new Date());
            } else {
                sprint.setDtalteracao(new Date());
            }

            //sprint.setProjeto(projeto);
            SprintDAO.salvarSprint(sprint);
        }

        Gson gson = new Gson();
        JsonObject myObj = new JsonObject();

        myObj.addProperty("sucesso", erros.isEmpty());
        JsonElement objetoErrosEmJson = gson.toJsonTree(erros);
        myObj.add("erros", objetoErrosEmJson);

        return myObj.toString();
    } catch (Exception erro) {
        return null;
    }
}

From source file:ilcc.ccgparser.incderivation.RevInc.java

private Pair<CCGJTreeNode, ArcJAction> checkAndApplyAction(CCGJTreeNode left, CCGJTreeNode right, String ccgKey,
        HashMap<Integer, CCGNodeDepInfo> nccgNodeDeps) {
    Pair<CCGJTreeNode, ArcJAction> pair;
    CCGJTreeNode result;/*from   w w  w .jav a  2s.  c  om*/
    SRAction sract;
    RuleType rule;

    String key1 = left.getConllNode().getNodeId() + "--" + right.getConllNode().getNodeId(),
            key2 = right.getConllNode().getNodeId() + "--" + left.getConllNode().getNodeId();
    CCGJRuleInfo info = checkRules(left, right, ccgKey);
    if (info != null) {
        updateHeadDirection(left, right, info, ccgKey);
        HashMap<String, CCGDepInfo> depsMap = new HashMap<>();
        Commons.getDepsMap(left.getCCGcat(), right.getCCGcat(), info.getResultCat(), depsMap);
        if (ftrue || (checkWithGoldDeps(depsMap) && !depsMap.isEmpty())
                || (depsMap.isEmpty() && (drvDeps.containsKey(key1) || drvDeps.containsKey(key2)
                        || (Utils.isPunct(left.getCCGcat()) || Utils.isPunct(right.getCCGcat()))))) {
            sract = info.getHeadDir() ? SRAction.RR : SRAction.RL;
            updateccgNodeDeps(left, right, sract, nccgNodeDeps, depsMap, false);
            result = applyAction(left, right, info, depsMap, sract);
            actionMap.put(sract, actionMap.get(sract) + 1);

            if (info.getCombinator() == RuleType.other)
                rule = findCombinator(info.getLeftCat(), info.getRightCat(), info.getResultCat().toString());
            else
                rule = info.getCombinator();
            ArcJAction act = ArcJAction.make(sract, 0, info.getResultCat().toString(), rule);
            pair = new ImmutablePair(result, act);
        } else {
            pair = checkSpecialRulesDep(left, right, ccgKey, nccgNodeDeps);
            if (pair != null && pair.getLeft() != null)
                stack.push(pair.getLeft());
        }
    } else //if(right.getCCGcat().toString().endsWith("[conj]"))
    {
        pair = checkSpecialRulesDep(left, right, ccgKey, nccgNodeDeps);
        if (pair != null && pair.getLeft() != null)
            stack.push(pair.getLeft());
    }
    return pair;
}

From source file:org.telegram.ui.Components.ImageUpdater.java

public void openSearch() {
    if (parentFragment == null) {
        return;/*w w  w .j a  v  a2  s .  com*/
    }
    final HashMap<Object, Object> photos = new HashMap<>();
    final ArrayList<Object> order = new ArrayList<>();
    PhotoPickerActivity fragment = new PhotoPickerActivity(0, null, photos, order, new ArrayList<>(), 1, false,
            null);
    fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() {

        private boolean sendPressed;

        @Override
        public void selectedPhotosChanged() {

        }

        private void sendSelectedPhotos(HashMap<Object, Object> photos, ArrayList<Object> order) {

        }

        @Override
        public void actionButtonPressed(boolean canceled) {
            if (photos.isEmpty() || delegate == null || sendPressed || canceled) {
                return;
            }
            sendPressed = true;

            ArrayList<SendMessagesHelper.SendingMediaInfo> media = new ArrayList<>();
            for (int a = 0; a < order.size(); a++) {
                Object object = photos.get(order.get(a));
                SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo();
                media.add(info);
                if (object instanceof MediaController.SearchImage) {
                    MediaController.SearchImage searchImage = (MediaController.SearchImage) object;
                    if (searchImage.imagePath != null) {
                        info.path = searchImage.imagePath;
                    } else {
                        info.searchImage = searchImage;
                    }
                    info.caption = searchImage.caption != null ? searchImage.caption.toString() : null;
                    info.entities = searchImage.entities;
                    info.masks = !searchImage.stickers.isEmpty() ? new ArrayList<>(searchImage.stickers) : null;
                    info.ttl = searchImage.ttl;
                }
            }
            didSelectPhotos(media);
        }
    });
    fragment.setInitialSearchString(delegate.getInitialSearchString());
    parentFragment.presentFragment(fragment);
}

From source file:com.yahoo.ycsb.workloads.MailAppCassandraWorkload.java

public void doTransactionPopReadOnly(DB db) throws WorkloadException {
    //choose a random key
    int keynum = nextKeynum();

    String keynameInbox = buildKeyName(keynum, inboxSuffix);

    HashSet<String> fields = null;

    HashSet<String> counterColumnNames = new HashSet<String>();
    counterColumnNames.add(messagecountfieldkey);
    counterColumnNames.add(mailboxsizefieldkey);

    HashMap<String, ByteIterator> counterResult = new HashMap<String, ByteIterator>();
    HashMap<String, ByteIterator> uidlResult = new HashMap<String, ByteIterator>();
    HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();

    HashSet<String> retrievedMessageIDList = new HashSet<String>();
    long st = System.nanoTime();

    //read counter Table (POP3 STAT Command)
    db.read(incrementTag + countertable, keynameInbox, counterColumnNames, counterResult);
    if (counterResult.isEmpty()) {
        long en = System.nanoTime();
        Measurements.getMeasurements().measure("POP_ReadOnly-Transaction", (int) ((en - st) / 1000));
        return;// w  ww . j  a v  a 2 s  .co  m
    }
    //get UIDL/List-List
    db.read(sizetable, keynameInbox, fields, uidlResult);
    //Retr x Messages
    int retrieveCount = getMessageRetrieveCountGenerator(0, uidlResult.size()).nextInt();
    for (int i = 0; i < retrieveCount; i++) {
        //request one message by key and single column name
        String columnName = uidlResult.entrySet().iterator().next().getKey();
        HashSet<String> requestColumn = new HashSet<String>();
        requestColumn.add(columnName);
        db.read(mailboxtable, keynameInbox, requestColumn, result);
        retrievedMessageIDList.add(columnName);
    }
    long en = System.nanoTime();
    Measurements.getMeasurements().measure("POP_ReadOnly-Transaction", (int) ((en - st) / 1000));

}