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:com.microsoft.applicationinsights.test.framework.telemetries.RequestTelemetryItem.java

/**
 * Converts JSON object to Request TelemetryItem
 * @param json The JSON object// w  w  w .  ja  v  a 2 s.co  m
 */
private void initRequestTelemetryItem(JSONObject json) throws URISyntaxException, JSONException {
    System.out.println("Converting JSON object to RequestTelemetryItem");
    JSONObject requestProperties = json.getJSONArray("request").getJSONObject(0);

    String address = requestProperties.getString("url");
    Integer port = requestProperties.getJSONObject("urlData").getInt("port");
    Integer responseCode = requestProperties.getInt("responseCode");
    String requestName = requestProperties.getString("name");

    JSONArray parameters = requestProperties.getJSONObject("urlData").getJSONArray("queryParameters");
    Hashtable<String, String> queryParameters = new Hashtable<String, String>();
    for (int i = 0; i < parameters.length(); ++i) {
        JSONObject parameterPair = parameters.getJSONObject(i);
        String name = parameterPair.getString("parameter");
        String value = parameterPair.getString("value");
        queryParameters.put(name, value);
    }

    this.setProperty("uri", address);
    this.setProperty("port", port.toString());
    this.setProperty("responseCode", responseCode.toString());
    this.setProperty("requestName", requestName);

    for (String key : queryParameters.keySet()) {
        this.setProperty("queryParameter." + key, queryParameters.get(key));
    }
}

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

/**
 * @param request// www.ja va2s .co m
 * @throws DAOException
 * @throws IOException
 */
