Example usage for java.util HashMap size

List of usage examples for java.util HashMap size

Introduction

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

Prototype

int size

To view the source code for java.util HashMap size.

Click Source Link

Document

The number of key-value mappings contained in this map.

Usage

From source file:edu.gmu.cs.sim.util.media.chart.PieChartGenerator.java

double[] amounts(HashMap map, String[] revisedLabels) {
    // Extract amounts
    double[] amounts = new double[map.size()];
    for (int i = 0; i < amounts.length; i++) {
        amounts[i] = ((Double) (map.get(revisedLabels[i]))).doubleValue();
    }//from w w w.ja  v  a 2s.c  o  m
    return amounts;
}

From source file:com.netcrest.pado.tools.pado.command.get.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void run(CommandLine commandLine, String command) throws Exception {
    String path = commandLine.getOptionValue("path");
    String bufferName = commandLine.getOptionValue("buffer");
    List<String> argList = commandLine.getArgList();

    if (path != null && bufferName != null) {
        PadoShell.printlnError(this, "Specifying both path and buffer not allowed. Only one option allowed.");
        return;//from   w  ww  .ja v a  2  s  .  c  o  m
    }
    if (path == null && bufferName == null) {
        path = padoShell.getCurrentPath();
    }

    if (path != null) {

        if (commandLine.getArgList().size() < 2) {
            PadoShell.printlnError(this, "Invalid command. Key or key fields must be specified.");
            return;
        }
        String input = (String) commandLine.getArgList().get(1);
        Object key = null;
        Object value;
        if (input.startsWith("'")) {
            int lastIndex = -1;
            if (input.endsWith("'") == false) {
                lastIndex = input.length();
            } else {
                lastIndex = input.lastIndexOf("'");
            }
            if (lastIndex <= 1) {
                PadoShell.printlnError(this, "Invalid key. Empty string not allowed.");
                return;
            }
            key = input.subSequence(1, lastIndex); // lastIndex exclusive
        } else {
            key = ObjectUtil.getPrimitive(padoShell, input, false);
            if (key == null) {
                key = padoShell.getQueryKey(argList, 1);
            }
        }
        if (key == null) {
            return;
        }
        // long startTime = System.currentTimeMillis();
        if (padoShell.isShowTime() && padoShell.isShowResults()) {
            TimerUtil.startTimer();
        }

        String fullPath = padoShell.getFullPath(path);
        String gridPath = GridUtil.getChildPath(fullPath);
        String gridId = SharedCache.getSharedCache().getGridId(fullPath);
        IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog()
                .newInstance(IGridMapBiz.class, gridPath);
        gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);
        value = gridMapBiz.get(key);

        if (value == null) {
            PadoShell.printlnError(this, "Key not found.");
            return;
        }

        HashMap map = new HashMap();
        map.put(key, value);
        if (padoShell.isShowResults()) {
            PrintUtil.printEntries(map, map.size(), null);
        }

    } else {
        // Get key from the buffer
        BufferInfo bufferInfo = SharedCache.getSharedCache().getBufferInfo(bufferName);
        if (bufferInfo == null) {
            PadoShell.printlnError(this, bufferName + ": Buffer undefined.");
            return;
        }
        String gridId = bufferInfo.getGridId();
        String gridPath = bufferInfo.getGridPath();
        if (gridId == null || gridPath == null) {
            PadoShell.printlnError(this, bufferName + ": Invalid buffer. This buffer does not contain keys.");
            return;
        }
        Map<Integer, Object> keyMap = bufferInfo.getKeyMap(argList, 1);
        if (keyMap.size() > 0) {
            IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog()
                    .newInstance(IGridMapBiz.class, gridPath);
            gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);
            Map map = gridMapBiz.getAll(keyMap.values());
            PrintUtil.printEntries(map, map.size(), null);
        }
    }
}

From source file:at.ac.tuwien.ifs.lupu.LangDetFilterFactory.java

