Example usage for java.util Hashtable size

List of usage examples for java.util Hashtable size

Introduction

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

Prototype

public synchronized int size() 

Source Link

Document

Returns the number of keys in this hashtable.

Usage

From source file:org.apache.torque.util.VillageUtils.java

/**
 * Converts a hashtable to a byte array for storage/serialization.
 *
 * @param  hash  The Hashtable to convert.
 *
 * @return  A byte[] with the converted Hashtable.
 *
 * @throws  Exception  If an error occurs.
 *//* w  ww  . j ava2 s.  com*/
public static byte[] hashtableToByteArray(final Hashtable hash) throws Exception {
    Hashtable saveData = new Hashtable(hash.size());
    byte[] byteArray = null;

    Iterator keys = hash.entrySet().iterator();
    while (keys.hasNext()) {
        Map.Entry entry = (Map.Entry) keys.next();
        if (entry.getValue() instanceof Serializable) {
            saveData.put(entry.getKey(), entry.getValue());
        }
    }

    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    ObjectOutputStream out = null;
    try {
        // These objects are closed in the finally.
        baos = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(baos);
        out = new ObjectOutputStream(bos);

        out.writeObject(saveData);

        out.flush();
        bos.flush();
        baos.flush();
        byteArray = baos.toByteArray();
    } finally {
        close(out);
        close(bos);
        close(baos);
    }
    return byteArray;
}

From source file:Util.java

/*********************************************************************
* Removes duplicate elements from the array.
*********************************************************************/
public static Object[] removeDuplicates(Object[] array)
//////////////////////////////////////////////////////////////////////
{

    Hashtable hashtable = new Hashtable();

    for (int i = 0; i < array.length; i++) {
        hashtable.put(array[i], array[i]);
    }/*from   w w  w.jav  a  2 s . c o m*/

    Object[] newArray = (Object[]) Array.newInstance(array.getClass().getComponentType(), hashtable.size());

    int index = 0;

    Enumeration enumeration = hashtable.elements();

    while (enumeration.hasMoreElements()) {
        newArray[index++] = enumeration.nextElement();
    }

    return newArray;
}

From source file:io.card.development.recording.Recording.java

public static Recording[] parseRecordings(InputStream recordingStream) throws IOException, JSONException {
    Hashtable<String, byte[]> recordingFiles = unzipFiles(recordingStream);
    Hashtable<String, byte[]> manifestFiles = findManifestFiles(recordingFiles);

    int recordingIndex = 0;
    Recording[] recordings = new Recording[manifestFiles.size()];
    Enumeration<String> manifestFilenames = manifestFiles.keys();
    while (manifestFilenames.hasMoreElements()) {
        String manifestFilename = manifestFilenames.nextElement();
        String manifestDirName = manifestFilename.substring(0, manifestFilename.lastIndexOf("/"));
        byte[] manifestData = manifestFiles.get(manifestFilename);

        ManifestEntry[] manifestEntries = buildManifest(manifestDirName, manifestData, recordingFiles);
        recordings[recordingIndex] = new Recording(manifestEntries);
        recordingIndex++;//from   w  w w . j  a  v a  2  s. c  om
    }

    return recordings;
}

From source file:org.wso2.carbon.custom.connector.EJBUtil.java

/**
 * @param messageContext message contest
 * @param operationName  name of the operation
 * @return extract the value's from properties and make its as hashable
 *///from   w w  w .j a  va2 s  .c o m
public static Object[] buildArguments(MessageContext messageContext, String operationName) {
    Hashtable<String, String> argValues = getParameters(messageContext, operationName);
    Set<String> argSet = argValues.keySet();
    Object[] args = new Object[argValues.size()];
    int i = 0;
    for (String aSet : argSet) {
        args[i] = argValues.get(aSet);
        i++;
    }
    return args;
}

From source file:org.squale.jraf.bootstrap.naming.NamingHelper.java

/**
 * Cree un contexte initial/*from w ww .  j  av  a 2 s.c  o  m*/
 * @param jndiUrl url de l'annuaire
 * @param jndiClass classe d'acces
 * @return contexte initial
 * @throws JrafConfigException
 */