private void updatePartnership(Hashtable ht, HttpServletRequest request, PropertyTree dom)
        throws DAOException, IOException {

    // get the parameters
    String requestAction = (String) ht.get("request_action");

    String partnershipId = (String) ht.get("partnership_id");
    String cpaId = (String) ht.get("cpa_id");
    String service = (String) ht.get("service");
    String action = (String) ht.get("action_id");

    String transportEndpoint = (String) ht.get("transport_endpoint");
    String isHostnameVerified = (String) ht.get("is_hostname_verified");
    String syncReplyMode = (String) ht.get("sync_reply_mode");
    String ackRequested = (String) ht.get("ack_requested");
    String ackSignRequested = (String) ht.get("ack_sign_requested");
    String dupElimination = (String) ht.get("dup_elimination");
    String messageOrder = (String) ht.get("message_order");

    String disabled = (String) ht.get("disabled");
    String retries = (String) ht.get("retries");
    String retryInterval = (String) ht.get("retry_interval");

    String signRequested = (String) ht.get("sign_requested");
    String encryptRequested = (String) ht.get("encrypt_requested");

    boolean hasEncryptCert = ht.get("encrypt_cert") != null;
    InputStream encryptCertInputStream = null;
    if (hasEncryptCert) {
        encryptCertInputStream = (InputStream) ht.get("encrypt_cert");
    }
    boolean hasRemoveEncryptCert = false;
    if (ht.get("encrypt_cert_remove") != null) {
        if (((String) ht.get("encrypt_cert_remove")).equalsIgnoreCase("on")) {
            hasRemoveEncryptCert = true;
        }
    }
    boolean hasVerifyCert = ht.get("verify_cert") != null;
    InputStream verifyCertInputStream = null;
    if (hasVerifyCert) {
        verifyCertInputStream = (InputStream) ht.get("verify_cert");
    }
    boolean hasRemoveVerifyCert = false;
    if (ht.get("verify_cert_remove") != null) {
        if (((String) ht.get("verify_cert_remove")).equalsIgnoreCase("on")) {
            hasRemoveVerifyCert = true;
        }
    }

    if ("add".equalsIgnoreCase(requestAction) || "update".equalsIgnoreCase(requestAction)
            || "delete".equalsIgnoreCase(requestAction)) {

        // validate and set to dao
        PartnershipDAO partnershipDAO = (PartnershipDAO) EbmsProcessor.core.dao.createDAO(PartnershipDAO.class);
        PartnershipDVO partnershipDVO = (PartnershipDVO) partnershipDAO.createDVO();

        partnershipDVO.setPartnershipId(partnershipId);

        if ("update".equalsIgnoreCase(requestAction)) {
            partnershipDAO.retrieve(partnershipDVO);
        }

        partnershipDVO.setCpaId(cpaId);
        partnershipDVO.setService(service);
        partnershipDVO.setAction(action);
        partnershipDVO.setTransportEndpoint(transportEndpoint);
        partnershipDVO.setIsHostnameVerified(isHostnameVerified);
        partnershipDVO.setSyncReplyMode(syncReplyMode);
        partnershipDVO.setAckRequested(ackRequested);
        partnershipDVO.setAckSignRequested(ackSignRequested);
        partnershipDVO.setDupElimination(dupElimination);
        partnershipDVO.setActor(null);
        partnershipDVO.setDisabled(disabled);
        partnershipDVO.setRetries(StringUtilities.parseInt(retries));
        partnershipDVO.setRetryInterval(StringUtilities.parseInt(retryInterval));
        partnershipDVO.setPersistDuration(null);
        partnershipDVO.setMessageOrder(messageOrder);
        partnershipDVO.setSignRequested(signRequested);
        partnershipDVO.setDsAlgorithm(null);
        partnershipDVO.setMdAlgorithm(null);
        partnershipDVO.setEncryptRequested(encryptRequested);
        partnershipDVO.setEncryptAlgorithm(null);

        if ("add".equalsIgnoreCase(requestAction)) {
            getPartnership(partnershipDVO, dom, "add_partnership/");
        }

        if (!cpaId.equals("")) {
            partnershipDVO.setCpaId(cpaId);
        } else {
            request.setAttribute(ATTR_MESSAGE, "CPA ID cannot be empty");
            return;
        }

        if (!service.equals("")) {
            partnershipDVO.setService(service);
        } else {
            request.setAttribute(ATTR_MESSAGE, "Service cannot be empty");
            return;
        }

        if (!action.equals("")) {
            partnershipDVO.setAction(action);
        } else {
            request.setAttribute(ATTR_MESSAGE, "Action cannot be empty");
            return;
        }

        URL transportEndpointURL = null;
        try {
            transportEndpointURL = new URL(transportEndpoint);
        } catch (Exception e) {
            request.setAttribute(ATTR_MESSAGE, "Transport Endpoint is invalid");
            return;
        }
        if (transportEndpointURL.getProtocol().equalsIgnoreCase("mailto")) {
            partnershipDVO.setTransportProtocol("smtp");
        } else if (transportEndpointURL.getProtocol().equalsIgnoreCase("http")
                || transportEndpointURL.getProtocol().equalsIgnoreCase("https")) {
            partnershipDVO.setTransportProtocol(transportEndpointURL.getProtocol());
        } else {
            request.setAttribute(ATTR_MESSAGE, "The endpoint protocol does not support");
            return;
        }

        if (partnershipDVO.getRetries() == Integer.MIN_VALUE) {
            request.setAttribute(ATTR_MESSAGE, "Retries must be integer");
            return;
        }
        if (partnershipDVO.getRetryInterval() == Integer.MIN_VALUE) {
            request.setAttribute(ATTR_MESSAGE, "Retry Interval must be integer");
            return;
        }

        // encrypt cert
        if (hasRemoveEncryptCert) {
            partnershipDVO.setEncryptCert(null);
        }
        if (hasEncryptCert) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOHandler.pipe(encryptCertInputStream, baos);
                CertificateFactory.getInstance("X.509")
                        .generateCertificate(new ByteArrayInputStream(baos.toByteArray()));
                partnershipDVO.setEncryptCert(baos.toByteArray());
            } catch (Exception e) {
                request.setAttribute(ATTR_MESSAGE, "Uploaded encrypt cert is not an X.509 cert");
                return;
            }
        }

        // verify cert
        if (hasRemoveVerifyCert) {
            partnershipDVO.setSignCert(null);
        }
        if (hasVerifyCert) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOHandler.pipe(verifyCertInputStream, baos);
                CertificateFactory.getInstance("X.509")
                        .generateCertificate(new ByteArrayInputStream(baos.toByteArray()));
                partnershipDVO.setSignCert(baos.toByteArray());
            } catch (Exception e) {
                request.setAttribute(ATTR_MESSAGE, "Uploaded verify cert is not an X.509 cert");
                return;
            }
        }

        // check partnership conflict
        if (!Boolean.valueOf(partnershipDVO.getDisabled()).booleanValue()) {
            Iterator allConflictDAOData = partnershipDAO.findPartnershipsByCPA(partnershipDVO).iterator();
            while (allConflictDAOData.hasNext()) {
                PartnershipDVO conflictDAOData = (PartnershipDVO) allConflictDAOData.next();
                if (conflictDAOData != null
                        && !conflictDAOData.getPartnershipId().equals(partnershipDVO.getPartnershipId())
                        && !Boolean.valueOf(conflictDAOData.getDisabled()).booleanValue()) {
                    request.setAttribute(ATTR_MESSAGE, "Partnership '" + conflictDAOData.getPartnershipId()
                            + "' with same combination of CPA ID, Service and Action has already been enabled");
                    return;
                }
            }
        }

        // dao action
        if ("add".equalsIgnoreCase(requestAction)) {
            partnershipDAO.create(partnershipDVO);
            request.setAttribute(ATTR_MESSAGE, "Partnership added successfully");
            dom.removeProperty("/partnerships/add_partnership");
            dom.setProperty("/partnerships/add_partnership", "");
        }
        if ("update".equalsIgnoreCase(requestAction)) {
            partnershipDAO.persist(partnershipDVO);
            request.setAttribute(ATTR_MESSAGE, "Partnership updated successfully");
        }
        if ("delete".equalsIgnoreCase(requestAction)) {

            partnershipDAO.remove(partnershipDVO);
            request.setAttribute(ATTR_MESSAGE, "Partnership deleted successfully");
        }

    }
}

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/*from  w ww. ja v  a2s.c  o  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:ch.rgw.tools.StringTool.java

public static String flattenStrings(final Hashtable<Object, Object> h, final flattenFilter fil) {
    if (h == null) {
        return null;
    }/*from  w w  w  .j  a  v  a 2 s .c  o m*/
    Enumeration<Object> keys = h.keys();
    StringBuffer res = new StringBuffer(1000);
    res.append("FS1").append(flattenSeparator);
    while (keys.hasMoreElements()) {
        Object ko = (keys.nextElement());
        if (fil != null) {
            if (fil.accept(ko) == false) {
                continue;
            }
        }
        String v = ObjectToString(h.get(ko));
        String k = ObjectToString(ko);
        if ((k == null) || (v == null) || k.matches(".*=.*")) { // log.log("attempt
            // to
            // flatten
            // unsupported
            // object
            // type",Log.FATALS);
            return null;
        }
        res.append(k).append("=").append(v).append(flattenSeparator);
    }
    String r = res.toString();
    return r.replaceFirst(flattenSeparator + "$", "");
}

