Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:info.ajaxplorer.client.http.AjxpAPI.java

public void enrichConnexionWithCookies(URLConnection connexion) {
    try {//from  w w w. ja  va2s  . c o  m
        URI uri = new URI(connexion.getURL().toString());
        List<Cookie> cookies = AjxpHttpClient.getCookies(uri);
        String cookieString = "";
        for (int i = 0; i < cookies.size(); i++) {
            String cs = "";
            if (i > 0) {
                cs += "; ";
            }
            cs += cookies.get(i).getName();
            cs += "=";
            cs += cookies.get(i).getValue();
            cookieString += cs;
        }
        connexion.setRequestProperty("Cookie", cookieString);
    } catch (Exception e) {

    }
}

From source file:com.novartis.opensource.yada.adaptor.RESTAdaptor.java

/**
 * Gets the input stream from the {@link URLConnection} and stores it in 
 * the {@link YADAQueryResult} in {@code yq}
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 *///from w w  w .  ja v  a  2s . com
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    boolean isPostPutPatch = this.method.equals(YADARequest.METHOD_POST)
            || this.method.equals(YADARequest.METHOD_PUT) || this.method.equals(YADARequest.METHOD_PATCH);
    resetCountParameter(yq);
    int rows = yq.getData().size() > 0 ? yq.getData().size() : 1;
    /*
     * Remember:
     * A row is an set of YADA URL parameter values, e.g.,
     * 
     *  x,y,z in this:      
     *    ...yada/q/queryname/p/x,y,z
     *  so 1 row
     *    
     *  or each of {col1:x,col2:y,col3:z} and {col1:a,col2:b,col3:c} in this:
     *    ...j=[{qname:queryname,DATA:[{col1:x,col2:y,col3:z},{col1:a,col2:b,col3:c}]}]
     *  so 2 rows
     */
    for (int row = 0; row < rows; row++) {
        String result = "";

        // creates result array and assigns it
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();

        String urlStr = yq.getUrl(row);

        for (int i = 0; i < yq.getParamCount(row); i++) {
            Matcher m = PARAM_URL_RX.matcher(urlStr);
            if (m.matches()) {
                String param = yq.getVals(row).get(i);
                urlStr = urlStr.replaceFirst(PARAM_SYMBOL_RX, m.group(1) + param);
            }
        }

        l.debug("REST url w/params: [" + urlStr + "]");
        try {
            URL url = new URL(urlStr);
            URLConnection conn = null;

            if (this.hasProxy()) {
                String[] proxyStr = this.proxy.split(":");
                Proxy proxySvr = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(proxyStr[0], Integer.parseInt(proxyStr[1])));
                conn = url.openConnection(proxySvr);
            } else {
                conn = url.openConnection();
            }

            // basic auth
            if (url.getUserInfo() != null) {
                //TODO issue with '@' sign in pw, must decode first
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                conn.setRequestProperty("Authorization", basicAuth);
            }

            // cookies
            if (yq.getCookies() != null && yq.getCookies().size() > 0) {
                String cookieStr = "";
                for (HttpCookie cookie : yq.getCookies()) {
                    cookieStr += cookie.getName() + "=" + cookie.getValue() + ";";
                }
                conn.setRequestProperty("Cookie", cookieStr);
            }

            if (yq.getHttpHeaders() != null && yq.getHttpHeaders().length() > 0) {
                l.debug("Processing custom headers...");
                @SuppressWarnings("unchecked")
                Iterator<String> keys = yq.getHttpHeaders().keys();
                while (keys.hasNext()) {
                    String name = keys.next();
                    String value = yq.getHttpHeaders().getString(name);
                    l.debug("Custom header: " + name + " : " + value);
                    conn.setRequestProperty(name, value);
                    if (name.equals(X_HTTP_METHOD_OVERRIDE) && value.equals(YADARequest.METHOD_PATCH)) {
                        l.debug("Resetting method to [" + YADARequest.METHOD_POST + "]");
                        this.method = YADARequest.METHOD_POST;
                    }
                }
            }

            HttpURLConnection hConn = (HttpURLConnection) conn;
            if (!this.method.equals(YADARequest.METHOD_GET)) {
                hConn.setRequestMethod(this.method);
                if (isPostPutPatch) {
                    //TODO make YADA_PAYLOAD case-insensitive and create an alias for it, e.g., ypl
                    // NOTE: YADA_PAYLOAD is a COLUMN NAME found in a JSONParams DATA object.  It 
                    //       is not a YADA param
                    String payload = yq.getDataRow(row).get(YADA_PAYLOAD)[0];
                    hConn.setDoOutput(true);
                    OutputStreamWriter writer;
                    writer = new OutputStreamWriter(conn.getOutputStream());
                    writer.write(payload.toString());
                    writer.flush();
                }
            }

            // debug
            Map<String, List<String>> map = conn.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                l.debug("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
            }

            try (BufferedReader in = new BufferedReader(new InputStreamReader(hConn.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    result += String.format("%1s%n", inputLine);
                }
            }
            yqr.addResult(row, result);
        } catch (MalformedURLException e) {
            String msg = "Unable to access REST source due to a URL issue.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (IOException e) {
            String msg = "Unable to read REST response.";
            throw new YADAAdaptorExecutionException(msg, e);
        }
    }
}

