Example usage for java.net URLConnection getOutputStream

List of usage examples for java.net URLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

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

public ModelAndView mailIntegrate(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    KwlReturnObject kmsg = null;/*from w  ww . j a va2s  .  c  om*/
    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: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;//  w w  w  .j  av  a 2 s . 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:com.fluidops.iwb.widget.ImportRDFWidget.java

private FButton createRefineButton(final FTextInput2 context, final FTextInput2 baseURI, final FContainer stat,
        final FTextInput2 project, final FTextInput2 refineFormat, final FTextInput2 refineURL,
        final FTextInput2 engine, final FCheckBox keepSourceCtx, final FCheckBox contextEditable) {
    return new FButton("refineButton", "Import RDF Data") {
        @Override/*w w  w .  j  av  a 2s  .  c  o  m*/
        public void onClick() {

            try {
                getBasicInput(context, baseURI);
            } catch (Exception e) {
                stat.hide(true);
                logger.info(e.getMessage());
                return;
            }

            if (engine.getInput().length() > 0 && project.getInput().length() > 0
                    && refineFormat.getInput().length() > 0 && refineURL.getInput().length() > 0) {
                Map<String, String> parameter = new HashMap<String, String>();
                parameter.put(engine.getName(), engine.getInput());
                parameter.put(project.getName(), project.getInput());
                parameter.put(refineFormat.getName(), refineFormat.getInput());
                URL urlValue = null;
                try {
                    urlValue = new URL(refineURL.getInput());
                } catch (MalformedURLException e) {
                    stat.hide(true);

                    getPage().getPopupWindowInstance().showError(refineURL.getInput() + " is not a valid URL");
                    logger.error(e.getMessage(), e);
                    return;
                }
                OutputStreamWriter wr = null;
                InputStream input = null;
                try {
                    // Collect the request parameters
                    StringBuilder params = new StringBuilder();
                    for (Entry<String, String> entry : parameter.entrySet())
                        params.append(StringUtil.urlEncode(entry.getKey())).append("=")
                                .append(StringUtil.urlEncode(entry.getValue())).append("&");

                    // Send data
                    URLConnection urlcon = urlValue.openConnection();
                    urlcon.setDoOutput(true);
                    wr = new OutputStreamWriter(urlcon.getOutputStream());
                    wr.write(params.toString());
                    wr.flush();

                    // Get the response
                    input = urlcon.getInputStream();
                    importData(this, input, baseUri, RDFFormat.RDFXML, contextUri, "Open Refine",
                            keepSourceCtx.getChecked(), contextEditable.getChecked());

                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    getPage().getPopupWindowInstance().showError(e.getMessage());

                } finally {
                    stat.hide(true);
                    IOUtils.closeQuietly(input);
                    IOUtils.closeQuietly(wr);
                }
            } else {
                stat.hide(true);
                getPage().getPopupWindowInstance().showError("All marked fields should be filled out");
            }
        }
    };
}

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
 *///from   ww w  .  j  a va 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.example.abrahamsofer.ident.Camera2Fragment.java

public void sendText() throws UnsupportedEncodingException {
    // Get user defined values
    // Create data variable for sent values to server

    JSONObject toSend = new JSONObject();
    try {//w  ww .  j a va 2s.c o  m
        toSend.put("Price", price);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String text = "";
    BufferedReader reader = null;

    // Send data
    try {
        // Defined URL  where to send data
        URL url = new URL(serverAddress);
        // Send POST data request

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(toSend.toString());
        wr.flush();

        // Get the server response

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
        }

        text = sb.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {

            reader.close();
        }

        catch (Exception ex) {
        }
    }

    // Show response on activity

}

From source file:com.util.httpHistorial.java

public List<Llamadas> getHistorial(String idAccount, String page, String max, String startDate, String endDate,
        String destination) {// w  w w .j  a  v  a 2 s .c  o m

    // String idAccount = "2";
    // String page = "1";
    // String max = "10";
    //String startDate = "2016-09-20 00:00:00";
    // String endDate = "2016-10-30 23:59:59";
    // String destination = "";
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/cdrs/history/" + idAccount + ".json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(page, "UTF-8");
            data += "&" + URLEncoder.encode("max", "UTF-8") + "=" + URLEncoder.encode(max, "UTF-8");
            data += "&" + URLEncoder.encode("startDate", "UTF-8") + "=" + URLEncoder.encode(startDate, "UTF-8");
            data += "&" + URLEncoder.encode("endDate", "UTF-8") + "=" + URLEncoder.encode(endDate, "UTF-8");
            data += "&" + URLEncoder.encode("destination", "UTF-8") + "="
                    + URLEncoder.encode(destination, "UTF-8");
            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println("DATOS ENVIADOS DEL SERVIDOR " + sb.toString());

    System.out.println(
            "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    // JSONArray dataJson = new JSONArray();
    //  dataJson = objJason.getJSONArray("data");
    String jdata = objJason.optString("data");
    String mensaje = objJason.optString("message");
    System.out.println("\n\n MENSAJE DEL SERVIDOR " + mensaje);
    //System.out.println(" el objeto jdata es "+jdata);
    objJason = new JSONObject(jdata);
    //  System.out.println("objeto normal 1 " + objJason.toString());
    //
    jdata = objJason.optString("items");
    // System.out.println("\n\n el objeto jdata es " + jdata);
    JSONArray jsonArray = new JSONArray();
    Gson gson = new Gson();
    //objJason = gson.t
    jsonArray = objJason.getJSONArray("items");
    // System.out.println("\n\nEL ARRAY FINAL ES " + jsonArray.toString());

    List<Llamadas> llamadas = new ArrayList<Llamadas>();

    for (int i = 0; i < jsonArray.length(); i++) {
        Llamadas llamada = new Llamadas();
        llamada.setNo(i + 1);
        llamada.setInicioLLamada(jsonArray.getJSONObject(i).getString("callstart"));
        llamada.setNumero(jsonArray.getJSONObject(i).getString("callednum"));
        llamada.setPais_operador(jsonArray.getJSONObject(i).getString("notes"));
        llamada.setDuracionSegundos(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("billseconds")));
        llamada.setCostoTotal(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("cost")));
        llamada.setCostoMinuto(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("rate_cost")));

        long minutos = Long.parseLong(llamada.getDuracionSegundos()) / 60;
        llamada.setDuracionMinutos(minutos);

        llamadas.add(llamada);

    }

    for (int i = 0; i < llamadas.size(); i++) {
        System.out.print("\n\nNo" + llamadas.get(i).getNo());
        System.out.print("  Fecna " + llamadas.get(i).getInicioLLamada());
        System.out.print("  Numero " + llamadas.get(i).getNumero());
        System.out.print("  Pais-Operador " + llamadas.get(i).getPais_operador());
        System.out.print("  Cantidad de segundos " + llamadas.get(i).getDuracionSegundos());
        System.out.print("  Costo total " + llamadas.get(i).getCostoTotal());
        System.out.print("  costo por minuto " + llamadas.get(i).getCostoMinuto());
        System.out.print("  costo por minuto " + llamadas.get(i).getDuracionMinutos());

    }

    /**
     * List<String> list = new ArrayList<String>(); for (int i = 0; i <
     * jsonArray.length(); i++) { list.add(String.valueOf(i));
     * list.add(jsonArray.getJSONObject(i).getString("callstart"));
     * list.add(jsonArray.getJSONObject(i).getString("callednum"));
     * list.add(jsonArray.getJSONObject(i).getString("notes"));
     * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("cost")));
     * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("billseconds")));
     * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("rate_cost")));
     * } System.out.println("\n\nel array java contiene " +
     * list.toString());
     *
     */
    return llamadas;
}

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

