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:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Send a bean as a web form POST and return an XML InputSource from the
 * response content./* w w  w.j  a va  2s  .  com*/
 * 
 * @param bean
 *        the bean
 * @param url
 *        the URL to POST to
 * @param attributes
 *        extra POST attributes and bean override values
 * @return an InputSource to the response content XML
 */
protected InputSource webFormPost(BeanWrapper bean, String url, Map<String, ?> attributes) {
    try {
        URLConnection conn = getURLConnection(url, HTTP_METHOD_POST);

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        writeURLEncodedBeanProperties(bean, attributes, out);

        return getInputSourceFromURLConnection(conn);
    } catch (IOException e) {
        if (log.isTraceEnabled()) {
            log.trace("IOException posting " + bean + " to " + url, e);
        } else if (log.isDebugEnabled()) {
            log.debug("Unable to post data to " + url + ": " + e.getMessage());
        }
        throw new RuntimeException(e);
    }
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

public List<Group> findSimpleGroup(String search) {

    List<Group> searchResults = new ArrayList<Group>();
    Group entry = null;/* w w  w  .  j a  v  a  2  s  .  c o m*/
    StringBuilder queryString = new StringBuilder();

    if (search != null && !search.trim().isEmpty()) {
        queryString.append("searchCriteria=");
        queryString.append(search.trim());
    }

    LOG.debug("Group serach QueryString will be : " + queryString.toString());
    try {
        URLConnection connection = new URL(GROUP_SEARCH_URL).openConnection();

        connection.setDoOutput(true); // Triggers POST.
        connection.setRequestProperty("Accept-Charset", DEFAULT_CHARACTER_SET);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + DEFAULT_CHARACTER_SET);
        OutputStream output = null;

        output = connection.getOutputStream();
        output.write(queryString.toString().getBytes(DEFAULT_CHARACTER_SET));

        String jsonData = null;
        jsonData = IOUtils.toString(connection.getInputStream(), DEFAULT_CHARACTER_SET);

        LOG.debug("Attempting to parse JSON using JSON.simple.");
        LOG.debug(jsonData);

        JSONParser parser = new JSONParser();

        Object rootObj = parser.parse(jsonData);

        JSONObject jsonObject = (JSONObject) rootObj;

        JSONArray groups = (JSONArray) jsonObject.get("group");
        for (Object group : groups) {
            JSONObject g = (JSONObject) group;
            LOG.debug(g.toString());
            entry = (Group) getApplicationContext().getBean("directoryGroup");
            entry.setDN((String) g.get("distinguishedName"));
            if (null != g.get("errors") && (g.get("errors")) instanceof JSONObject) {
                JSONObject error = (JSONObject) g.get("errors");
                if (null != error.get("global")) {
                    JSONObject globalError = (JSONObject) error.get("global");
                    entry.setDisplayName("Error");
                    List<String> tDesc = new ArrayList<String>();
                    tDesc.add((String) globalError.get("description"));
                    entry.setDescriptions(tDesc);
                }
            } else {
                if (null != g.get("description")) {
                    if ((g.get("description")) instanceof String) {
                        List<String> tDesc = new ArrayList<String>();
                        tDesc.add((String) g.get("description"));
                        entry.setDescriptions(tDesc);
                    } else {
                        entry.setDescriptions((List) g.get("description"));
                    }
                }
                entry.setDisplayName((String) g.get("displayName"));
                entry.setEmail((String) g.get("email"));
            }
            searchResults.add(entry);
        }

    } catch (IOException ioe) {
        LOG.error(ioe.getLocalizedMessage(), ioe);
    } catch (ParseException pe) {
        LOG.error(pe.getLocalizedMessage(), pe);
    }
    return searchResults;
}

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