From source file:org.holistic.ws_proxy.WSProxyHelper.java

public void set_headers2urlconn(HttpServletRequest req, URLConnection objURLConn) throws Exception {
    String m_strName;// w ww . j  av a2s .  c  o m
    String m_strValue;
    for (Enumeration m_objElement = req.getHeaderNames(); m_objElement.hasMoreElements(); log
            .debug("ClientToEndPoint HEADER[" + m_strName + "] - VALUE[" + m_strValue + "]")) {
        m_strName = (String) m_objElement.nextElement();
        m_strValue = req.getHeader(m_strName);
        if (m_strName.toUpperCase().equals("COOKIE") && m_strValue.indexOf(COOKIE_SESSION + "=") > 0)
            m_strValue = m_strValue.replaceAll(COOKIE_SESSION + "=", COOKIE_SESSION + "_PROXY=");
        if (m_strName.toUpperCase().equals("COOKIE") && m_strValue.indexOf(EXTRA_COOKIE) > 0)
            m_strValue = m_strValue.replaceAll(EXTRA_COOKIE, "");
        objURLConn.setRequestProperty(m_strName, m_strValue);
    }

    String m_RemoteAddr = req.getRemoteAddr();
    objURLConn.setRequestProperty("x-forwarded-for", m_RemoteAddr);
    log.debug("Client IP x-forwarded-for (" + m_RemoteAddr + ").");
    String cipherSuite = (String) req.getAttribute("javax.net.ssl.cipher_suite");
    if (cipherSuite != null && req.getAttribute("javax.net.ssl.peer_certificates") != null) {
        java.security.cert.X509Certificate certChain[] = (java.security.cert.X509Certificate[]) req
                .getAttribute("javax.net.ssl.peer_certificates");
        java.security.cert.X509Certificate certStandar = certChain[0];
        m_strName = "entrust-client-certificate";
        String m_strTemp = (new BASE64Encoder()).encode(certStandar.getEncoded());
        m_strValue = m_strTemp.replaceAll("\r\n", "").replaceAll("\n", "");
        objURLConn.setRequestProperty(m_strName, m_strValue);
        log.debug("HEADER[" + m_strName + "] - VALUE[" + m_strValue + "]");
    }
}

From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java

private String sendRequest(Map<String, String> parameters) {
    URL url = createRequestUrl(parameters);
    URLConnection urlConn;

    try {//from  www.ja  va 2  s  .  c  om
        urlConn = url.openConnection();
        // setup url connection
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        // add content type
        urlConn.setRequestProperty("Content-Type", CONTENT_TYPE);
        // add cookie information
        if (cookie != null)
            urlConn.setRequestProperty("Cookie", COOKIE + cookie);

        // send request
        urlConn.connect();

        // read response
        BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = input.readLine()) != null)
            response.append(line);
        input.close();

        if (isLogDebugEnabled()) {
            logDebug("Requested URL: " + url);
            logDebug("Response: " + response);
        }

        return response.toString();
    } catch (IOException e) {
        logError("Sending request to Adobe Connect failed. Request: " + url.toString(), e);
        return "";
    }
}

From source file:io.hummer.util.ws.WebServiceClient.java