From source file:Controller.ControllerImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w  w  w.jav  a 2 s .  c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String code = (String) params.get("txtCode");
                    String name = (String) params.get("txtName");
                    String price = (String) params.get("txtPrice");
                    int a = Integer.parseInt(price);
                    String image = (String) params.get("txtImage");
                    //Update  product
                    if (fileName.equals("")) {

                        Products sp = new Products();
                        sp.Update(code, name, price, image);
                        RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi
                        Products sp = new Products();
                        sp.Update(code, name, price, "upload\\" + fileName);

                        RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

    this.processRequest(request, response);

}

From source file:com.stimulus.archiva.extraction.MessageExtraction.java

private String preparePlaintextMessage(Hashtable<String, String> inl, Hashtable<String, String> imgs,
        Hashtable<String, String> nonImgs, Hashtable<String, String> ready, ArrayList<String> mimeTypes) {
    String str = (String) inl.get("text/plain");
    str = activateURLs(str);/*  w w w  .  j a  v  a 2  s .  c  om*/
    Enumeration enuma = imgs.keys();
    StringBuffer buff = new StringBuffer();
    while (enuma.hasMoreElements()) {
        String fl = (String) enuma.nextElement();
        fl = (String) ready.get(fl);
        if (fl.endsWith(".tif") || fl.endsWith(".tiff")) {
            buff.append("<BR><BR><EMBED SRC=\"" + fl + "\" TYPE=\"image/tiff\" >"
                    + System.getProperty("line.separator"));
        } else {
            buff.append("<BR><BR><IMG SRC=\"" + fl + "\">" + System.getProperty("line.separator"));
        }
    }
    str = str.replaceAll("\r", "").replaceAll("\n", "<br>" + System.getProperty("line.separator"));
    return writeTempMessage("<html><head><META http-equiv=Content-Type content=\"text/html; charset="
            + serverEncoding + "\"></head><body>" + str + System.getProperty("line.separator") + buff.toString()
            + "</body></html>", ".html");
}