public static Context getInitialContext(String jndiUrl, String jndiClass) throws JrafConfigException {

    Hashtable hash = getJndiProperties(jndiUrl, jndiClass);

    if (log.isDebugEnabled()) {
        log.debug("JNDI InitialContext properties:" + hash.size());
    }
    Context lc_context = null;
    try {
        if (hash.size() == 0) {
            lc_context = new InitialContext();
            if (log.isDebugEnabled()) {
                try {
                    log.debug("New initial context" + lc_context.getNameInNamespace());
                } catch (NoInitialContextException exc) {
                    log.debug("No initial context...");
                }
            }
        } else {
            lc_context = new InitialContext(hash);
            if (log.isDebugEnabled()) {
                log.debug("new Initial context:" + lc_context.getNameInNamespace() + " " + hash.size());
            }
        }
        return lc_context;
    } catch (NamingException e) {
        log.error("Impossible de recuperer le contexte JNDI : ", e);
        throw new JrafConfigException("Impossible de recuperer le contexte JNDI : ", e);
    }
}

From source file:com.nokia.carbide.internal.bugreport.model.Communication.java

/**
 * Sends given fields as a bug_report to the server provided by product.
 * @param fields values which are sent to the server
 * @param product product provides e.g. server URL
 * @return bug_id of the added bug_entry
 * @throws RuntimeException if an error occurred. Error can be either some communication error 
 * or error message provided by the server (e.g. invalid password)
 *///from   w ww  .j  av a  2s  .c  o m
public static String sendBugReport(Hashtable<String, String> fields, IProduct product) throws RuntimeException {

    // Nothing to send
    if (fields == null || fields.size() < 1) {
        throw new RuntimeException(Messages.getString("Communication.NothingToSend")); //$NON-NLS-1$
    }

    String bugNumber = ""; //$NON-NLS-1$
    String url = product.getUrl();
    if (url.startsWith("https")) { //$NON-NLS-1$
        // we'll support HTTPS with trusted (i.e. signed) certificates
        //         Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    PostMethod filePost = new PostMethod(url);
    Part[] parts = new Part[fields.size()];
    int i = 0;
    Iterator<Map.Entry<String, String>> it = fields.entrySet().iterator();

    // create parts
    while (it.hasNext()) {
        Map.Entry<String, String> productField = it.next();

        // attachment field
        if (productField.getKey() == FieldsHandler.FIELD_ATTACHMENT) {
            File f = new File(productField.getValue());
            try {
                parts[i] = new FilePart(FieldsHandler.FIELD_DATA, f);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                parts[i] = new StringPart(FieldsHandler.FIELD_DATA,
                        Messages.getString("Communication.NotFound")); //$NON-NLS-1$
            }
            // string field
        } else {
            parts[i] = new StringPart(productField.getKey(), productField.getValue());
        }
        i++;
    }

    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    setProxyData(client, filePost);
    int status = 0;
    String receivedData = ""; //$NON-NLS-1$
    try {
        status = client.executeMethod(filePost);
        receivedData = filePost.getResponseBodyAsString(1024 * 1024);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        filePost.releaseConnection();
    }

    // HTTP status codes: 2xx = Success
    if (status >= 200 && status < 300) {
        // some error occurred in the server side (e.g. invalid password)
        if (receivedData.contains(FieldsHandler.TAG_RESPONSE_ERROR)
                && receivedData.contains(FieldsHandler.TAG_RESPONSE_ERROR_CLOSE)) {
            int beginIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_ERROR)
                    + FieldsHandler.TAG_RESPONSE_ERROR.length();
            int endIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_ERROR_CLOSE);
            String error = receivedData.substring(beginIndex, endIndex);
            error = error.trim();
            throw new RuntimeException(error);
            // bug_entry was added successfully to database, read the bug_number
        } else if (receivedData.contains(FieldsHandler.TAG_RESPONSE_BUG_ID)
                && receivedData.contains(FieldsHandler.TAG_RESPONSE_BUG_ID_CLOSE)) {
            int beginIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_BUG_ID)
                    + FieldsHandler.TAG_RESPONSE_BUG_ID.length();
            int endIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_BUG_ID_CLOSE);
            bugNumber = receivedData.substring(beginIndex, endIndex);
            bugNumber = bugNumber.trim();
            // some unknown error
        } else {
            throw new RuntimeException(Messages.getString("Communication.UnknownError")); //$NON-NLS-1$
        }
        // some HTTP error (status code other than 2xx)
    } else {
        String error = Messages.getString("Communication.HttpError") + status; //$NON-NLS-1$
        throw new RuntimeException(error);
    }

    return bugNumber;
}

From source file:Main.java

public static <ValueType> ArrayList<ValueType> getArrayList(Hashtable<?, ValueType> hashTable) {

    // /////////////////////////////////////////
    // Declarations:
    // /////////////////////////////////////////

    ArrayList<ValueType> newList = null;

    // /////////////////////////////////////////
    // Code://from   ww  w . j  ava  2  s  .  c  o m
    // /////////////////////////////////////////

    newList = new ArrayList<ValueType>(hashTable.size());
    newList.addAll(hashTable.values());

    return newList;

}