private InvocationResult doInvokeGET(String parameters, Map<String, String> httpHeaders, int retries,
        long connectTimeoutMS, long readTimeoutMS, boolean doUseCache) throws Exception {
    if (retries < 0)
        throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(parameters));

    String host = new URL(endpointURL).getHost();
    if (!lastRequestedHosts.containsKey(host)) {
        lastRequestedHosts.put(host, new AtomicLong());
    }/*from  w  w w . j  a  v  a  2  s .  c  o  m*/
    Object lockForTargetHost = lastRequestedHosts.get(host);

    parameters = parameters.trim();
    String urlString = endpointURL;
    if (!strUtil.isEmpty(parameters)) {
        String separator = endpointURL.contains("?") ? "&" : "?";
        urlString = endpointURL + separator + parameters;
    }

    if (doUseCache) {
        /** retrieve result from document cache */
        CacheEntry existing = cache.get(urlString);
        if (existing != null && !strUtil.isEmpty(existing.value)) {
            String valueShort = (String) existing.value;
            if (valueShort.length() > 200)
                valueShort = valueShort.substring(0, 200) + "...";
            AtomicReference<Element> eRef = new AtomicReference<Element>();
            Parallelization.warnIfNoResultAfter(eRef, "! Client could not convert element ("
                    + existing.value.length() + " bytes) within 15 seconds: " + valueShort, 15 * 1000);
            Parallelization.warnIfNoResultAfter(eRef, "! Client could not convert element ("
                    + existing.value.length() + " bytes) within 40 seconds: " + valueShort, 40 * 1000);
            Element e = xmlUtil.toElement((String) existing.value);
            eRef.set(e);
            logger.info("Result exists in cache for URL " + urlString + " - " + e + " - "
                    + this.xmlUtil.toString().length());
            return new InvocationResult(e);
        }
    }

    pauseToAvoidSpamming();

    URL url = new URL(urlString);
    URLConnection c = url.openConnection();
    c.setConnectTimeout((int) connectTimeoutMS);
    c.setReadTimeout((int) readTimeoutMS);
    logger.info("Retrieving data from service using GET: " + url);

    String tmpID = PerformanceInterceptor.event(EventType.START_HTTP_GET);
    for (String key : httpHeaders.keySet()) {
        c.setRequestProperty(key, httpHeaders.get(key));
    }
    StringBuilder b = new StringBuilder();
    synchronized (lockForTargetHost) {
        try {
            BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String temp;
            while ((temp = r.readLine()) != null) {
                b.append(temp);
                b.append("\n");
            }
        } catch (Exception e) {
            logger.info("Could not GET page with regular URLConnection, trying HtmlUnit..: " + e);
            b = getPageUsingHtmlUnit(urlString, httpHeaders, readTimeoutMS, null);
        }
    }

    PerformanceInterceptor.event(EventType.FINISH_HTTP_GET, tmpID);

    String tmpID1 = PerformanceInterceptor.event(EventType.START_RESPONSE_TO_XML);
    String result = b.toString().trim();
    if (!result.startsWith("<") || !result.endsWith(">")) { // wrap non-xml results (e.g., CSV files)
        StringBuilder sb = new StringBuilder("<doc><![CDATA[");
        sb.append(result);
        sb.append("]]></doc>");
        result = sb.toString();
    }

    String tmpID2 = PerformanceInterceptor.event(EventType.START_STRING_TO_XML);
    Element resultElement = xmlUtil.toElement(result);
    PerformanceInterceptor.event(EventType.FINISH_STRING_TO_XML, tmpID2);

    if (doUseCache) {
        /** put result element to document cache */
        cache.putWithoutWaiting(urlString, xmlUtil.toString(resultElement, true));
    }

    InvocationResult invResult = new InvocationResult(resultElement);
    PerformanceInterceptor.event(EventType.FINISH_RESPONSE_TO_XML, tmpID1);

    return invResult;
}

From source file:com.krawler.spring.mailIntegration.mailIntegrationController.java

