Example usage for java.util Hashtable get

List of usage examples for java.util Hashtable get

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public synchronized V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:edu.ku.brc.specify.tasks.subpane.JasperReportsCache.java

/**
 * Checks to see if any files in the database need to be copied to the database. A file may not
 * exist or be out of date./* w w  w . j  a v a  2 s  .c o m*/
 */
protected static void refreshCacheFromDatabase(final String mimeType) {
    File cachePath = getCachePath();

    Hashtable<String, File> hash = new Hashtable<String, File>();
    for (File f : cachePath.listFiles()) {
        //log.info("Report Cache File["+f.getName()+"]");
        hash.put(f.getName(), f);
    }

    for (AppResourceIFace ap : AppContextMgr.getInstance().getResourceByMimeType(mimeType)) {
        // Check to see if the resource or file has changed.
        boolean updateCache = false;
        File fileFromJasperCache = hash.get(ap.getName());
        if (fileFromJasperCache == null) {
            updateCache = true;

        } else {
            Date fileDate = new Date(fileFromJasperCache.lastModified());
            Timestamp apTime = ap.getTimestampModified() == null ? ap.getTimestampCreated()
                    : ap.getTimestampModified();
            updateCache = apTime == null || fileDate.getTime() < apTime.getTime();
        }

        // If it has changed then copy the contents into the cache and delete the compiled file
        // so it forces it to be recompiled.
        if (updateCache) {
            File localFilePath = new File(cachePath.getAbsoluteFile() + File.separator + ap.getName());
            try {
                XMLHelper.setContents(localFilePath, ap.getDataAsString());

                File compiledFile = getCompiledFile(localFilePath);
                if (compiledFile.exists()) {
                    compiledFile.delete();
                }

            } catch (Exception ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(JasperReportsCache.class, ex);
                throw new RuntimeException(ex);
            }
        }
    }
}

From source file:edu.ku.brc.af.ui.forms.FormHelper.java

public static void dumpDataObj(final DataProviderSessionIFace session, final Object dataObj,
        final Hashtable<Class<?>, Boolean> clsHash, final int level) {
    if (dataObj == null || clsHash.get(dataObj.getClass()) != null)
        return;//from w ww.  j  a  va  2s  .  c o  m

    String clsName = dataObj.getClass().toString();
    if (clsName.indexOf("CGLIB") > -1)
        return;

    StringBuilder indent = new StringBuilder();
    for (int i = 0; i < level; i++)
        indent.append("  ");

    for (Method method : dataObj.getClass().getMethods()) {
        String methodName = method.getName();
        if (!methodName.startsWith("get") || method.getModifiers() == 9) {
            continue;
        }

        String fieldName = methodName.substring(3, 4).toLowerCase()
                + methodName.substring(4, methodName.length());
        Object kidData = null;
        try {
            kidData = getValue((FormDataObjIFace) dataObj, fieldName);

        } catch (Exception ex) {
            System.out.println(indent + fieldName + " = <no data>");
        }
        if (kidData != null) {
            if (kidData instanceof Set<?>) {
                for (Object obj : ((Set<?>) kidData)) {
                    System.out.println(indent + fieldName + " = " + obj);
                    if (obj instanceof FormDataObjIFace) {
                        dumpDataObj(session, obj, clsHash, level + 1);
                    }
                }
            } else {
                System.out.println(indent + fieldName + " = " + kidData);
                if (kidData instanceof FormDataObjIFace) {
                    session.attach(kidData);
                    dumpDataObj(session, kidData, clsHash, level + 1);
                }
            }

        }

    }
}

From source file:edu.ucsb.nceas.metacat.util.RequestUtil.java

private static String paramsToQuery(Hashtable<String, String[]> params) {
    String query = "";
    if (params != null) {
        boolean firstParam = true;
        for (String paramName : params.keySet()) {
            if (firstParam) {
                firstParam = false;/*from ww w  .  j  a  v  a  2 s.c om*/
            } else {
                query += "&";
            }
            query += paramName + "=" + params.get(paramName)[0];
        }
    }

    return query;
}

From source file:Main.java