@Override
public void inform(ResourceLoader loader) throws IOException {
    try {// w w w  .  j  a  va  2s . c  o  m
        LOG.log(Level.ALL, "in inform");
        List<String> files = splitFileNames(languageFiles);
        if (files.size() > 0) {
            languages = new HashSet<>();
            for (String file : files) {
                List<String> lines = getLines(loader, file.trim());
                System.out.println(lines);
                List<Language> typesLines = lines.stream().map(line -> readLanguage(line)).collect(toList());
                languages.addAll(typesLines);
                LOG.log(Level.ALL, "languages:{0}", languages.size());
            }
        }
        HashMap priorMap = new HashMap();
        detector = DetectorFactory.create();
        languages.stream().forEach((language) -> {
            priorMap.put(language.lang, language.prob);
        });
        LOG.log(Level.ALL, "priorMap size:{0}", priorMap.size());
        detector.setPriorMap(priorMap);
    } catch (LangDetectException ex) {
        Logger.getLogger(LangDetFilterFactory.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:cc.kune.core.server.manager.I18nManagerDefaultTest.java

/**
 * Gets the non existent translation in any lang returns key.
 * /*from w  w  w.  ja  v a  2 s  .c om*/
 * @return the non existent translation in any lang returns key
 */
@Test
public void getNonExistentTranslationInAnyLangReturnsKey() {
    HashMap<String, String> map = translationManager.getLexicon("en");
    HashMap<String, String> map2 = translationManager.getLexicon("af");
    final int initialSize = map.size();
    final int initialSize2 = map2.size();

    final String translation = translationManager.getTranslation("es", "Foo foo foo", "note for translators");
    final String translation2 = translationManager.getTranslation("af", "Foo foo foo", "note for translators");

    assertEquals(I18nTranslation.UNTRANSLATED_VALUE, translation);
    assertEquals(I18nTranslation.UNTRANSLATED_VALUE, translation2);

    map = translationManager.getLexicon("en");
    map2 = translationManager.getLexicon("af");
    final int newSize = map.size();
    final int newSize2 = map2.size();

    assertEquals(initialSize + 1, newSize);
    assertEquals(initialSize2 + 1, newSize2);
}

From source file:hd3gtv.mydmam.useraction.fileoperation.UAFileOperationDelete.java

@Override
public void process(JobProgression progression, UserProfile userprofile, UAConfigurator user_configuration,
        HashMap<String, SourcePathIndexerElement> source_elements) throws Exception {
    Log2Dump dump = new Log2Dump();
    dump.add("user", userprofile.key);

    progression.updateStep(1, source_elements.size());

    ArrayList<File> items_to_delete = new ArrayList<File>();
    for (Map.Entry<String, SourcePathIndexerElement> entry : source_elements.entrySet()) {
        progression.incrStep();/*from   w  w  w. j a va2  s  . co  m*/
        File current_element = Explorer.getLocalBridgedElement(entry.getValue());
        CopyMove.checkExistsCanRead(current_element);
        CopyMove.checkIsWritable(current_element.getParentFile());

        if (current_element.isFile() | FileUtils.isSymlink(current_element)) {
            if (current_element.delete() == false) {
                Log2.log.debug("Can't delete correctly file", dump);
                throw new IOException("Can't delete correctly file: " + current_element.getPath());
            }
            if (stop) {
                return;
            }
        } else {
            items_to_delete.clear();
            items_to_delete.add(current_element);
            boolean can_delete_all = true;
            recursivePath(current_element, items_to_delete);

            progression.updateProgress(1, items_to_delete.size());
            for (int pos_idel = items_to_delete.size() - 1; pos_idel > -1; pos_idel--) {
                progression.updateProgress(items_to_delete.size() - pos_idel, items_to_delete.size());
                if (items_to_delete.get(pos_idel).delete() == false) {
                    dump.add("item", items_to_delete.get(pos_idel));
                    can_delete_all = false;
                }
                if (stop) {
                    return;
                }
            }

            if (can_delete_all == false) {
                Log2.log.debug("Can't delete correctly multiple files", dump);
                throw new IOException("Can't delete multiple files from: " + current_element.getPath());
            }
        }

        if (stop) {
            return;
        }

        ElasticsearchBulkOperation bulk = Elasticsearch.prepareBulk();

        /**
         * Delete mtds
         */
        Container container = ContainerOperations.getByPathIndexId(entry.getKey());
        if (container != null) {
            ContainerOperations.requestDelete(container, bulk);
            RenderedFile.purge(entry.getKey());
        }

        explorer.deleteStoragePath(bulk, Arrays.asList(entry.getValue()));

        bulk.terminateBulk();

        if (stop) {
            return;
        }
    }
}

From source file:it.cnr.icar.eric.service.catalogingTest.cppaCataloging.CPPACataloging.java

public SOAPElement catalogContent(SOAPElement partCatalogContentRequest) throws RemoteException {
    try {//from  w  w w. j a  v  a2s  . co  m
        if (log.isDebugEnabled()) {
            printNodeToConsole(partCatalogContentRequest);
        }

        final HashMap<String, DataHandler> repositoryItemDHMap = getRepositoryItemDHMap();

        if (log.isDebugEnabled()) {
            log.debug("Attachments: " + repositoryItemDHMap.size());
        }

        Object requestObj = getBindingObjectFromNode(partCatalogContentRequest);

        if (!(requestObj instanceof CatalogContentRequest)) {
            throw new Exception(
                    "Wrong response received from validation service.  Expected CatalogContentRequest, got: "
                            + partCatalogContentRequest.getElementName().getQualifiedName());
        }

        ccReq = (CatalogContentRequest) requestObj;

        IdentifiableType originalContentIT = ccReq.getOriginalContent().getIdentifiable().get(0).getValue();
        IdentifiableType invocationControlIT = ccReq.getInvocationControlFile().get(0);

        DataHandler invocationControlDH = repositoryItemDHMap.get(invocationControlIT.getId());

        if (log.isDebugEnabled()) {
            log.debug("originalContentIT id: " + originalContentIT.getId());
            log.debug("invocationControlIT id: " + invocationControlIT.getId());
        }

        StreamSource invocationControlSrc = new StreamSource(invocationControlDH.getInputStream());

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(invocationControlSrc);

        transformer.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                Source source = null;
                try {
                    // Should this check that href is UUID URN first?
                    source = new StreamSource((repositoryItemDHMap.get(href)).getInputStream());
                } catch (Exception e) {
                    source = null;
                }

                return source;
            }
        });
        transformer.setErrorListener(new ErrorListener() {
            public void error(TransformerException exception) throws TransformerException {
                log.info(exception);
            }

            public void fatalError(TransformerException exception) throws TransformerException {
                log.error(exception);
                throw exception;
            }

            public void warning(TransformerException exception) throws TransformerException {
                log.info(exception);
            }
        });

        //Set respository item as parameter
        transformer.setParameter("repositoryItem", originalContentIT.getId());

        StringWriter sw = new StringWriter();
        transformer.transform(new JAXBSource(jaxbContext, originalContentIT), new StreamResult(sw));

        ccResp = cmsFac.createCatalogContentResponse();

        RegistryObjectListType catalogedMetadata = (RegistryObjectListType) getUnmarshaller()
                .unmarshal(new StreamSource(new StringReader(sw.toString())));
        RegistryObjectListType roList = rimFac.createRegistryObjectListType();
        ccResp.setCatalogedContent(roList);
        // FIXME: Setting catalogedMetadata as CatalogedContent results in incorrect serialization.
        roList.getIdentifiable().addAll(catalogedMetadata.getIdentifiable());

        ccResp.setStatus(CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);

        ccRespElement = getSOAPElementFromBindingObject(ccResp);

        // Copy request's attachments to response to exercise attachment-processing code on client.
        MessageContext mc = servletEndpointContext.getMessageContext();
        mc.setProperty(com.sun.xml.rpc.server.ServerPropertyConstants.SET_ATTACHMENT_PROPERTY,
                (Collection<?>) mc
                        .getProperty(com.sun.xml.rpc.server.ServerPropertyConstants.GET_ATTACHMENT_PROPERTY));

    } catch (Exception e) {
        throw new RemoteException("Could not create response.", e);
    }

    return ccRespElement;
}

