List of usage examples for java.io BufferedReader read
public int read() throws IOException
From source file:com.ehsy.solr.util.SimplePostTool.java
private static boolean checkResponseCode(HttpURLConnection urlc) throws IOException { if (urlc.getResponseCode() >= 400) { warn("Solr returned an error #" + urlc.getResponseCode() + " (" + urlc.getResponseMessage() + ") for url: " + urlc.getURL()); Charset charset = StandardCharsets.ISO_8859_1; final String contentType = urlc.getContentType(); // code cloned from ContentStreamBase, but post.jar should be standalone! if (contentType != null) { int idx = contentType.toLowerCase(Locale.ROOT).indexOf("charset="); if (idx > 0) { charset = Charset.forName(contentType.substring(idx + "charset=".length()).trim()); }/*ww w .j a va 2 s . c o m*/ } // Print the response returned by Solr try (InputStream errStream = urlc.getErrorStream()) { if (errStream != null) { BufferedReader br = new BufferedReader(new InputStreamReader(errStream, charset)); final StringBuilder response = new StringBuilder("Response: "); int ch; while ((ch = br.read()) != -1) { response.append((char) ch); } warn(response.toString().trim()); } } return false; } return true; }
From source file:org.openmrs.util.databasechange.SourceMySqldiffFile.java
/** * @param cmdWithArguments//from w ww. j a v a 2 s . c o m * @param wd * @param the string * @return process exit value */ private Integer execCmd(File wd, String[] cmdWithArguments, StringBuffer out) throws Exception { log.debug("executing command: " + Arrays.toString(cmdWithArguments)); Integer exitValue = -1; // Needed to add support for working directory because of a linux // file system permission issue. if (!OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM) { wd = null; } Process p = (wd != null) ? Runtime.getRuntime().exec(cmdWithArguments, null, wd) : Runtime.getRuntime().exec(cmdWithArguments); out.append("Normal cmd output:\n"); Reader reader = new InputStreamReader(p.getInputStream()); BufferedReader input = new BufferedReader(reader); int readChar = 0; while ((readChar = input.read()) != -1) { out.append((char) readChar); } input.close(); reader.close(); out.append("ErrorStream cmd output:\n"); reader = new InputStreamReader(p.getErrorStream()); input = new BufferedReader(reader); readChar = 0; while ((readChar = input.read()) != -1) { out.append((char) readChar); } input.close(); reader.close(); exitValue = p.waitFor(); log.debug("Process exit value: " + exitValue); log.debug("execCmd output: \n" + out.toString()); return exitValue; }
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.c o 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:network.HttpClientAdaptor.java
public String doGet(String url) { try {//from w w w .j a va 2 s.c o m HttpGet httpGet = new HttpGet(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();//?????????? httpGet.setConfig(requestConfig); CloseableHttpResponse response = this.httpclient.execute(httpGet, localContext); BufferedReader br = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), this.encode)); String htmlStr = null; int c = 0; StringBuilder temp = new StringBuilder(); while ((c = br.read()) != -1) { temp.append((char) c); } htmlStr = temp.toString(); httpGet.releaseConnection(); httpGet.completed(); return htmlStr; } catch (IOException ex) { Logger.getLogger(HttpClientAdaptor.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.interacciones.mxcashmarketdata.driver.process.DriverServerHandler.java
@Override public void messageReceived(IoSession session, Object message) throws Exception { LOGGER.debug("Received : " + message); IoBuffer ib = (IoBuffer) message;/*ww w . ja v a 2 s . co m*/ try { InputStream is = ib.asInputStream(); /** * We have to create them b/c they are needed as arguments in the constructors. */ InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); long time = System.currentTimeMillis(); int data = br.read(); int count = 1; while (data != -1) { char theChar = (char) data; strbuf.append(theChar); count++; if (data == 13) { count = 0; long tmpSequence = 0; String strSequence; strbuf.deleteCharAt(strbuf.length() - 1); int sizestrbuf = strbuf.length(); try { //Message reader, Sequence number strSequence = strbuf.substring(sizestrbuf - MSG_LENGTH, sizestrbuf - MSG_SEQUENCE); tmpSequence = Long.parseLong(strSequence); if (myMsgSequence == tmpSequence) { myMsgSequence = countSequence.next(); /** * Sending message File, OpenMama, Queuing * Implement Interface MessageProcessing */ messageProcessing.receive( strbuf.toString().substring(sizestrbuf - MSG_LENGTH, sizestrbuf), tmpSequence); flagRetransmission = true; } else if (flagRetransmission) { System.out.print( "\r[" + df.format(new Date()) + "] Sequence retransmission: " + myMsgSequence); MessageRetransmission msgRetra = new MessageRetransmission(); msgRetra.setSequencelong(myMsgSequence); msgRetra.MsgConstruct(); IoBuffer io = IoBuffer.wrap(msgRetra.getByte()); LOGGER.info("Sequence Retransmission " + myMsgSequence); LOGGER.debug(msgRetra.toString()); session.write(io.duplicate()); flagRetransmission = false; } } catch (Exception e) { e.printStackTrace(); LOGGER.error("Error: " + e.getMessage()); LOGGER.error(strbuf.toString()); } strbuf.delete(0, strbuf.length()); //What's more expensive? delete or read the object. } data = br.read(); } time = System.currentTimeMillis() - time; globlaCount = globlaCount + time; isr.close(); br.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:org.n52.wps.server.feed.FeedServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { /*//from w w w . ja va 2 s . c o m * how can the new remote repository be posted?! * 1. complete xml snippet * 2. what else?! */ RemoteRepository newRemoteRepo = null; OutputStream out = res.getOutputStream(); try { InputStream is = req.getInputStream(); if (req.getParameterMap().containsKey("request")) { is = new ByteArrayInputStream(req.getParameter("request").getBytes("UTF-8")); } // WORKAROUND cut the parameter name "request" of the stream BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringWriter sw = new StringWriter(); int k; while ((k = br.read()) != -1) { sw.write(k); } LOGGER.debug(sw.toString()); String s; String reqContentType = req.getContentType(); if (sw.toString().startsWith("request=")) { if (reqContentType.equalsIgnoreCase("text/plain")) { s = sw.toString().substring(8); } else { s = URLDecoder.decode(sw.toString().substring(8), "UTF-8"); } LOGGER.debug(s); } else { s = sw.toString(); } newRemoteRepo = RemoteRepositoryDocument.Factory.parse(s).getRemoteRepository(); addNewRemoteRepository(newRemoteRepo); res.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error occured"); } out.flush(); out.close(); }
From source file:network.HttpClientAdaptor.java
public String doPost(String url, List<NameValuePair> parameters) { try {//ww w. ja v a 2 s . com HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();//?????????? httpPost.setConfig(requestConfig); httpPost.setEntity(new UrlEncodedFormEntity(parameters)); CloseableHttpResponse response = this.httpclient.execute(httpPost, localContext); BufferedReader br = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), this.encode)); String htmlStr = null; int c = 0; StringBuilder temp = new StringBuilder(); while ((c = br.read()) != -1) { temp.append((char) c); } htmlStr = temp.toString(); httpPost.completed(); httpPost.releaseConnection(); return htmlStr; } catch (UnsupportedEncodingException ex) { Logger.getLogger(HttpClientAdaptor.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(HttpClientAdaptor.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.util.httpHistorial.java
public List<Llamadas> getHistorial(String idAccount, String page, String max, String startDate, String endDate, String destination) {//from w w w . j av a2s .co 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:org.onebusaway.util.rest.RestApiLibrary.java
public String getContentsOfUrlAsString(URL requestUrl) throws Exception { URLConnection conn = requestUrl.openConnection(); conn.setConnectTimeout(connectionTimeout); conn.setReadTimeout(readTimeout);//from ww w. j a v a 2 s . co m InputStream inStream = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inStream)); StringBuilder output = new StringBuilder(); int cp; while ((cp = br.read()) != -1) { output.append((char) cp); } br.close(); inStream.close(); return output.toString(); }