From source file:com.adito.agent.client.ProxyUtil.java

/**
 * Attempt to proxy settings from Firefox.
 * /*from   ww  w  .  ja  v  a2  s  .c  o m*/
 * @return firefox proxy settings
 * @throws IOException if firefox settings could not be obtained for some
 *         reason
 */
public static BrowserProxySettings lookupFirefoxProxySettings() throws IOException {

    try {

        Vector proxies = new Vector();
        Vector bypassAddr = new Vector();

        File home = new File(Utils.getHomeDirectory());
        File firefoxAppData;

        if (System.getProperty("os.name") != null && System.getProperty("os.name").startsWith("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            firefoxAppData = new File(home, "Application Data\\Mozilla\\Firefox\\profiles.ini"); //$NON-NLS-1$
        } else {
            firefoxAppData = new File(home, ".mozilla/firefox/profiles.ini"); //$NON-NLS-1$
        }

        // Look for Path elements in the profiles.ini
        BufferedReader reader = null;
        Hashtable profiles = new Hashtable();
        String line;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(firefoxAppData)));
            String currentProfileName = ""; //$NON-NLS-1$

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("[") && line.endsWith("]")) { //$NON-NLS-1$ //$NON-NLS-2$
                    currentProfileName = line.substring(1, line.length() - 1);
                    continue;
                }

                if (line.startsWith("Path=")) { //$NON-NLS-1$
                    profiles.put(currentProfileName, new File(firefoxAppData.getParent(), line.substring(5)));
                }
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        // Iterate through all the profiles and load the proxy infos from
        // the prefs.js file

        File prefsJS;
        String profileName;
        for (Enumeration e = profiles.keys(); e.hasMoreElements();) {
            profileName = (String) e.nextElement();
            prefsJS = new File((File) profiles.get(profileName), "prefs.js"); //$NON-NLS-1$
            Properties props = new Properties();
            reader = null;
            try {
                if (!prefsJS.exists()) {
                    // needed to defend against un-initialised profiles.
                    // #ifdef DEBUG
                    log.info("The file " + prefsJS.getAbsolutePath() + " does not exist."); //$NON-NLS-1$
                    // #endif
                    // now remove it from the map.
                    profiles.remove(profileName);
                    continue;
                }
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(prefsJS)));
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("user_pref(\"")) { //$NON-NLS-1$
                        int idx = line.indexOf("\"", 11); //$NON-NLS-1$
                        if (idx == -1)
                            continue;
                        String pref = line.substring(11, idx);

                        // Save this position
                        int pos = idx + 1;

                        // Look for another quote
                        idx = line.indexOf("\"", idx + 1); //$NON-NLS-1$

                        String value;
                        if (idx == -1) {
                            // No more quotes
                            idx = line.indexOf(" ", pos); //$NON-NLS-1$

                            if (idx == -1)
                                continue;

                            int idx2 = line.indexOf(")", pos); //$NON-NLS-1$

                            if (idx2 == -1)
                                continue;

                            value = line.substring(idx + 1, idx2);

                        } else {

                            // String value
                            int idx2 = line.indexOf("\"", idx + 1); //$NON-NLS-1$

                            if (idx2 == -1)
                                continue;

                            value = line.substring(idx + 1, idx2);
                        }

                        props.put(pref, value);

                    }
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
            ProxyInfo p;
            /**
             * Extract some proxies from the properites, if the proxy is
             * enabled
             */
            if ("1".equals(props.get("network.proxy.type"))) { //$NON-NLS-1$ //$NON-NLS-2$
                boolean isProfileActive = checkProfileActive(prefsJS);
                if (props.containsKey("network.proxy.ftp")) { //$NON-NLS-1$
                    p = createProxyInfo(
                            "ftp=" + props.get("network.proxy.ftp") + ":" + props.get("network.proxy.ftp_port"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                            "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.http")) { //$NON-NLS-1$
                    p = createProxyInfo(
                            "http=" + props.get("network.proxy.http") + ":" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                                    + props.get("network.proxy.http_port"), //$NON-NLS-1$
                            "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.ssl")) { //$NON-NLS-1$
                    p = createProxyInfo(
                            "ssl=" + props.get("network.proxy.ssl") + ":" + props.get("network.proxy.ssl_port"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                            "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.socks")) { //$NON-NLS-1$
                    p = createProxyInfo("socks=" + props.get("network.proxy.socks") + ":" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                            + props.get("network.proxy.socks_port"), "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.no_proxies_on")) { //$NON-NLS-1$

                    StringTokenizer tokens = new StringTokenizer(
                            props.getProperty("network.proxy.no_proxies_on"), ","); //$NON-NLS-1$ //$NON-NLS-2$

                    while (tokens.hasMoreTokens()) {
                        bypassAddr.addElement(((String) tokens.nextToken()).trim());
                    }

                }
            }
        }

        // need to ensure that the returned values are sorted correctly...
        BrowserProxySettings bps = new BrowserProxySettings();
        bps.setBrowser("Mozilla Firefox"); //$NON-NLS-1$
        bps.setProxiesActiveFirst(proxies);
        bps.setBypassAddr(new String[bypassAddr.size()]);
        bypassAddr.copyInto(bps.getBypassAddr());
        return bps;

    } catch (Throwable t) {
        throw new IOException("Failed to get proxy information from Firefox profiles: " + t.getMessage()); //$NON-NLS-1$
    }
}

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;/*  ww  w  .  j a v a  2 s  . c om*/
    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:edu.ku.brc.specify.extras.ViewToSchemaReview.java

