Example usage for java.util Hashtable containsKey

List of usage examples for java.util Hashtable containsKey

Introduction

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

Prototype

public synchronized boolean containsKey(Object key) 

Source Link

Document

Tests if the specified object is a key in this hashtable.

Usage

From source file:de.berlios.gpon.wui.actions.data.ItemSearchAction.java

private void addAssociatedProperties(List idMapped, HashMap associatedPropertyMap) {

    // build up a pathDigest -> ipd-List mapping
    final Hashtable pathAndProperties = new Hashtable();

    CollectionUtils.forAllDo(associatedPropertyMap.keySet(), new Closure() {
        // foreach key in associatedPropertyMap do:
        public void execute(Object o) {
            String key = (String) o;

            String[] keySplit = ItemSearchForm.splitAssociatedPropertyKey(key);

            String pathDigest = keySplit[0];
            String ipdId = keySplit[1];

            if (!pathAndProperties.containsKey(pathDigest)) {
                pathAndProperties.put(pathDigest, new ArrayList());
            }//from  ww w  .j a  va2s.  c  o  m

            ((List) pathAndProperties.get(pathDigest)).add(new Long(ipdId));
        }
    });

    final String[] digests = (String[]) Collections.list(pathAndProperties.keys()).toArray(new String[0]);

    final PathResolver pathResolver = (PathResolver) getObjectForBeanId("pathResolver");

    CollectionUtils.forAllDo(idMapped, new Closure() {

        public void execute(Object o) {

            ItemMap im = (ItemMap) o;

            // foreach digest

            for (int digIdx = 0; digIdx < digests.length; digIdx++) {
                String digest = digests[digIdx];

                Set items = pathResolver.getItemsForPath(im.getItem().getId(), digest);

                if (items != null && items.size() > 0) {
                    if (items.size() > 1) {
                        throw new RuntimeException("more than one associated item found");
                    }

                    // get one & only item
                    Item item = ((Item[]) items.toArray(new Item[0]))[0];

                    Long[] ipds = (Long[]) ((List) pathAndProperties.get(digest)).toArray(new Long[0]);

                    ItemMappedById associatedImbi = new ItemMappedById(item);

                    for (int ipdIdx = 0; ipdIdx < ipds.length; ipdIdx++) {
                        Value value = associatedImbi.getValueObject(ipds[ipdIdx] + "");

                        if (value != null) {
                            im.addAdditionalAttribute(digest + "|" + ipds[ipdIdx], value);
                        }
                    }
                }
            }

        }
    });
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.ALMIntegration.java

/**
 * A integrao presupe que cada Cenrio de cada histria  um Caso de
 * Teste na ALM/*  ww  w. j  a v a  2  s.  co  m*/
 */
public void sendScenario(Hashtable<String, Object> result) {

    try {
        // Tenta obter dados de autenticacao vindo do Hashtable
        if (result.containsKey("user") && result.containsKey("password")) {
            username = (String) result.get("user");
            password = (String) result.get("password");
        } else {
            // Pega os dados de autenticao
            log.debug(message.getString("message-get-authenticator"));
            AutenticatorClient autenticator = new AutenticatorClient(
                    BehaveConfig.getIntegration_AuthenticatorPort(),
                    BehaveConfig.getIntegration_AuthenticatorHost());
            autenticator.open();
            username = autenticator.getUser();
            password = autenticator.getPassword();
            autenticator.close();
        }

        // Tenta obter dados de conexao com o ALM via hash
        urlServer = getHash(result, "urlServer", BehaveConfig.getIntegration_UrlServices()).trim();
        urlServerAuth = getHash(result, "urlServerAuth", BehaveConfig.getIntegration_UrlSecurity()).trim();
        projectAreaAlias = getHash(result, "projectAreaAlias", BehaveConfig.getIntegration_ProjectArea())
                .trim();

        // Para evitar problemas com encodings em projetos ns sempre
        // fazemos o decoding e depois encoding
        projectAreaAlias = URLDecoder.decode(projectAreaAlias, ENCODING);

        // Encode do Alias do Projeto
        projectAreaAlias = URLEncoder.encode(projectAreaAlias, ENCODING);

        // ID fixo de caso de teste
        boolean testCaseIdMeta = false;
        if (result.containsKey("testCaseId")) {
            testCaseId = Integer.parseInt((String) result.get("testCaseId"));
            testCaseIdMeta = true;
        } else {
            testCaseId = null;
        }

        log.debug(message.getString("message-integration-alm-started"));
        long t0 = GregorianCalendar.getInstance().getTimeInMillis();

        HttpClient client;
        String testCaseName;

        // Somente cria e associa o caso de teste quando ele no  informado
        if (testCaseId == null) {
            String testCaseIdentification = convertToIdentificationString(result.get("name").toString());
            testCaseName = "testcase" + testCaseIdentification;

            // --------------------------- TestCase (GET)
            // Conexo HTTPS
            client = HttpsClient.getNewHttpClient(ENCODING);
            // Login
            login(client);

            // Cria um novo caso de teste
            Testcase testCase = new Testcase();

            HttpResponse responseTestCaseGet = getRequest(client, "testcase", testCaseName);
            if (responseTestCaseGet.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                testCase = GenerateXMLString.getTestcaseObject(responseTestCaseGet);
            }

            // --------------------------- TestCase (PUT)
            // Conexo HTTPS
            client = HttpsClient.getNewHttpClient(ENCODING);
            // Login
            login(client);

            // TestCase
            log.debug(message.getString("message-send-test-case"));
            HttpResponse responseTestCase = sendRequest(client, "testcase", testCaseName,
                    GenerateXMLString.getTestcaseString(urlServer, projectAreaAlias, ENCODING,
                            result.get("name").toString(), result.get("steps").toString(), testCase));
            if (responseTestCase.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED
                    && responseTestCase.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new BehaveException(message.getString("exception-create-test-case",
                        responseTestCase.getStatusLine().toString()));
            }
        } else {
            testCaseName = "urn:com.ibm.rqm:testcase:" + testCaseId;
        }

        // Verifica se a auto associao esta habilitada
        if (BehaveConfig.getIntegration_AutoAssociateTestCaseInPlan()) {
            // --------------------------- Test Plan (GET)
            // Conexo HTTPS
            client = HttpsClient.getNewHttpClient(ENCODING);
            // Login
            login(client);

            Testplan plan;

            String testPlanNameId = "urn:com.ibm.rqm:testplan:" + result.get("testPlanId").toString();
            HttpResponse responseTestPlanGet = getRequest(client, "testplan", testPlanNameId);
            if (responseTestPlanGet.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED
                    && responseTestPlanGet.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new BehaveException(
                        message.getString("exception-test-plan-not-found", result.get("testPlanId").toString(),
                                projectAreaAlias) + ". --> communication failure, status code ["
                                + responseTestPlanGet.getStatusLine().getStatusCode() + "]");
            } else {
                plan = GenerateXMLString.getTestPlanObject(responseTestPlanGet);
            }

            // --------------------------- Test Plan (PUT)
            // Conexo HTTPS
            client = HttpsClient.getNewHttpClient(ENCODING);
            // Login
            login(client);

            // TestPlan
            log.debug(message.getString("message-send-test-plan"));
            HttpResponse responseTestPlan = sendRequest(client, "testplan", testPlanNameId, GenerateXMLString
                    .getTestplanString(urlServer, projectAreaAlias, ENCODING, testCaseName, plan));
            if (responseTestPlan.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new BehaveException(message.getString("exception-send-test-plan",
                        responseTestPlan.getStatusLine().toString()));
            }
        }

        // --------------------------- Work Item (PUT)
        // Conexo HTTPS
        client = HttpsClient.getNewHttpClient(ENCODING);
        // Login
        login(client);

        // WorkItem
        log.debug(message.getString("message-send-execution"));
        String workItemName = "workitemExecucaoAutomatizada-" + convertToIdentificationString(testCaseName)
                + "-" + result.get("testPlanId").toString();
        boolean redirect = false;
        HttpResponse responseWorkItem = sendRequest(client, "executionworkitem", workItemName,
                GenerateXMLString.getExecutionworkitemString(urlServer, projectAreaAlias, ENCODING,
                        testCaseName, result.get("testPlanId").toString()));
        if (responseWorkItem.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED
                && responseWorkItem.getStatusLine().getStatusCode() != HttpStatus.SC_OK
                && responseWorkItem.getStatusLine().getStatusCode() != HttpStatus.SC_SEE_OTHER) {
            String ms = message.getString("exception-create-execution",
                    responseWorkItem.getStatusLine().toString());
            if (testCaseIdMeta) {
                ms = message.getString("exception-verity-execution", testCaseId.toString(), message);
            }
            throw new BehaveException(ms);
        } else {
            Header locationHeader = responseWorkItem.getFirstHeader("Content-Location");
            if (locationHeader != null) {
                redirect = true;
                workItemName = locationHeader.getValue();
            }
        }

        // --------------------------- Result (PUT)
        // Conexo HTTPS
        client = HttpsClient.getNewHttpClient(ENCODING);
        // Login
        login(client);

        // WorkItem
        log.debug(message.getString("message-send-result"));
        String resultName = "result" + System.nanoTime();

        // Tratamento da identificao do workitem
        String executionWorkItemUrl = urlServer + "resources/" + projectAreaAlias + "/executionworkitem/"
                + workItemName;
        if (redirect) {
            executionWorkItemUrl = workItemName;
        }

        HttpResponse responseResult = sendRequest(client, "executionresult", resultName,
                GenerateXMLString.getExecutionresultString(urlServer, projectAreaAlias, ENCODING,
                        executionWorkItemUrl, ((ScenarioState) result.get("state")),
                        (Date) result.get("startDate"), (Date) result.get("endDate"),
                        (String) result.get("details")));
        if (responseResult.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            throw new BehaveException(
                    message.getString("exception-send-result", responseResult.getStatusLine().toString()));
        }

        long t1 = GregorianCalendar.getInstance().getTimeInMillis();

        DecimalFormat df = new DecimalFormat("0.0");
        log.debug(message.getString("message-integration-alm-end", df.format((t1 - t0) / 1000.00)));

    } catch (RuntimeException e) {
        if (e.getCause() instanceof ConnectException) {
            throw new BehaveException(message.getString("exception-authenticator-inaccessible"), e);
        } else {
            throw new BehaveException(e);
        }
    } catch (Exception e) {
        throw new BehaveException(e);
    }
}

From source file:adams.flow.control.TimedSubProcess.java

/**
 * Restores the state of the actor before the variables got updated.
 *
 * @param state   the backup of the state to restore from
 *///from  w w  w  . j  a  v a  2s.  co m
@Override
protected void restoreState(Hashtable<String, Object> state) {
    super.restoreState(state);

    if (state.containsKey(BACKUP_CALLABLEACTOR)) {
        m_CallableActor = (Actor) state.get(BACKUP_CALLABLEACTOR);
        state.remove(BACKUP_CALLABLEACTOR);
    }

    if (state.containsKey(BACKUP_CONFIGURED)) {
        m_Configured = (Boolean) state.get(BACKUP_CONFIGURED);
        state.remove(BACKUP_CONFIGURED);
    }
}

From source file:org.evolizer.da4java.graph.data.EdgeGrouper.java

/**
 * Checks for all edges whether it represents an invocation or an
 * inheritance relationship. Then all edges of the same type are aggregated
 * Given lower level edges are removed and a high level edge with the
 * corresponding width representing the number of grouped/aggregated
 * lower edges is created./*  w  w w  .  j  a  v a  2s.  c o  m*/
 * 
 * @param edges The list of lower edges to aggregate.
 */
private void group(List<Edge> edges) {
    Hashtable<String, List<Edge>> typeToEdgeListMap = new Hashtable<String, List<Edge>>();

    // get list of lower level edges per edge type
    for (Edge edge : edges) {
        FamixAssociation association = fGraph.getGraphModelMapper().getAssociation(edge);
        if (association != null) {
            List<Edge> edgeList;
            if (typeToEdgeListMap.containsKey(association.getType())) {
                edgeList = typeToEdgeListMap.get(association.getType());
            } else {
                edgeList = new ArrayList<Edge>();
                typeToEdgeListMap.put(association.getType(), edgeList);
            }
            edgeList.add(edge);
        }
    }

    // create higher level edges per edge type
    for (Entry<String, List<Edge>> entry : typeToEdgeListMap.entrySet()) {
        createHighLevelEdges(aggregateEdges(entry.getValue()), entry.getKey());
    }
}

From source file:org.kepler.kar.KARBuilder.java

private void removeDuplicateKAREntries() throws Exception {

    // now remove any "duplicate" karentries where duplicate
    // defined as same name and lsid.
    // see bug#4555. We may remove this in the future, where
    // such dupes might be allowed
    // (e.g. same name + lsid but in different subdirs in kar).
    Hashtable<String, String> nameMap = new Hashtable<String, String>();
    for (KAREntry ke : _karItems.keySet()) {
        String name = ke.getName();
        String itemLsid = ke.getAttributes().getValue(KAREntry.LSID);
        if (nameMap.containsKey(name)) {
            if (nameMap.get(name).equals(itemLsid)) {
                _karItemLSIDs.remove(ke.getLSID());
                _karItemNames.remove(ke.getName());
                _karItems.remove(ke);//from www .j  a  v a  2 s  .  c o  m
            }
        }
        nameMap.put(name, itemLsid);
    }
}

From source file:fr.eolya.utils.http.HttpUtils.java

public static String getHtmlDeclaredLanguage(String rawData) {
    if (rawData == null || "".equals(rawData))
        return "";

    Hashtable<String, Integer> langFreq = new Hashtable<String, Integer>();
    BufferedReader in = new BufferedReader(new StringReader(rawData));
    String line;//from   ww  w  .  j ava  2 s . c  o  m
    try {
        while ((line = in.readLine()) != null) {
            line = line.toLowerCase();

            //<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr-fr">
            if (line.indexOf("<html") >= 0 && line.toLowerCase().indexOf(" xml:lang") >= 0) {
                String lang = parseAttributeValue(line, "xml:lang=");
                if (lang != null && lang.length() >= 2) {
                    lang = lang.substring(0, 2);

                    if (langFreq.containsKey(lang))
                        langFreq.put(lang, langFreq.get(lang) + 1);
                    else
                        langFreq.put(lang, 1);
                }
            }

            //<html lang="fr">
            if (line.indexOf("<html") >= 0 && line.toLowerCase().indexOf(" lang") >= 0) {
                String lang = parseAttributeValue(line, "lang=");
                if (lang != null && lang.length() >= 2) {
                    lang = lang.substring(0, 2);

                    if (langFreq.containsKey(lang))
                        langFreq.put(lang, langFreq.get(lang) + 1);
                    else
                        langFreq.put(lang, 1);
                }
            }

            //<meta http-equiv="content-language" content="fr-fr" />
            if (line.indexOf("<meta") >= 0 && line.toLowerCase().indexOf(" http-equiv") >= 0
                    && line.toLowerCase().indexOf("content-language") >= 0) {
                String lang = parseAttributeValue(line, "content=");
                if (lang != null && lang.length() >= 2) {
                    lang = lang.substring(0, 2);

                    if (langFreq.containsKey(lang))
                        langFreq.put(lang, langFreq.get(lang) + 1);
                    else
                        langFreq.put(lang, 1);
                }
            }

            //<meta name="language" content="fr-fr" />
            if (line.indexOf("<meta") >= 0 && line.toLowerCase().indexOf(" name") >= 0
                    && line.toLowerCase().indexOf("language") >= 0
                    && line.toLowerCase().indexOf(" content") >= 0) {
                String lang = parseAttributeValue(line, "content=");
                if (lang != null && lang.length() >= 2) {
                    lang = lang.substring(0, 2);

                    if (langFreq.containsKey(lang))
                        langFreq.put(lang, langFreq.get(lang) + 1);
                    else
                        langFreq.put(lang, 1);
                }
            }

            //<meta name="content-language" content="fr-fr" />
            if (line.indexOf("<meta") >= 0 && line.toLowerCase().indexOf(" name") >= 0
                    && line.toLowerCase().indexOf("content-language") >= 0
                    && line.toLowerCase().indexOf(" content") >= 0) {
                String lang = parseAttributeValue(line, "content=");
                if (lang != null && lang.length() >= 2) {
                    lang = lang.substring(0, 2);

                    if (langFreq.containsKey(lang))
                        langFreq.put(lang, langFreq.get(lang) + 1);
                    else
                        langFreq.put(lang, 1);
                }
            }
        }

        // Get the best candidate
        Vector<String> v = new Vector<String>(langFreq.keySet());
        Iterator<String> it = v.iterator();
        int max = 0;
        String lang = "";
        while (it.hasNext()) {
            String element = (String) it.next();
            //System.out.println( element + " " + encodingFreq.get(element));
            if (langFreq.get(element) > max) {
                max = langFreq.get(element);
                lang = element;
            }
        }

        return lang;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

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

/**
 * Generate a pie graph representing average test counts for each type of test for 
 * all builds in the list. /*  w w w  .  j  ava  2  s . c om*/
 *
 * @param   builds  List of builds 
 * 
 * @return  Pie graph representing build execution times across all builds 
 */
public static final JFreeChart getAverageTestCountChart(Vector<CMnDbBuildData> builds) {
    JFreeChart chart = null;

    // Collect the average of all test types 
    Hashtable countAvg = new Hashtable();

    DefaultPieDataset dataset = new DefaultPieDataset();
    if ((builds != null) && (builds.size() > 0)) {

        // Collect build metrics for each of the builds in the list 
        Enumeration buildList = builds.elements();
        while (buildList.hasMoreElements()) {
            // Process the build metrics for the current build
            CMnDbBuildData build = (CMnDbBuildData) buildList.nextElement();
            Hashtable testSummary = build.getTestSummary();
            if ((testSummary != null) && (testSummary.size() > 0)) {
                Enumeration keys = testSummary.keys();
                while (keys.hasMoreElements()) {
                    String testType = (String) keys.nextElement();
                    CMnDbTestSummaryData tests = (CMnDbTestSummaryData) testSummary.get(testType);

                    Integer avgValue = null;
                    if (countAvg.containsKey(testType)) {
                        Integer oldAvg = (Integer) countAvg.get(testType);
                        avgValue = oldAvg + tests.getTotalCount();
                    } else {
                        avgValue = tests.getTotalCount();
                    }
                    countAvg.put(testType, avgValue);

                }
            }

        } // while list has elements

        // Populate the data set with the average values for each metric
        Enumeration keys = countAvg.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            Integer total = (Integer) countAvg.get(key);
            Integer avg = new Integer(total.intValue() / builds.size());
            dataset.setValue(key, avg);
        }

    } // if list has elements

    // API: ChartFactory.createPieChart(title, data, legend, tooltips, urls)
    chart = ChartFactory.createPieChart("Avg Test Count by Type", dataset, true, true, false);

    // get a reference to the plot for further customization...
    PiePlot plot = (PiePlot) chart.getPlot();
    chartFormatter.formatTypeChart(plot, "tests");

    return chart;
}

From source file:adams.ml.Dataset.java

public Vector<String> getDistinctStrings(String columnname) {
    Hashtable<String, Boolean> ht = new Hashtable<>();
    Vector<String> ret = new Vector<>();
    for (int i = 0; i < count(); i++) {
        DataRow dr = getSafe(i);/* www  .  ja va 2  s  .  c  om*/
        if (dr == null) {
            continue;
        }
        String cll = dr.getAsString(columnname);
        if (cll != null) {
            if (!ht.containsKey(cll)) {
                ht.put(cll, true);
            }
        }
    }
    for (String s : ht.keySet()) {
        ret.add(s);
    }
    return (ret);
}

From source file:net.timbusproject.extractors.rpmsoftwareextractor.Engine.java

private void extractInstallers(Hashtable<String, JSONObject> packages)
        throws InterruptedException, JSchException, IOException, JSONException {
    if (!isCommandAvailable("repoquery")) {
        log.warn("Installers could not be extracted.");
        return;//from   ww w. j  a  v  a  2s.  co m
    }
    String rpm = doCommand(commands.getProperty("installers")).getProperty("stdout");
    for (String installerInfo : rpm.split("\\n\\n")) {
        JSONObject object = extractPackage(installerInfo);
        if (packages.containsKey(object.getString("Id")))
            packages.get(object.getString("Id")).put("Installer", object.getString("Location"));
    }
}

From source file:com.autentia.intra.manager.billing.BillManager.java

/**
 * Account DAO */*from w w  w  .  j  a  va 2  s . c  o m*/
 */

public List<BillBreakDown> getAllBitacoreBreakDowns(Date start, Date end, Set<ProjectRole> roles,
        Set<ProjectCost> costes) {

    List<BillBreakDown> desgloses = new ArrayList<BillBreakDown>();

    ActivityDAO activityDAO = ActivityDAO.getDefault();
    ActivitySearch actSearch = new ActivitySearch();
    actSearch.setBillable(new Boolean(true));
    actSearch.setStartStartDate(start);
    actSearch.setEndStartDate(end);

    List<Activity> actividadesTotal = new ArrayList<Activity>();
    Hashtable user_roles = new Hashtable();

    for (ProjectRole proyRole : roles) {
        actSearch.setRole(proyRole);
        List<Activity> actividades = activityDAO.search(actSearch, new SortCriteria("startDate", false));
        actividadesTotal.addAll(actividades);
    }

    for (Activity act : actividadesTotal) {
        String key = act.getRole().getId().toString() + act.getUser().getId().toString();

        if (!user_roles.containsKey(key)) {
            Hashtable value = new Hashtable();
            value.put("ROLE", act.getRole());
            value.put("USER", act.getUser());
            user_roles.put(key, value);
        }
    }

    Enumeration en = user_roles.keys();

    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        Hashtable pair = (Hashtable) user_roles.get(key);
        actSearch.setBillable(new Boolean(true));
        actSearch.setStartStartDate(start);
        actSearch.setEndStartDate(end);

        ProjectRole pR = (ProjectRole) pair.get("ROLE");
        User u = (User) pair.get("USER");
        actSearch.setRole(pR);
        actSearch.setUser(u);
        List<Activity> actividadesUsuarioRol = activityDAO.search(actSearch,
                new SortCriteria("startDate", false));

        BillBreakDown brd = new BillBreakDown();
        brd.setConcept("Imputaciones (usuario - rol): " + u.getName() + " - " + pR.getName());
        brd.setAmount(pR.getCostPerHour());
        brd.setIva(new BigDecimal(ConfigurationUtil.getDefault().getIva()));
        BigDecimal unitsTotal = new BigDecimal(0);
        for (Activity act : actividadesUsuarioRol) {
            BigDecimal unitsActual = new BigDecimal(act.getDuration());
            unitsActual = unitsActual.divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
            unitsTotal = unitsTotal.add(unitsActual);
        }
        brd.setUnits(unitsTotal);
        brd.setSelected(true);
        desgloses.add(brd);
    }

    for (ProjectCost proyCost : costes) {
        BillBreakDown brd = new BillBreakDown();
        brd.setConcept("Coste: " + proyCost.getName());
        brd.setUnits(new BigDecimal(1));
        brd.setAmount(proyCost.getCost());
        brd.setIva(new BigDecimal(ConfigurationUtil.getDefault().getIva()));
        brd.setSelected(true);
        desgloses.add(brd);
    }

    return desgloses;

}