public String addUserEntryForEmails(String loginid, User user, UserLogin userLogin, String pwdtext,
        boolean isPasswordText) throws ServiceException {
    String returnStr = "";
    try {// w ww.j a  va2  s.c  o  m
        String baseURLFormat = storageHandlerImpl.GetSOAPServerUrl();
        String url = baseURLFormat + "defaultUserEntry.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");
        String userName = userLogin.getUserName() + "_" + user.getCompany().getSubDomain();
        String strParam = "loginid=" + loginid + "&userid=" + user.getUserID() + "&username=" + userName
                + "&password=" + userLogin.getPassword() + "&pwdtext=" + pwdtext + "&fullname="
                + (user.getFirstName() + user.getLastName()) + "&isadmin=0&ispwdtest=" + isPasswordText;
        PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.println(strParam);
        pw.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line = "";
        while ((line = in.readLine()) != null) {
            returnStr += line;
        }
        in.close();
        returnStr = returnStr.replaceAll("\\s+", " ").trim();
        JSONObject emailresult = new JSONObject(returnStr);
        if (Boolean.parseBoolean(emailresult.getString("success"))) {
            user.setUser_hash(emailresult.getString("pwd"));
        }
    } catch (IOException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (JSONException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return returnStr;
}

From source file:com.allblacks.utils.web.HttpUtil.java

/**
 * Gets data from URL as char[] throws {@link RuntimeException} If anything
 * goes wrong/*from w ww  . j av a 2 s.  c o m*/
 * 
 * @return The content of the URL as a char[]
 * @throws java.io.IOException
 */
public char[] postDataAsCharArray(String url, String contentType, String contentName, char[] content)
        throws IOException {

    URLConnection urlc = null;
    OutputStream os = null;
    InputStream is = null;
    CharArrayWriter dat = null;
    BufferedReader reader = null;
    String boundary = "" + new Date().getTime();

    try {
        urlc = new URL(url).openConnection();
        urlc.setDoOutput(true);
        urlc.setRequestProperty(HttpUtil.CONTENT_TYPE,
                "multipart/form-data; boundary=---------------------------" + boundary);

        String message1 = "-----------------------------" + boundary + HttpUtil.BNL;
        message1 += "Content-Disposition: form-data; name=\"nzbfile\"; filename=\"" + contentName + "\""
                + HttpUtil.BNL;
        message1 += "Content-Type: " + contentType + HttpUtil.BNL;
        message1 += HttpUtil.BNL;
        String message2 = HttpUtil.BNL + "-----------------------------" + boundary + "--" + HttpUtil.BNL;

        os = urlc.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName(HttpUtil.UTF_8)));

        writer.write(message1);
        writer.write(content);
        writer.write(message2);
        writer.flush();

        dat = new CharArrayWriter();
        if (urlc.getContentEncoding() != null && urlc.getContentEncoding().equalsIgnoreCase(HttpUtil.GZIP)) {
            is = new GZIPInputStream(urlc.getInputStream());
        } else {
            is = urlc.getInputStream();
        }
        reader = new BufferedReader(new InputStreamReader(is, Charset.forName(HttpUtil.UTF_8)));

        int c;
        while ((c = reader.read()) != -1) {
            dat.append((char) c);
        }
    } catch (IOException exception) {
        throw exception;
    } finally {
        try {
            reader.close();
            os.close();
            is.close();
        } catch (Exception e) {
            // we do not care about this
        }
    }

    return dat.toCharArray();
}

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