/**
 * // w w  w  .  ja va 2 s  .  c  o m
 */
public static void dumpFormFieldList(final boolean doShowInBrowser) {
    List<ViewIFace> viewList = ((SpecifyAppContextMgr) AppContextMgr.getInstance()).getEntirelyAllViews();
    Hashtable<String, ViewIFace> hash = new Hashtable<String, ViewIFace>();

    for (ViewIFace view : viewList) {
        hash.put(view.getName(), view);
    }
    Vector<String> names = new Vector<String>(hash.keySet());
    Collections.sort(names);

    try {
        File file = new File("FormFields.html");
        PrintWriter pw = new PrintWriter(file);

        pw.println(
                "<HTML><HEAD><TITLE>Form Fields</TITLE><link rel=\"stylesheet\" href=\"http://specify6.specifysoftware.org/schema/specify6.css\" type=\"text/css\"/></HEAD><BODY>");
        pw.println("<center>");
        pw.println("<H2>Forms and Fields</H2>");
        pw.println("<center><table class=\"brdr\" border=\"0\" cellspacing=\"0\">");

        int formCnt = 0;
        int fieldCnt = 0;
        for (String name : names) {
            ViewIFace view = hash.get(name);
            boolean hasEdit = false;
            for (AltViewIFace altView : view.getAltViews()) {
                if (altView.getMode() != AltViewIFace.CreationMode.EDIT) {
                    hasEdit = true;
                    break;
                }
            }

            //int numViews = view.getAltViews().size();
            for (AltViewIFace altView : view.getAltViews()) {
                //AltView av = (AltView)altView;
                if ((hasEdit && altView.getMode() == AltViewIFace.CreationMode.VIEW)) {
                    ViewDefIFace vd = altView.getViewDef();
                    if (vd instanceof FormViewDef) {
                        formCnt++;
                        FormViewDef fvd = (FormViewDef) vd;
                        pw.println("<tr><td class=\"brdrodd\">");
                        pw.println(fvd.getName());
                        pw.println("</td></tr>");
                        int r = 1;
                        for (FormRowIFace fri : fvd.getRows()) {
                            FormRow fr = (FormRow) fri;
                            for (FormCellIFace cell : fr.getCells()) {
                                if (StringUtils.isNotEmpty(cell.getName())) {
                                    if (cell.getType() == FormCellIFace.CellType.panel) {
                                        FormCellPanelIFace panelCell = (FormCellPanelIFace) cell;
                                        for (String fieldName : panelCell.getFieldNames()) {
                                            pw.print("<tr><td ");
                                            pw.print("class=\"");
                                            pw.print(r % 2 == 0 ? "brdrodd" : "brdreven");
                                            pw.print("\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fieldName);
                                            pw.println("</td></tr>");
                                            fieldCnt++;
                                        }

                                    } else if (cell.getType() == FormCellIFace.CellType.field
                                            || cell.getType() == FormCellIFace.CellType.subview) {
                                        pw.print("<tr><td ");
                                        pw.print("class=\"");
                                        pw.print(r % 2 == 0 ? "brdrodd" : "brdreven");
                                        pw.print("\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + cell.getName());
                                        pw.println("</td></tr>");
                                        fieldCnt++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        pw.println("</table></center><br>");
        pw.println("Number of Forms: " + formCnt + "<br>");
        pw.println("Number of Fields: " + fieldCnt + "<br>");
        pw.println("</body></html>");
        pw.close();

        try {
            if (doShowInBrowser) {
                AttachmentUtils.openURI(file.toURI());
            } else {
                JOptionPane.showMessageDialog(getTopWindow(),
                        String.format(getResourceString("FormDisplayer.OUTPUT"), file.getCanonicalFile()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Calculates the previous cluster ratio feature for each cluster generated
 * on a specific run date and stores them in the database.
 *
 * @param log_date the run date//from   w w  w .  j  a v a2  s .c  om
 * @throws SQLException if the feature values can not be stored in the database
 */
public void updatePrevClusterRatios(Date log_date) throws SQLException {
    Hashtable<Integer, List<Double>> ratios = this.calculatePrevClusterRatios(log_date,
            Integer.parseInt(properties.getProperty(PREVCLUSTER_WINDOWKEY)));
    for (int clusterid : ratios.keySet()) {
        List<Double> ratiovals = ratios.get(clusterid);
        StringBuffer querybuf = new StringBuffer();
        Formatter formatter = new Formatter(querybuf);
        formatter.format(properties.getProperty(PREVCLUSTER_QUERY4KEY), df.format(log_date),
                ratiovals.get(0).toString(), ratiovals.get(1).toString(), Integer.toString(clusterid));
        dbi.executeQueryNoResult(querybuf.toString());
        formatter.close();
    }
}