public static void addApp(String file, String name, Hashtable<String, String> attri) throws Exception {
    DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder dombuilder = domfac.newDocumentBuilder();
    FileInputStream is = new FileInputStream(file);

    Document doc = dombuilder.parse(is);

    NodeList nodeList = doc.getElementsByTagName("app");
    if (nodeList != null && nodeList.getLength() >= 1) {
        Node deviceNode = nodeList.item(0);
        Element device = doc.createElement("aut");
        device.setTextContent(name);/*from   www  .  j a v a  2 s.  c  o m*/
        for (Iterator itrName = attri.keySet().iterator(); itrName.hasNext();) {
            String attriKey = (String) itrName.next();
            String attriValue = (String) attri.get(attriKey);
            device.setAttribute(attriKey, attriValue);
        }
        deviceNode.appendChild(device);
    }

    //save
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    Properties props = t.getOutputProperties();
    props.setProperty(OutputKeys.ENCODING, "GB2312");
    t.setOutputProperties(props);
    DOMSource dom = new DOMSource(doc);
    StreamResult sr = new StreamResult(file);
    t.transform(dom, sr);
}

From source file:Main.java

public static void addHandset(String file, String name, Hashtable<String, String> attri) throws Exception {
    DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder dombuilder = domfac.newDocumentBuilder();
    FileInputStream is = new FileInputStream(file);

    Document doc = dombuilder.parse(is);
    NodeList nodeList = doc.getElementsByTagName("devices");
    if (nodeList != null && nodeList.getLength() >= 1) {
        Node deviceNode = nodeList.item(0);
        Element device = doc.createElement("device");
        device.setTextContent(name);//  w  w  w  . j  av  a2s .  c o m
        for (Iterator itrName = attri.keySet().iterator(); itrName.hasNext();) {
            String attriKey = (String) itrName.next();
            String attriValue = (String) attri.get(attriKey);
            device.setAttribute(attriKey, attriValue);
        }
        deviceNode.appendChild(device);
    }

    //save
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    Properties props = t.getOutputProperties();
    props.setProperty(OutputKeys.ENCODING, "GB2312");
    t.setOutputProperties(props);
    DOMSource dom = new DOMSource(doc);
    StreamResult sr = new StreamResult(file);
    t.transform(dom, sr);
}

From source file:com.attentec.ServerContact.java

/**
 * Posts POST request to url with data that from values.
 * Values are put together to a json object before they are sent to server.
 * postname = { subvar_1_name => subvar_1_value,
 *             subvar_2_name => subvar_2_value
 *             ...}// w  w w.j av  a2s. c  o  m
 * postname_2 = {...}
 * ...
 * @param values hashtable with structure:
 * @param url path on the server to call
 * @param ctx calling context
 * @return JSONObject with data from rails server.
 * @throws Login.LoginException when login is wrong
 */
public static JSONObject postJSON(final Hashtable<String, List<NameValuePair>> values, final String url,
        final Context ctx) throws Login.LoginException {
    //fetch the urlbase
    urlbase = PreferencesHelper.getServerUrlbase(ctx);

    //create a JSONObject of the hashtable
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    Enumeration<String> postnames = values.keys();

    String postname;
    List<NameValuePair> postvalues;
    JSONObject postdata;

    while (postnames.hasMoreElements()) {
        postname = (String) postnames.nextElement();
        postvalues = values.get(postname);
        postdata = new JSONObject();
        for (int i = 0; i < postvalues.size(); i++) {
            try {
                postdata.put(postvalues.get(i).getName(), postvalues.get(i).getValue());
            } catch (JSONException e) {
                Log.w(TAG, "JSON fail");
                return null;
            }
        }
        pairs.add(new BasicNameValuePair(postname, postdata.toString()));
    }

    //prepare the http call
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT);

    HttpClient client = new DefaultHttpClient(httpParams);

    HttpPost post = new HttpPost(urlbase + url);
    //Log.d(TAG, "contacting url: " + post.getURI());
    try {
        post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return null;
    }

    //call the server
    String response = null;
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        response = client.execute(post, responseHandler);
    } catch (IOException e) {
        Log.e(TAG, "Failed in HTTP request: " + e.toString());
        return null;
    }
    //Log.d(TAG, "Have contacted url success: " + post.getURI());
    //read response
    JSONObject jsonresponse;
    try {

        jsonresponse = new JSONObject(response);
    } catch (JSONException e) {
        Log.e(TAG, "Incorrect response from server" + e.toString());
        return null;
    }
    String responsestatus;
    try {
        responsestatus = jsonresponse.getString("Responsestatus");
    } catch (JSONException e1) {
        return null;
    }
    if (!responsestatus.equals("Wrong login")) {
        return jsonresponse;
    } else {
        Log.w(TAG, "Wrong login");
        throw new Login.LoginException("Wrong login");
    }
}