private InvocationResult doInvokePOST(Object request, Map<String, String> httpHeaders, int retries)
        throws Exception {
    if (retries < 0)
        throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(request));
    logger.debug("POST request to: " + endpointURL + " with body " + request);
    URL url = new URL(endpointURL);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);//from ww w .ja  v a 2 s  .c o m
    for (String key : httpHeaders.keySet()) {
        conn.setRequestProperty(key, httpHeaders.get(key));
    }
    String theRequest = null;
    if (request instanceof Element) {
        theRequest = xmlUtil.toString((Element) request);
        conn.setRequestProperty("Content-Type", "application/xml");
    } else if (request instanceof String) {
        theRequest = (String) request;
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    }
    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
    theRequest = theRequest.trim();
    w.write(theRequest);
    w.close();
    BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder b = new StringBuilder();
    String temp;
    while ((temp = r.readLine()) != null) {
        b.append(temp);
        b.append("\n");
    }
    String originalResult = b.toString();
    String result = originalResult.trim();
    if (!result.startsWith("<")) // wrap non-xml results (e.g., CSV files)
        result = "<doc>" + result + "</doc>";
    Element resultElement = xmlUtil.toElement(result);
    InvocationResult invResult = new InvocationResult(resultElement, originalResult);
    invResult.getHeaders().putAll(conn.getHeaderFields());
    return invResult;
}

From source file:com.apache.ivy.BasicURLHandler.java

public InputStream openStreamPost(URL url, ArrayList<NameValuePair> postData) throws IOException {
    // Install the IvyAuthenticator
    if ("http".equals(url.getProtocol()) || "https".equals(url.getProtocol())) {
        IvyAuthenticator.install();//from   w ww . j  a v a 2  s .  co  m
    }

    URLConnection conn = null;
    try {
        url = normalizeToURL(url);
        conn = url.openConnection();
        conn.setRequestProperty("User-Agent", "Apache Ivy/1.0");// + Ivy.getIvyVersion());
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");

        if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpCon = (HttpURLConnection) conn;

            httpCon.setRequestMethod("POST");
            httpCon.setDoInput(true);
            httpCon.setDoOutput(true);

            byte[] postDataBytes = getQuery(postData).getBytes(Charset.forName("UTF-8"));
            String contentLength = String.valueOf(postDataBytes.length);
            httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpCon.setRequestProperty("Content-Length", contentLength);
            httpCon.setDoOutput(true);

            httpCon.connect();

            httpCon.getOutputStream().write(postDataBytes);

            conn.getOutputStream().flush();

            if (!checkStatusCode(url, httpCon)) {
                throw new IOException("The HTTP response code for " + url + " did not indicate a success."
                        + " See log for more detail.");
            }

        }

        // read the output
        InputStream inStream = getDecodingInputStream(conn.getContentEncoding(), conn.getInputStream());
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[BUFFER_SIZE];
        int len;
        while ((len = inStream.read(buffer)) > 0) {
            outStream.write(buffer, 0, len);
        }

        return new ByteArrayInputStream(outStream.toByteArray());
    } finally {
        disconnect(conn);
    }
}