From source file:models.data.providers.LogProvider.java

/**
 * Read JSON log to the hashmap. From file back to the memory.
 * /*from w w w. j  a  v a2s. co m*/
 * @param nodeGroupType
 * @param agentCommandType
 * @param timeStamp
 * @return
 */
public static Map<String, NodeData> readJsonLogToNodeDataMap(String nodeGroupType, String agentCommandType,
        String timeStamp) {

    String logContent = readJsonLog(nodeGroupType, agentCommandType, timeStamp);
    HashMap<String, NodeData> nodeDataMapValid = null;
    if (logContent == null) {
        models.utils.LogUtils.printLogError("Error logContent is null in readJsonLogToNodeDataMap ");

        return nodeDataMapValid;
    }

    try {

        // Great solution: very challenging part: 20130523
        // http://stackoverflow.com/questions/2779251/convert-json-to-hashmap-using-gson-in-java
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
        Gson gson = gsonBuilder.create();
        Object mapObject = gson.fromJson(logContent, Object.class);
        nodeDataMapValid = (HashMap<String, NodeData>) (mapObject);

        if (VarUtils.IN_DETAIL_DEBUG) {
            models.utils.LogUtils.printLogNormal(nodeDataMapValid.size() + "");
        }

    } catch (Throwable e) {
        e.printStackTrace();
    }

    return nodeDataMapValid;
}