From source file:Main.java

public static Hashtable<String, String> getChildHash(Element elem) {
    if (elem == null)
        return null;
    NodeList nl = elem.getChildNodes();
    if (nl == null)
        return null;
    Hashtable<String, String> retlist = new Hashtable<String, String>(nl.getLength());
    for (int n = 0; n < nl.getLength(); n++) {
        Node child = nl.item(n);/*from  w  ww .java 2s.c o m*/
        if (child instanceof Element) {
            Element element = (Element) child;
            String key = element.getTagName();
            String value = getSimpleElementText(element);
            retlist.put(key, value);
        }
    }
    if (retlist.size() == 0)
        return null;
    return retlist;
}

From source file:nl.ellipsis.webdav.server.methods.AbstractMethod.java

/**
 * Send a multistatus element containing a complete error report to the client.
 * If the errorList contains only one error, send the error directly without
 * wrapping it in a multistatus message.
 * //  w  w  w . j a  v  a 2  s.co  m
 * @param req
 *            Servlet request
 * @param resp
 *            Servlet response
 * @param errorList
 *            List of error to be displayed
 */
protected static void sendReport(HttpServletRequest req, HttpServletResponse resp,
        Hashtable<String, Integer> errorList) throws IOException {

    if (errorList.size() == 1) {
        int code = errorList.elements().nextElement();
        HttpStatus s = HttpStatus.valueOf(code);
        String status = s.getReasonPhrase();
        if (status != null && !status.isEmpty()) {
            resp.sendError(code, status);
        } else {
            resp.sendError(code);
        }
    } else {
        resp.setStatus(HttpStatus.MULTI_STATUS.value());

        String absoluteUri = req.getRequestURI();
        // String relativePath = getRelativePath(req);

        XMLWriter generatedXML = new XMLWriter();
        generatedXML.writeXMLHeader();

        generatedXML.writeElement(NS_DAV_PREFIX, NS_DAV_FULLNAME, WebDAVConstants.XMLTag.MULTISTATUS,
                XMLWriter.OPENING);

        Enumeration<String> pathList = errorList.keys();
        while (pathList.hasMoreElements()) {

            String errorPath = (String) pathList.nextElement();
            int errorCode = ((Integer) errorList.get(errorPath)).intValue();

            generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.RESPONSE, XMLWriter.OPENING);

            generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.HREF, XMLWriter.OPENING);
            String toAppend = null;
            if (absoluteUri.endsWith(errorPath)) {
                toAppend = absoluteUri;
            } else if (absoluteUri.contains(errorPath)) {
                int endIndex = absoluteUri.indexOf(errorPath) + errorPath.length();
                toAppend = absoluteUri.substring(0, endIndex);
            }
            if (StringUtils.isEmpty(toAppend)) {
                toAppend = CharsetUtil.FORWARD_SLASH;
            } else if (!toAppend.startsWith(CharsetUtil.FORWARD_SLASH) && !toAppend.startsWith(PROTOCOL_HTTP)) {
                toAppend = CharsetUtil.FORWARD_SLASH + toAppend;
            }
            generatedXML.writeText(errorPath);
            generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.HREF, XMLWriter.CLOSING);
            generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.STATUS, XMLWriter.OPENING);
            HttpStatus s = HttpStatus.valueOf(errorCode);
            generatedXML.writeText("HTTP/1.1 " + errorCode + " " + s.getReasonPhrase());
            generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.STATUS, XMLWriter.CLOSING);

            generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.RESPONSE, XMLWriter.CLOSING);

        }

        generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.MULTISTATUS, XMLWriter.CLOSING);

        Writer writer = resp.getWriter();
        writer.write(generatedXML.toString());
        writer.close();
    }
}

From source file:Main.java

public static Hashtable<String, Element> getChildHash(Element elem, String elementName, String attrName) {
    if (elem == null)
        return null;
    NodeList nl = elem.getChildNodes();
    if (nl == null)
        return null;
    Hashtable<String, Element> retlist = new Hashtable<String, Element>(100);
    for (int n = 0; n < nl.getLength(); n++) {
        Node child = nl.item(n);/*from   ww  w  . j av  a2 s  . c om*/
        if (child instanceof Element) {
            Element element = (Element) child;
            if (!elementName.equals(element.getTagName()))
                continue;
            String keyValue = element.getAttribute(attrName);
            if (keyValue == null)
                continue;
            retlist.put(keyValue, element);
        }
    }
    if (retlist.size() == 0)
        return null;
    return retlist;
}