From source file:com.nary.Debug.java

/**
 * This method prints all the elements in a Hashtable printing each
 * key:value pair on a new line/*  w ww. jav a  2 s. c o  m*/
 *
 * @param _hashtable The Hashtable to go through
 */

public static void println(Hashtable _hashtable) {
    checkCurrentInstance();
    if (_hashtable == null)
        return;

    Enumeration E = _hashtable.keys();

    while (E.hasMoreElements()) {
        String key = (String) E.nextElement();
        Debug.println("KEY=[" + key + "] DATA=[" + _hashtable.get(key) + "]");
    }
}

From source file:eionet.acl.PersistenceDB.java

/**
 * Generate the plain text format of an ACL.
 * <pre>//  ww  w  .j  a  v  a  2  s  .c  o m
 * user:john:rwx
 * user:john:rwx:doc
 * </pre>
 * @param aclEntries
 * @return List of rows in the plain text file format.
 */
private static ArrayList<String> aclEntriesToFileRows(List aclEntries) {

    if (aclEntries == null)
        return null;

    ArrayList<String> l = new ArrayList<String>();
    for (int i = 0; i < aclEntries.size(); i++) {

        Hashtable e = (Hashtable) aclEntries.get(i);
        String eType = (String) e.get("type");
        String eName = (String) e.get("id");
        String ePerms = (String) e.get("perms");
        String aclType = (String) e.get("acltype");

        StringBuffer eRow = new StringBuffer(eType);
        eRow.append(":").append(eName).append(":").append(ePerms);
        if (aclType != null && !aclType.equals("object"))
            eRow.append(":").append(aclType);

        l.add(eRow.toString());
    }

    return l;
}

From source file:com.greenpepper.server.rpc.xmlrpc.XmlRpcDataMarshaller.java

/**
 * Checks if the XML-RPC response is an GreenPepper server Exception.
 * If so an GreenPepperServerException will be thrown with the error id found.
 * </p>/*from   w w w.  ja v  a  2 s .  c  om*/
 *
 * @param xmlRpcResponse a {@link java.lang.Object} object.
 * @throws com.greenpepper.server.GreenPepperServerException if any.
 */
public static void checkForErrors(Object xmlRpcResponse) throws GreenPepperServerException {
    if (xmlRpcResponse instanceof Vector) {
        Vector temp = (Vector) xmlRpcResponse;
        if (!temp.isEmpty()) {
            checkErrors(temp.elementAt(0));
        }
    } else if (xmlRpcResponse instanceof Hashtable) {
        Hashtable table = (Hashtable) xmlRpcResponse;
        if (!table.isEmpty()) {
            checkForErrors(table.get(GreenPepperServerErrorKey.ERROR));
        }
    } else {
        checkErrors(xmlRpcResponse);
    }
}

From source file:com.modeln.build.ctrl.charts.CMnPatchCountChart.java

/**
 * Create a chart representing an arbitrary collection of name/value pairs. 
 * The data is passed in as a hashtable where the key is the name and the  
 * value is the number items. /*from   www .  ja v a2  s.  c o  m*/
 */
public static final JFreeChart getBarChart(Hashtable<String, Integer> data, String title, String nameLabel,
        String valueLabel) {
    JFreeChart chart = null;

    // Sort the data by name
    Vector<String> names = new Vector<String>();
    Enumeration nameList = data.keys();
    while (nameList.hasMoreElements()) {
        names.add((String) nameList.nextElement());
    }
    Collections.sort(names);

    // Populate the dataset with data
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    Iterator keyIter = names.iterator();
    while (keyIter.hasNext()) {
        String name = (String) keyIter.next();
        Integer value = data.get(name);
        dataset.addValue(value, valueLabel, name);
    }

    // Create the chart
    chart = ChartFactory.createBarChart(title, /*title*/
            nameLabel, /*categoryAxisLabel*/
            valueLabel, /*valueAxisLabel*/
            dataset, /*dataset*/
            PlotOrientation.VERTICAL, /*orientation*/
            false, /*legend*/
            false, /*tooltips*/
            false /*urls*/
    );

    // get a reference to the plot for further customization...
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    //chartFormatter.formatMetricChart(plot, "min");

    // Set the chart colors
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // disable bar outlines...
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setShadowVisible(false);
    final GradientPaint gp = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, Color.blue);
    renderer.setSeriesPaint(0, gp);

    // Set the label orientation
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    return chart;
}