From source file:ru.apertum.qsystem.reports.formirovators.DistributionWaitDay.java

@Override
public String validate(String driverClassName, String url, String username, String password,
        HttpRequest request, HashMap<String, String> params) {
    //   ?  /*from w  w w. j  a va  2s .  c  o m*/
    QLog.l().logger().trace("?  \"" + params.toString() + "\".");
    if (params.size() == 1) {
        Date date;
        String sdate;
        try {
            date = Uses.format_dd_MM_yyyy.parse(params.get("date"));
            sdate = (new java.text.SimpleDateFormat("yyyy-MM-dd")).format(date);
        } catch (ParseException ex) {
            return "<br>  ! ? ?   (..).";
        }
        paramMap.put("sdate", sdate);
        paramMap.put("date", date);

    } else {
        return "<br>  !";
    }
    return null;// ? 
}

From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java

public synchronized static InputStream doPost(String urlstring, String queryString, String separator,
        Map<String, String> additionalHeaders, StringBuffer charsetb) throws HttpException, IOException {
    System.err.println("posting to: " + urlstring + ". query string: " + queryString);
    HashMap<String, String> query = parseQueryString(queryString, separator);
    HttpClient client = getClient();/* ww w.j a v  a 2s .  co m*/

    URL url = new URL(urlstring);
    int port = url.getPort();
    if (port == -1) {
        if (url.getProtocol().equalsIgnoreCase("http")) {
            port = 80;
        }
        if (url.getProtocol().equalsIgnoreCase("https")) {
            port = 443;
        }
    }

    client.getHostConfiguration().setHost(url.getHost(), port, url.getProtocol());
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    final PostMethod post = new PostMethod(url.getFile());
    addHeaders(additionalHeaders, post);
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.setRequestHeader("Accept", "*/*");
    // Prepare login parameters
    NameValuePair[] valuePairs = new NameValuePair[query.size()];

    int counter = 0;

    for (String key : query.keySet()) {
        //System.out.println("Adding pair: "+key+": "+query.get(key));
        valuePairs[counter++] = new NameValuePair(key, query.get(key));

    }

    post.setRequestBody(valuePairs);
    //authpost.setRequestEntity(new StringRequestEntity(requestEntity));

    client.executeMethod(post);

    int statuscode = post.getStatusCode();
    InputStream toret = null;
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = post.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }

        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    } else {
        charsetb.append(post.getResponseCharSet());
        final InputStream in = post.getResponseBodyAsStream();

        toret = new InputStream() {

            @Override
            public int read() throws IOException {
                return in.read();
            }

            @Override
            public void close() {
                post.releaseConnection();
            }

        };

    }

    return toret;
}

From source file:com.marketcloud.marketcloud.Utilities.java

/**
 * Returns a list of objects that comply with the given query.
 *
 * @param baseURL endpoint of the database
 * @param token a session token that identifies the user
 * @param m HashMap containing a list of filters
 * @return a JSONArray containing a list of objects that comply with the given filter
 *//*from  ww w.  j a  v  a 2 s. c  om*/
public JSONObject list(final String baseURL, String token, final HashMap<String, Object> m)
        throws ExecutionException, InterruptedException, JSONException {

    String url = baseURL.substring(0, baseURL.length() - 1) + "?";

    //Concatenate the filters to the base URL

    int index = 0;
    int max = m.size() - 1;

    for (Map.Entry<String, Object> entry : m.entrySet()) {

        url += entry.getKey() + "=" + entry.getValue();

        if (index != max)
            url += "&";

        index++;
    }

    return new Connect(context).run("get", url, publicKey + ":" + token);
}