public JSONObject getRecentEmailDetails(HttpServletRequest request, String recid, String emailadd)
        throws ServiceException {
    JSONObject jobj = new JSONObject();
    try {//w  w w  .  j  a  v  a2  s .  c o  m
        DateFormat userdft = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        String dateFormatId = sessionHandlerImpl.getDateFormatID(request);
        String timeFormatId = sessionHandlerImpl.getUserTimeFormat(request);
        String timeZoneDiff = sessionHandlerImpl.getTimeZoneDifference(request);
        String userid = sessionHandlerImpl.getUserid(request);
        userdft = KwlCommonTablesDAOObj.getUserDateFormatter(dateFormatId, timeFormatId, timeZoneDiff);
        String url = StorageHandler.GetSOAPServerUrl();
        String res = "";
        String str = "";
        String pass = "";
        String currUser = sessionHandlerImplObj.getUserName(request) + "_";
        String jsonStr = profileHandlerDAOObj.getUser_hash(userid);
        //String emailadd = request.getParameter("email");
        JSONObject currUserAuthInfo = new JSONObject(jsonStr);
        if (currUserAuthInfo.has("userhash")) {
            currUser += currUserAuthInfo.getString("subdomain");
            pass = currUserAuthInfo.getString("userhash");
        }
        str = "username=" + currUser + "&user_hash=" + pass;
        str = str
                + "&action=EmailUIAjax&emailUIAction=rebuildShowAccount&krawler_body_only=true&module=Emails&to_pdf=true";

        URL u = new URL(url + "krawlermails.php");
        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();
        boolean flag = true;
        try {
            JSONArray jarr = new JSONArray(res);
        } catch (JSONException ex) {
            flag = false;
        }
        if (flag) {
            String ieId = "";
            JSONArray jarr = new JSONArray(res);
            for (int cnt = 0; cnt < jarr.length(); cnt++) {
                JSONObject tempObj = jarr.getJSONObject(cnt);
                if (!StringUtil.isNullOrEmpty(tempObj.getString("value"))) {
                    ieId += tempObj.getString("value") + ",";
                }
            }

            if (ieId.length() > 0) {
                ieId = ieId.substring(0, ieId.length() - 1);
                str = "username=" + currUser + "&user_hash=" + pass;
                str = str + "&ieId=" + ieId + "&fromaddr=" + emailadd + "&mbox=INBOX";
                res = StringUtil.makeExternalRequest(url + "getSendersMails.php", str);
            } else {
                res = "{\"count\":0,\"data\":{}}";
            }

            JSONObject resJobj = new JSONObject();
            try {
                resJobj = new JSONObject(res);
            } catch (Exception ex) {
                resJobj = new JSONObject("{\"count\":0,\"data\":{}}");
            }
            JSONArray FinalArr = new JSONArray();
            if (resJobj.optInt("count", 0) > 0) {
                JSONArray jArr = resJobj.getJSONArray("data");
                for (int i = 0; i < jArr.length(); i++) {
                    JSONObject tmpobj = jArr.getJSONObject(i);
                    Date sendDateObj = sdf.parse(tmpobj.getString("senddate"));
                    String senddate = userdft.format(sendDateObj);
                    JSONObject obj = new JSONObject();
                    obj.put("docid", tmpobj.getString("imap_uid"));
                    obj.put("subject", tmpobj.getString("subject"));
                    obj.put("fromaddr", tmpobj.getString("fromaddr"));
                    obj.put("toaddr", tmpobj.getString("toaddr"));
                    obj.put("senddate", senddate);
                    obj.put("ie_id", tmpobj.getString("ie_id"));
                    obj.put("seen", tmpobj.getString("seen"));
                    //                    obj.put("time", AuthHandler.getUserDateFormatter(request, session).format(sdf.parse(tmpobj.getString("senddate"))));
                    obj.put("time", senddate);
                    obj.put("timeobj", sendDateObj);
                    obj.put("details", tmpobj.getString("subject"));
                    obj.put("folder", "Inbox");
                    obj.put("imgsrc", "../../images/inbox.png");
                    FinalArr.put(obj);
                }
            }

            // fetched Sent Items

            // get sent folder id
            //            String sentid = "";
            //            str = "username="+currUser+"&user_hash="+pass;
            //            str = str + "&action=EmailUIAjax&emailUIAction=refreshKrawlerFolders&krawler_body_only=true&module=Emails&to_pdf=true";
            //            res = StringUtil.makeExternalRequest(url+"getSendersMails.php",str);
            //            resJobj = new JSONObject(res);
            //            if(resJobj.has("children")) {
            //                JSONArray childArray = resJobj.getJSONArray("children");
            //                for(int cnt = 0; cnt< childArray.length(); cnt++) {
            //                    if(childArray.getJSONObject(cnt).getString("folder_type").equals("folder_type")) {
            //                        sentid = childArray.getJSONObject(cnt).getString("folder_type");
            //                    }
            //                }
            //            }
            //
            //            if(!StringUtil.isNullOrEmpty(sentid)) {
            //                str = "username="+currUser+"&user_hash="+pass;
            //                str = str + "&action=EmailUIAjax&emailUIAction=getMessageListKrawlerFoldersXML&module=Emails&to_pdf=true&start=0&limit=20&forceRefresh=false&mbox=Sent%20Emails&ieId="+sentid;
            //                res = StringUtil.makeExternalRequest(url+"krawlermails.php",str);
            //            }

            str = "userid=" + userid + "&username=" + currUser + "&user_hash=" + pass;
            str = str + "&fromaddr=" + emailadd + "&mbox=sent";
            res = StringUtil.makeExternalRequest(url + "getSendersMails.php", str);
            try {
                resJobj = new JSONObject(res);
            } catch (Exception ex) {
                resJobj = new JSONObject("{\"count\":0,\"data\":{}}");
            }
            if (resJobj.optInt("count", 0) > 0) {
                JSONArray jArr = resJobj.getJSONArray("data");
                for (int i = 0; i < jArr.length(); i++) {
                    JSONObject tmpobj = jArr.getJSONObject(i);
                    Date sendDateObj = sdf.parse(tmpobj.getString("date_sent"));
                    String senddate = userdft.format(sendDateObj);
                    JSONObject obj = new JSONObject();
                    obj.put("docid", tmpobj.getString("id"));
                    obj.put("subject", tmpobj.getString("name"));
                    obj.put("fromaddr", tmpobj.getString("from_addr"));
                    obj.put("toaddr", tmpobj.getString("to_addrs"));
                    obj.put("senddate", senddate);
                    //                    obj.put("ie_id", tmpobj.getString("ieId"));
                    obj.put("seen", tmpobj.getString("status").equals("unread") ? 0 : 1);
                    obj.put("time", senddate);
                    obj.put("details", tmpobj.getString("name"));
                    obj.put("timeobj", sendDateObj);
                    obj.put("folder", "Sent Item");
                    obj.put("imgsrc", "../../images/outbox.png");
                    FinalArr.put(obj);
                }
            }

            for (int i = 0; i < FinalArr.length(); i++) {
                for (int j = 0; j < FinalArr.length(); j++) {
                    if (((Date) (FinalArr.getJSONObject(i).get("timeobj")))
                            .after((Date) (FinalArr.getJSONObject(j).get("timeobj")))) {
                        JSONObject jobj1 = FinalArr.getJSONObject(i);
                        FinalArr.put(i, FinalArr.getJSONObject(j));
                        FinalArr.put(j, jobj1);
                    }
                }
            }
            jobj.put("emailList", FinalArr);
        } else {
            jobj.put("emailList", new JSONArray());
        }

    } catch (JSONException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (SessionExpiredException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (HibernateException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (Exception e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return jobj;
}

From source file:org.apache.xmlrpc.applet.SimpleXmlRpcClient.java

/**
 * Generate an XML-RPC request and send it to the server. Parse the result
 * and return the corresponding Java object.
 *
 * @exception XmlRpcException If the remote host returned a fault message.
 * @exception IOException If the call could not be made for lower level
 *          problems./*from   w  w  w .  j  a  va 2s  . co m*/
 */
public Object execute(String method, Vector arguments) throws XmlRpcException, IOException {
    fault = false;
    long now = System.currentTimeMillis();
    try {
        StringBuffer strbuf = new StringBuffer();
        XmlWriter writer = new XmlWriter(strbuf);
        writeRequest(writer, method, arguments);
        byte[] request = strbuf.toString().getBytes();
        URLConnection con = url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setAllowUserInteraction(false);
        con.setRequestProperty("Content-Length", Integer.toString(request.length));
        con.setRequestProperty("Content-Type", "text/xml");
        // con.connect ();
        OutputStream out = con.getOutputStream();
        out.write(request);
        out.flush();
        InputStream in = con.getInputStream();
        parse(in);
        System.out.println("result = " + result);
    } catch (Exception x) {
        x.printStackTrace();
        throw new IOException(x.getMessage());
    }
    if (fault) {
        // generate an XmlRpcException
        XmlRpcException exception = null;
        try {
            Hashtable f = (Hashtable) result;
            String faultString = (String) f.get("faultString");
            int faultCode = Integer.parseInt(f.get("faultCode").toString());
            exception = new XmlRpcException(faultCode, faultString.trim());
        } catch (Exception x) {
            throw new XmlRpcException(0, "Invalid fault response");
        }
        throw exception;
    }
    System.out.println("Spent " + (System.currentTimeMillis() - now) + " in request");
    return result;
}

From source file:au.org.ala.layers.dao.LayerIntersectDAOImpl.java

ArrayList<String> remoteSampling(IntersectionFile[] intersectionFiles, double[][] points,
        IntersectCallback callback) {//from   ww  w  .  java  2  s . c  o m
    logger.info("begin REMOTE sampling, number of threads " + intersectConfig.getThreadCount()
            + ", number of layers=" + intersectionFiles.length + ", number of coordinates=" + points.length);

    ArrayList<String> output = null;

    try {
        long start = System.currentTimeMillis();
        URL url = new URL(intersectConfig.getLayerIndexUrl() + "/intersect/batch");
        URLConnection c = url.openConnection();
        c.setDoOutput(true);

        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(c.getOutputStream());
            out.write("fids=");
            for (int i = 0; i < intersectionFiles.length; i++) {
                if (i > 0) {
                    out.write(",");
                }
                out.write(intersectionFiles[i].getFieldId());
            }
            out.write("&points=");
            for (int i = 0; i < points.length; i++) {
                if (i > 0) {
                    out.write(",");
                }
                out.write(String.valueOf(points[i][1]));
                out.write(",");
                out.write(String.valueOf(points[i][0]));
            }
            out.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        JSONObject jo = JSONObject.fromObject(IOUtils.toString(c.getInputStream()));

        String checkUrl = jo.getString("statusUrl");

        //check status
        boolean notFinished = true;
        String downloadUrl = null;
        while (notFinished) {
            //wait 5s before querying status
            Thread.sleep(5000);

            jo = JSONObject.fromObject(IOUtils.toString(new URI(checkUrl).toURL().openStream()));

            if (jo.containsKey("error")) {
                notFinished = false;
            } else if (jo.containsKey("status")) {
                String status = jo.getString("status");

                if ("finished".equals(status)) {
                    downloadUrl = jo.getString("downloadUrl");
                    notFinished = false;
                } else if ("cancelled".equals(status) || "error".equals(status)) {
                    notFinished = false;
                }
            }
        }

        ZipInputStream zis = null;
        CSVReader csv = null;
        InputStream is = null;
        ArrayList<StringBuilder> tmpOutput = new ArrayList<StringBuilder>();
        long mid = System.currentTimeMillis();
        try {
            is = new URI(downloadUrl).toURL().openStream();
            zis = new ZipInputStream(is);
            ZipEntry ze = zis.getNextEntry();
            csv = new CSVReader(new InputStreamReader(zis));

            for (int i = 0; i < intersectionFiles.length; i++) {
                tmpOutput.add(new StringBuilder());
            }
            String[] line;
            int row = 0;
            csv.readNext(); //discard header
            while ((line = csv.readNext()) != null) {
                //order is consistent with request
                for (int i = 2; i < line.length && i - 2 < tmpOutput.size(); i++) {
                    if (row > 0) {
                        tmpOutput.get(i - 2).append("\n");
                    }
                    tmpOutput.get(i - 2).append(line[i]);
                }
                row++;
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (csv != null) {
                try {
                    csv.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        output = new ArrayList<String>();
        for (int i = 0; i < tmpOutput.size(); i++) {
            output.add(tmpOutput.get(i).toString());
            tmpOutput.set(i, null);
        }

        long end = System.currentTimeMillis();

        logger.info("sample time for " + 5 + " layers and " + 3 + " coordinates: get response=" + (mid - start)
                + "ms, write response=" + (end - mid) + "ms");

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return output;
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

@Override
public SearchResultImpl findEntries(SearchCriteria search) {
    SearchResultImpl results = null;/*from ww w.  j  a va  2 s  .  c  om*/
    String searchText = search.getSearchText();
    if (searchText != null && searchText.contains("<script>")) {
        // Do not perform any search
    }
    if (searchText != null && searchText.contains(";")) {
        // Do not perform any search
    } else if (searchText != null && searchText.contains("eval")) {
        // Do not perform any search
    } else {
        results = (SearchResultImpl) getApplicationContext().getBean("searchResult");

        StringBuilder queryString = new StringBuilder();

        if (search.getSearchText() != null && !search.getSearchText().trim().isEmpty()) {
            searchText = searchText.replaceAll("[^\\w\\s]", ""); //Removes all special character
            queryString.append("searchCriteria=");
            queryString.append(searchText.trim());
        } else if (search.getUserName() != null && !search.getUserName().isEmpty()) {
            queryString.append("uniqname=");
            queryString.append(search.getUserName().trim());
        } else {
            if ("starts".equalsIgnoreCase(search.getExactness())) {
                search.setExactness("starts with");
            }
            if (search.getFirstName() != null && !search.getFirstName().trim().isEmpty()) {
                queryString.append("givenName=");
                queryString.append(search.getFirstName().trim());
                queryString.append("&givenNameSearchType=");
                queryString.append(search.getExactness());
                queryString.append("&");
            }
            if (search.getLastName() != null && !search.getLastName().trim().isEmpty()) {
                queryString.append("sn=");
                queryString.append(search.getLastName().trim());
                queryString.append("&snSearchType=");
                queryString.append(search.getExactness());
            }
        }

        LOG.debug("QueryString will be : " + queryString.toString());

        try {
            URLConnection connection = new URL(SEARCH_URL).openConnection();

            connection.setDoOutput(true); // Triggers POST.
            connection.setRequestProperty("Accept-Charset", DEFAULT_CHARACTER_SET);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=" + DEFAULT_CHARACTER_SET);
            OutputStream output = null;

            output = connection.getOutputStream();
            output.write(queryString.toString().getBytes(DEFAULT_CHARACTER_SET));

            InputStream response = connection.getInputStream();
            String contentType = connection.getHeaderField("Content-Type");

            if (contentType != null && "application/json".equalsIgnoreCase(contentType)) {
                //               LOG.debug("Attempting to parse JSON using Gson.");

                List<Person> peeps = new ArrayList<Person>();
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(response, DEFAULT_CHARACTER_SET));

                    String jsonData = IOUtils.toString(response, DEFAULT_CHARACTER_SET);

                    LOG.debug("Attempting to parse JSON using JSON.simple.");
                    LOG.debug(jsonData);

                    JSONParser parser = new JSONParser();

                    Object rootObj = parser.parse(jsonData);

                    JSONObject jsonObject = (JSONObject) rootObj;
                    JSONArray jsonPerson = (JSONArray) jsonObject.get("person");
                    for (Object o : jsonPerson) {
                        peeps.add(parsePerson((JSONObject) o));
                    }
                } catch (UnsupportedEncodingException uee) {
                    LOG.error(uee.getLocalizedMessage());
                } catch (IOException ioe) {
                    LOG.error(ioe.getLocalizedMessage());
                } catch (ParseException pe) {
                    LOG.error(pe.getLocalizedMessage(), pe);
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException logOrIgnore) {
                            LOG.error(logOrIgnore.getLocalizedMessage());
                        }
                    }
                }
                results.setPeople(peeps);
            } else {
                LOG.debug("Content type was not application/json.");
            }
        } catch (IOException ioe) {
            LOG.error(ioe.getLocalizedMessage());
        }
        LOG.debug("Searching for groups.");
        results.setGroups(searchForGroup(search));
    }
    return results;
}

From source file:org.ixdhof.speechrecognizer.Recognizer.java

private void do_recognize(String waveString, String language) throws Exception {
    //"en-US"/*from  w  w  w.  j a v a 2  s.co  m*/

    URL url;
    URLConnection urlConn;
    OutputStream outputStream;
    BufferedReader br;

    File waveFile = new File(parent.sketchPath(waveString));

    FlacEncoder flacEncoder = new FlacEncoder();
    File flacFile = new File(waveFile + ".flac");

    flacEncoder.convertWaveToFlac(waveFile, flacFile);

    // URL of Remote Script.
    url = new URL(GOOGLE_RECOGNIZER_URL_NO_LANG + language);

    // Open New URL connection channel.
    urlConn = url.openConnection();

    // we want to do output.
    urlConn.setDoOutput(true);

    // No caching
    urlConn.setUseCaches(false);

    // Specify the header content type.
    urlConn.setRequestProperty("Content-Type", "audio/x-flac; rate=8000");

    // Send POST output.
    outputStream = urlConn.getOutputStream();

    FileInputStream fileInputStream = new FileInputStream(flacFile.getAbsolutePath());

    byte[] buffer = new byte[256];

    while ((fileInputStream.read(buffer, 0, 256)) != -1) {
        outputStream.write(buffer, 0, 256);
    }

    fileInputStream.close();
    outputStream.close();

    // Get response data.
    br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

    response = br.readLine();

    br.close();

    flacFile.delete();
    waveFile.delete();

    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(response);
        JSONObject jsonObject = (JSONObject) obj;
        HashMap returnValues = new HashMap();

        if (response.contains("utterance")) {
            status = (int) (long) (Long) jsonObject.get("status");
            id = (String) jsonObject.get("id");
            JSONArray hypotheses_array = (JSONArray) jsonObject.get("hypotheses");
            JSONObject hypotheses = (JSONObject) hypotheses_array.get(0);
            utterance = (String) hypotheses.get("utterance");
            confidence = (float) (double) (Double) hypotheses.get("confidence");
        } else {
            utterance = null;
        }

        if (recognizerEvent != null) {
            try {
                recognizerEvent.invoke(parent, new Object[] { utterance });
            } catch (Exception e) {
                System.err.println("Disabling recognizerEvent()");
                e.printStackTrace();
                recognizerEvent = null;
            }
        }
    } catch (Exception e) {
        parent.println(e);
    }

    recognizing = false;
}

From source file:com.util.httpRecargas.java

public List<Recarga> getRecargas(String idAccount, String page, String max, String startDate, String endDate) {

    //   System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/recharges/history/" + idAccount + ".json";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;/*from   w  w w.j a v a  2  s  . co  m*/
    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");
            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 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<String> list = new ArrayList<String>();
            for (int i = 0; i
        < jsonArray.length(); i++) {
    list.add(String.valueOf(i));
    list.add(jsonArray.getJSONObject(i).getString("created_date"));
    list.add(jsonArray.getJSONObject(i).getString("description"));
    list.add(String.valueOf(jsonArray.getJSONObject(i).getInt("credit")));
    list.add(jsonArray.getJSONObject(i).getString("before_balance"));
    list.add(jsonArray.getJSONObject(i).getString("after_balance"));
            }
            System.out.println("\n\nel array java contiene "+ list.toString());
    */
    List<Recarga> recargas = new ArrayList<Recarga>();

    for (int i = 0; i < jsonArray.length(); i++) {
        Recarga recarga = new Recarga();
        recarga.setNo(i);
        recarga.setFecha(jsonArray.getJSONObject(i).getString("created_date"));
        recarga.setDescripcion(jsonArray.getJSONObject(i).getString("description"));
        recarga.setMonto(String.valueOf(jsonArray.getJSONObject(i).getInt("credit")));
        recarga.setSaldoAnterior(jsonArray.getJSONObject(i).getString("before_balance"));
        recarga.setSaldoPosterior(jsonArray.getJSONObject(i).getString("after_balance"));

        recargas.add(recarga);
    }

    for (int i = 0; i < recargas.size(); i++) {
        System.out.print("\n\nNo" + recargas.get(i).getNo());
        System.out.print("\nFecna " + recargas.get(i).getFecha());
        System.out.print("\nDescripcion " + recargas.get(i).getDescripcion());
        System.out.print("\nMonto " + recargas.get(i).getMonto());
        System.out.print("\nSaldo Anterior " + recargas.get(i).getSaldoAnterior());
        System.out.print("\nSaldo Posterior" + recargas.get(i).getSaldoPosterior());

    }
    return recargas;

}

From source file:org.tightblog.service.WeblogEntryManager.java

public ValidationResult makeAkismetCall(String apiRequestBody) throws IOException {
    if (!StringUtils.isBlank(akismetApiKey)) {
        URL url = new URL("http://" + akismetApiKey + ".rest.akismet.com/1.1/comment-check");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);/*from ww  w  . j av  a  2  s . c  om*/

        conn.setRequestProperty("User_Agent", "TightBlog");
        conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=utf8");
        conn.setRequestProperty("Content-length", Integer.toString(apiRequestBody.length()));

        OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
        osr.write(apiRequestBody, 0, apiRequestBody.length());
        osr.flush();
        osr.close();

        try (InputStreamReader isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr)) {
            String response = br.readLine();
            if ("true".equals(response)) {
                if ("discard".equalsIgnoreCase(conn.getHeaderField("X-akismet-pro-tip"))) {
                    return ValidationResult.BLATANT_SPAM;
                }
                return ValidationResult.SPAM;
            }
        }
    }

    return ValidationResult.NOT_SPAM;
}

From source file:org.geotools.data.shapefile.ShpFiles.java

/**
 * Opens a output stream for the indicated file. A write lock is requested at the method call and
 * released on close./*w  ww.  j a v a2s . c  o m*/
 * 
 * @param type
 *           the type of file to open the stream to.
 * @param requestor
 *           the object requesting the stream
 * @return an output stream
 * 
 * @throws IOException
 *            if a problem occurred opening the stream.
 */
public OutputStream getOutputStream(ShpFileType type, final FileWriter requestor) throws IOException {
    final URL url = acquireWrite(type, requestor);

    try {

        OutputStream out;
        if (isLocal()) {
            File file = DataUtilities.urlToFile(url);
            out = new FileOutputStream(file);
        } else {
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            out = connection.getOutputStream();
        }

        FilterOutputStream output = new FilterOutputStream(out) {

            private volatile boolean closed = false;

            @Override
            public void close() throws IOException {
                try {
                    super.close();
                } finally {
                    if (!closed) {
                        closed = true;
                        unlockWrite(url, requestor);
                    }
                }
            }

        };

        return output;
    } catch (Throwable e) {
        unlockWrite(url, requestor);
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else if (e instanceof Error) {
            throw (Error) e;
        } else {
            throw new RuntimeException(e);
        }
    }
}