public ModelAndView mailIntegrate(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    KwlReturnObject kmsg = null;/* w w w  .ja  v a2  s  .  com*/
    JSONObject obj = new JSONObject();
    String url = storageHandlerImpl.GetSOAPServerUrl();
    String res = "";
    boolean isFormSubmit = false;
    boolean isDefaultModelView = true;
    ModelAndView mav = null;
    try {
        if (!StringUtil.isNullOrEmpty(request.getParameter("action"))
                && request.getParameter("action").equals("getoutboundconfid")) {
            String str = "";
            url += "getOutboundConfiId.php";
            URL u = new URL(url);
            URLConnection uc = u.openConnection();
            uc.setDoOutput(true);
            uc.setUseCaches(false);
            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            PrintWriter pw = new PrintWriter(uc.getOutputStream());
            pw.println(str);
            pw.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String line = "";

            while ((line = in.readLine()) != null) {
                res += line;
            }
            in.close();
        } else if (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                && request.getParameter("emailUIAction").equals("uploadAttachment")) {
            isDefaultModelView = false;
            url += "krawlermails.php";

            String pass = "";
            String currUser = sessionHandlerImplObj.getUserName(request) + "_";
            String userid = sessionHandlerImplObj.getUserid(request);

            String jsonStr = profileHandlerDAOObj.getUser_hash(userid);
            JSONObject currUserAuthInfo = new JSONObject(jsonStr);
            if (currUserAuthInfo.has("userhash")) {
                currUser += currUserAuthInfo.getString("subdomain");
                pass = currUserAuthInfo.getString("userhash");
            }

            Enumeration en = request.getParameterNames();
            String str = "username=" + currUser + "&user_hash=" + pass;
            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String paramValue = request.getParameter(paramName);
                str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
            }

            List fileItems = null;
            HashMap<String, String> arrParam = new HashMap<String, String>();
            ArrayList<FileItem> fi = new ArrayList<FileItem>();
            //                if (request.getParameter("email_attachment") != null) {
            DiskFileUpload fu = new DiskFileUpload();
            fileItems = fu.parseRequest(request);
            //                    crmDocumentDAOObj.parseRequest(fileItems, arrParam, fi, fileUpload);
            FileItem fi1 = null;
            for (Iterator k = fileItems.iterator(); k.hasNext();) {
                fi1 = (FileItem) k.next();
                if (fi1.isFormField()) {
                    arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
                } else {
                    if (fi1.getSize() != 0) {
                        fi.add(fi1);
                    }
                }
            }
            //                }
            long sizeinmb = 10; // 10 MB
            long maxsize = sizeinmb * 1024 * 1024;
            if (fi.size() > 0) {
                for (int cnt = 0; cnt < fi.size(); cnt++) {

                    if (fi.get(cnt).getSize() <= maxsize) {
                        try {
                            byte[] filecontent = fi.get(cnt).get();

                            URL u = new URL(url + "?" + str);
                            URLConnection uc = u.openConnection();
                            uc.setDoOutput(true);
                            uc.setUseCaches(false);
                            uc.setRequestProperty("Content-Type",
                                    "multipart/form-data; boundary=---------------------------4664151417711");
                            uc.setRequestProperty("Content-length", "" + filecontent.length);
                            uc.setRequestProperty("Cookie", "");

                            OutputStream outstream = uc.getOutputStream();

                            String newline = "\r\n";
                            String b1 = "";
                            b1 += "-----------------------------4664151417711" + newline;
                            b1 += "Content-Disposition: form-data; name=\"email_attachment\"; filename=\""
                                    + fi.get(cnt).getName() + "\"" + newline;
                            b1 += "Content-Type: text" + newline;
                            b1 += newline;

                            String b2 = "";
                            b2 += newline + "-----------------------------4664151417711--" + newline;

                            String b3 = "";
                            b3 += "-----------------------------4664151417711" + newline;
                            b3 += "Content-Disposition: form-data; name=\"addval\";" + newline;
                            b3 += newline;

                            String b4 = "";
                            b4 += newline + "-----------------------------4664151417711--" + newline;

                            outstream.write(b1.getBytes());
                            outstream.write(b1.getBytes());
                            outstream.write(b1.getBytes());
                            outstream.write(fi.get(cnt).get());
                            outstream.write(b4.getBytes());
                            PrintWriter pw = new PrintWriter(outstream);
                            pw.println(str);
                            pw.close();
                            outstream.flush();

                            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                            String line = "";

                            while ((line = in.readLine()) != null) {
                                res += line;
                            }
                            in.close();
                        } catch (Exception e) {
                            throw ServiceException.FAILURE(e.getMessage(), e);
                        }
                    } else {
                        JSONObject jerrtemp = new JSONObject();
                        jerrtemp.put("Success", "Fail");
                        jerrtemp.put("errmsg", "Attachment size should be upto " + sizeinmb + "mb");
                        res = jerrtemp.toString();
                    }
                }
            } else {
                JSONObject jerrtemp = new JSONObject();
                jerrtemp.put("Success", "Fail");
                jerrtemp.put("errmsg", "Attachment file size should be greater than zero");
                res = jerrtemp.toString();
            }

        } else {

            url += "krawlermails.php";

            String pass = "";
            String currUser = sessionHandlerImplObj.getUserName(request) + "_";
            String userid = sessionHandlerImplObj.getUserid(request);

            String jsonStr = profileHandlerDAOObj.getUser_hash(userid);
            JSONObject currUserAuthInfo = new JSONObject(jsonStr);
            if (currUserAuthInfo.has("userhash")) {
                currUser += currUserAuthInfo.getString("subdomain");
                pass = currUserAuthInfo.getString("userhash");
            }

            Enumeration en = request.getParameterNames();
            String str = "username=" + currUser + "&user_hash=" + pass;
            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String paramValue = request.getParameter(paramName);
                str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
            }

            URL u = new URL(url);
            URLConnection uc = u.openConnection();
            uc.setDoOutput(true);
            uc.setUseCaches(false);
            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            PrintWriter pw = new PrintWriter(uc.getOutputStream());
            pw.println(str);
            pw.close();

            if ((!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                    && request.getParameter("emailUIAction").equals("getMessageListXML"))
                    || (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction")) && request
                            .getParameter("emailUIAction").equals("getMessageListKrawlerFoldersXML"))) {
                //response.setContentType("text/xml;charset=UTF-8");
                isFormSubmit = true;
                int totalCnt = 0;
                int unreadCnt = 0;
                JSONObject jobj = new JSONObject();
                JSONArray jarr = new JSONArray();
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(uc.getInputStream());

                NodeList cntentity = doc.getElementsByTagName("TotalCount");
                Node cntNode = cntentity.item(0);
                if (cntNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element firstPersonElement = (Element) cntNode;
                    totalCnt = Integer.parseInt(firstPersonElement.getChildNodes().item(0).getNodeValue());
                }

                cntentity = doc.getElementsByTagName("UnreadCount");
                cntNode = cntentity.item(0);
                if (cntNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element firstPersonElement = (Element) cntNode;
                    unreadCnt = Integer.parseInt(firstPersonElement.getChildNodes().item(0).getNodeValue());
                }
                String dateFormatId = sessionHandlerImpl.getDateFormatID(request);
                String timeFormatId = sessionHandlerImpl.getUserTimeFormat(request);
                String timeZoneDiff = sessionHandlerImpl.getTimeZoneDifference(request);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                // check for Mail server protocol
                boolean isYahoo = false;

                if (request.getParameter("mbox").equals("INBOX")) {
                    u = new URL(url);
                    uc = u.openConnection();
                    uc.setDoOutput(true);
                    uc.setUseCaches(false);
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    str = "username=" + currUser + "&user_hash=" + pass
                            + "&action=EmailUIAjax&emailUIAction=getIeAccount&ieId="
                            + request.getParameter("ieId") + "&module=Emails&to_pdf=true";
                    pw = new PrintWriter(uc.getOutputStream());
                    pw.println(str);
                    pw.close();
                    BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                    String line = "";
                    while ((line = in.readLine()) != null) {
                        res += line;
                    }
                    in.close();

                    JSONObject ieIDInfo = new JSONObject(res);
                    if (ieIDInfo.getString("server_url").equals("pop.mail.yahoo.com"))
                        isYahoo = true;
                }
                sdf.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
                DateFormat userdft = null;
                if (!isYahoo)
                    userdft = KwlCommonTablesDAOObj.getUserDateFormatter(dateFormatId, timeFormatId,
                            timeZoneDiff);
                else
                    userdft = KwlCommonTablesDAOObj.getOnlyDateFormatter(dateFormatId, timeFormatId);

                NodeList entity = doc.getElementsByTagName("Emails");
                NodeList email = ((Element) entity.item(0)).getElementsByTagName("Email");
                for (int i = 0; i < email.getLength(); i++) {
                    JSONObject tmpObj = new JSONObject();
                    Node rowElement = email.item(i);
                    if (rowElement.getNodeType() == Node.ELEMENT_NODE) {
                        NodeList childNodes = rowElement.getChildNodes();
                        for (int j = 0; j < childNodes.getLength(); j++) {
                            Node node = childNodes.item(j);
                            if (node.getNodeType() == Node.ELEMENT_NODE) {
                                Element firstPersonElement = (Element) node;
                                if (firstPersonElement != null) {
                                    NodeList textFNList = firstPersonElement.getChildNodes();
                                    if (textFNList.item(0) != null) {
                                        if (request.getSession().getAttribute("iPhoneCRM") != null) {
                                            String body = ((Node) textFNList.item(0)).getNodeValue().trim();
                                            if (body.contains("&lt;"))
                                                body = body.replace("&lt;", "<");
                                            if (body.contains("&gt;"))
                                                body = body.replace("&gt;", ">");
                                            tmpObj.put(node.getNodeName(), body);
                                        } else {
                                            String value = ((Node) textFNList.item(0)).getNodeValue().trim();
                                            if (node.getNodeName().equals("date")) {
                                                value = userdft.format(sdf.parse(value));
                                            }
                                            tmpObj.put(node.getNodeName(), value);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    jarr.put(tmpObj);
                }
                jobj.put("data", jarr);
                jobj.put("totalCount", totalCnt);
                jobj.put("unreadCount", unreadCnt);
                res = jobj.toString();
            } else {
                BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                String line = "";

                while ((line = in.readLine()) != null) {
                    res += line;
                }
                in.close();
                if ((!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                        && request.getParameter("emailUIAction").equals("fillComposeCache"))) {
                    isFormSubmit = true;
                } else if (!StringUtil.isNullOrEmpty(request.getParameter("emailUIAction"))
                        && request.getParameter("emailUIAction").equals("refreshKrawlerFolders")) {
                    if (res.equals("Not a valid entry method")) {
                        ArrayList filter_names = new ArrayList();
                        ArrayList filter_params = new ArrayList();
                        filter_names.add("u.userID");
                        filter_params.add(userid);
                        HashMap<String, Object> requestParams = new HashMap<String, Object>();
                        KwlReturnObject kwlobject = profileHandlerDAOObj.getUserDetails(requestParams,
                                filter_names, filter_params);
                        List li = kwlobject.getEntityList();
                        if (li.size() >= 0) {
                            if (li.iterator().hasNext()) {
                                User user = (User) li.iterator().next();
                                String returnStr = addUserEntryForEmails(
                                        user.getCompany().getCreator().getUserID(), user, user.getUserLogin(),
                                        user.getUserLogin().getPassword(), false);
                                JSONObject emailresult = new JSONObject(returnStr);
                                if (Boolean.parseBoolean(emailresult.getString("success"))) {
                                    pw = new PrintWriter(uc.getOutputStream());
                                    pw.println(str);
                                    pw.close();
                                    in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
                                    line = "";
                                    while ((line = in.readLine()) != null) {
                                        res += line;
                                    }
                                    in.close();
                                }
                            }
                        }
                    }
                } else if (res.equals("bool(false)")) {
                    res = "false";
                }
            }
        }
        if (!isFormSubmit) {
            JSONObject resjobj = new JSONObject();
            resjobj.put("valid", true);
            resjobj.put("data", res);
            res = resjobj.toString();
        }
        if (isDefaultModelView)
            mav = new ModelAndView("jsonView-ex", "model", res);
        else
            mav = new ModelAndView("jsonView", "model", res);
    } catch (SessionExpiredException e) {
        mav = new ModelAndView("jsonView-ex", "model", "{'valid':false}");
        System.out.println(e.getMessage());
    } catch (Exception e) {
        mav = new ModelAndView("jsonView-ex", "model",
                "{'valid':true,data:{success:false,errmsg:'" + e.getMessage() + "'}}");
        System.out.println(e.getMessage());
    }
    return mav;
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.data.SessionBean.java

/**
 * Connect to the JMarkets server and start the session defined by the given SessionDef object.
 *  Return the session Id of the created session
 */// w ww.j  av  a  2 s . co m
private int executeSession(String path, String name, SessionDef session) {
    try {
        URL servlet = new URL(path + "/servlet/ServletReceiver");
        Request req = new Request(Request.SERVER_INIT_REQUEST);

        req.addIntInfo("numClients", numSubjects);
        req.addIntInfo("updateProtocol", JMConstants.HTTP_UPDATE_PROTOCOL);
        req.addIntInfo("updateTime", 100);
        req.addStringInfo("name", name);
        req.addInfo("session", session);

        URLConnection servletConnection = servlet.openConnection();

        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");

        ObjectOutputStream outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());

        outputToServlet.writeObject(req);
        outputToServlet.flush();
        outputToServlet.close();

        ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
        Response res = (Response) inputFromServlet.readObject();
        int sessionId = res.getIntInfo("sessionId");

        inputFromServlet.close();

        return sessionId;

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return -1;
}

From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java

private String loginToSrf() throws MalformedURLException, IOException, ConnectException {
    String authorizationsAddress = _ftaasServerAddress.concat("/rest/security/authorizations/access-tokens");
    //    .concat("/?TENANTID="+_tenant);
    Writer writer = null;/*from ww  w.j a va2s  .  c  o  m*/
    // login //
    JSONObject login = new JSONObject();
    login.put("loginName", _app);
    login.put("password", _secret);
    OutputStream out;
    URL loginUrl = new URL(authorizationsAddress);
    URLConnection loginCon;

    if (_ftaasServerAddress.startsWith("http://")) {
        loginCon = (HttpURLConnection) loginUrl.openConnection();
        loginCon.setDoOutput(true);
        loginCon.setDoInput(true);
        ((HttpURLConnection) loginCon).setRequestMethod("POST");
        loginCon.setRequestProperty("Content-Type", "application/json");
        out = loginCon.getOutputStream();
    } else {
        loginCon = loginUrl.openConnection();
        loginCon.setDoOutput(true);
        loginCon.setDoInput(true);
        ((HttpsURLConnection) loginCon).setRequestMethod("POST");
        loginCon.setRequestProperty("Content-Type", "application/json");
        ((HttpsURLConnection) loginCon).setSSLSocketFactory(_factory);
        out = loginCon.getOutputStream();
    }

    writer = new OutputStreamWriter(out);
    writer.write(login.toString());
    writer.flush();
    out.flush();
    out.close();
    int responseCode = ((HttpURLConnection) loginCon).getResponseCode();
    systemLogger.fine(String.format("SRF login received response code: %d", responseCode));
    BufferedReader br = new BufferedReader(new InputStreamReader((loginCon.getInputStream())));
    StringBuffer response = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
        response.append(line);
    }
    String tmp = response.toString();
    int n = tmp.length();

    return tmp.substring(1, n - 1);
}

From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java

/**
 * Removes the given Rule from the PolicySet which is stored on the server
 * /*w w  w  .  j  a v a 2s  .co m*/
 * @param oo
 * @return
 */
private boolean requestRemoveRule(OIDObject oo) {

    try {
        URL url = new URL(strRelURL + "/" + privilegedServlet
                + "CreateConsentServiceServlet?type=removeRule&id=" + oo.getIdentifier());
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("cookie", strCookie);
        conn.setDoInput(true);

        InputStream is = conn.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(new InputStreamReader(is, "UTF8"), writer);
        String s = writer.toString();

        is.close();

        JSONObject ack = new JSONObject(s);

        return ack.getBoolean("removed");
    } catch (Exception e) {
        return false;
    }
}

From source file:org.openehealth.coms.cc.consent_applet.applet.ConsentApplet.java

/**
 * Requests a newly created CDA Document from the server
 * /*from www .  j a  v  a  2 s  . co m*/
 */
private void requestDocument() {
    try {

        URL url = new URL(
                strRelURL + "/" + privilegedServlet + "CreateConsentServiceServlet?type=newconsentcda");
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("cookie", strCookie);
        conn.setDoInput(true);

        InputStream is = conn.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(new InputStreamReader(is, "UTF8"), writer);
        String s = writer.toString();
        is.close();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        cda = db.parse(new InputSource(new ByteArrayInputStream(s.getBytes("utf-8"))));

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