List of usage examples for java.io InputStreamReader read
public int read() throws IOException
From source file:com.rhfung.P2PDictionary.DataConnection.java
private String ReadLineFromBinary(InputStreamReader reader) throws IOException { StringBuilder builder = new StringBuilder(); int byte1 = reader.read(); int byte2 = reader.read(); while (byte1 != 13 && byte2 != 10) { builder.append((char) byte1); byte1 = byte2; byte2 = reader.read(); while (byte2 == -1) // EOS {/* w w w. jav a 2 s . c o m*/ try { Thread.sleep(P2PDictionary.SLEEP_IDLE_SLEEP); byte2 = reader.read(); } catch (InterruptedException ex) { return builder.toString(); } if (killBit) // truncate line reading return builder.toString(); } } return builder.toString(); }
From source file:org.eclipse.swt.examples.fileviewer.FileViewer.java
/** * Copies a file or entire directory structure. * //from www. j ava 2 s. c o m * @param oldFile * the location of the old file or directory * @param newFile * the location of the new file or directory * @return true iff the operation succeeds without errors */ boolean copyFileStructure(File oldFile, File newFile) { Log.i(""); if (oldFile == null || newFile == null) return false; // ensure that newFile is not a child of oldFile or a dupe File searchFile = newFile; do { if (oldFile.equals(searchFile)) return false; searchFile = searchFile.getParentFile(); } while (searchFile != null); if (oldFile.isDirectory()) { /* * Copy a directory */ if (progressDialog != null) { progressDialog.setDetailFile(oldFile, ProgressDialog.COPY); } if (simulateOnly) { // System.out.println(getResourceString("simulate.DirectoriesCreated.text", // new Object[] { newFile.getPath() })); } else { if (!newFile.mkdirs()) return false; } File[] subFiles = oldFile.listFiles(); if (subFiles != null) { if (progressDialog != null) { progressDialog.addWorkUnits(subFiles.length); } for (int i = 0; i < subFiles.length; i++) { File oldSubFile = subFiles[i]; File newSubFile = new File(newFile, oldSubFile.getName()); if (!copyFileStructure(oldSubFile, newSubFile)) return false; if (progressDialog != null) { progressDialog.addProgress(1); if (progressDialog.isCancelled()) return false; } } } } else { /* * Copy a file */ if (simulateOnly) { // System.out.println(getResourceString("simulate.CopyFromTo.text", // new Object[] { oldFile.getPath(), newFile.getPath() })); } else { InputStreamReader in = null; OutputStreamWriter out = null; try { in = new InputStreamReader(oldFile.getInputStream()); out = new OutputStreamWriter(newFile.getOutputStream()); int count; while ((count = in.read()) != -1) out.write(count); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { return false; } } } } return true; }
From source file:org.pentaho.di.trans.steps.http.HTTP.java
private Object[] callHttpService(RowMetaInterface rowMeta, Object[] rowData) throws KettleException { String url = determineUrl(rowMeta, rowData); try {//from w w w . ja v a 2s. c o m if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "HTTP.Log.Connecting", url)); } // Prepare HTTP get // HttpClient httpclient = SlaveConnectionManager.getInstance().createHttpClient(); HttpMethod method = new GetMethod(url); // Set timeout if (data.realConnectionTimeout > -1) { httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(data.realConnectionTimeout); } if (data.realSocketTimeout > -1) { httpclient.getHttpConnectionManager().getParams().setSoTimeout(data.realSocketTimeout); } if (!Const.isEmpty(data.realHttpLogin)) { httpclient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(data.realHttpLogin, data.realHttpPassword); httpclient.getState().setCredentials(AuthScope.ANY, defaultcreds); } HostConfiguration hostConfiguration = new HostConfiguration(); if (!Const.isEmpty(data.realProxyHost)) { hostConfiguration.setProxy(data.realProxyHost, data.realProxyPort); } // Add Custom HTTP headers if (data.useHeaderParameters) { for (int i = 0; i < data.header_parameters_nrs.length; i++) { method.addRequestHeader(data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])); if (isDebug()) { log.logDebug(BaseMessages.getString(PKG, "HTTPDialog.Log.HeaderValue", data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]))); } } } InputStreamReader inputStreamReader = null; Object[] newRow = null; if (rowData != null) { newRow = rowData.clone(); } // Execute request // try { // used for calculating the responseTime long startTime = System.currentTimeMillis(); int statusCode = httpclient.executeMethod(hostConfiguration, method); // calculate the responseTime long responseTime = System.currentTimeMillis() - startTime; if (log.isDetailed()) { log.logDetailed(BaseMessages.getString(PKG, "HTTP.Log.ResponseTime", responseTime, url)); } String body = null; // The status code if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTP.Log.ResponseStatusCode", "" + statusCode)); } if (statusCode != -1) { if (statusCode == 204) { body = ""; } else { // if the response is not 401: HTTP Authentication required if (statusCode != 401) { // guess encoding // String encoding = meta.getEncoding(); // Try to determine the encoding from the Content-Type value // if (Const.isEmpty(encoding)) { String contentType = method.getResponseHeader("Content-Type").getValue(); if (contentType != null && contentType.contains("charset")) { encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "") .replace("\"", "").trim(); } } if (isDebug()) { log.logDebug(toString(), BaseMessages.getString(PKG, "HTTP.Log.ResponseHeaderEncoding", encoding)); } // the response if (!Const.isEmpty(encoding)) { inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream(), encoding); } else { inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream()); } StringBuffer bodyBuffer = new StringBuffer(); int c; while ((c = inputStreamReader.read()) != -1) { bodyBuffer.append((char) c); } inputStreamReader.close(); body = bodyBuffer.toString(); if (isDebug()) { logDebug("Response body: " + body); } } else { // the status is a 401 throw new KettleStepException( BaseMessages.getString(PKG, "HTTP.Exception.Authentication", data.realUrl)); } } } int returnFieldsOffset = rowMeta.size(); if (!Const.isEmpty(meta.getFieldName())) { newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body); returnFieldsOffset++; } if (!Const.isEmpty(meta.getResultCodeFieldName())) { newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode)); returnFieldsOffset++; } if (!Const.isEmpty(meta.getResponseTimeFieldName())) { newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime)); } } finally { if (inputStreamReader != null) { inputStreamReader.close(); } // Release current connection to the connection pool once you are done method.releaseConnection(); if (data.realcloseIdleConnectionsTime > -1) { httpclient.getHttpConnectionManager().closeIdleConnections(data.realcloseIdleConnectionsTime); } } return newRow; } catch (UnknownHostException uhe) { throw new KettleException( BaseMessages.getString(PKG, "HTTP.Error.UnknownHostException", uhe.getMessage())); } catch (Exception e) { throw new KettleException(BaseMessages.getString(PKG, "HTTP.Log.UnableGetResult", url), e); } }
From source file:ProcessRequest.java
public JSONObject getWeight(final String host, final int port, final int numChars, final int weightBeginPos, final int weightEndPos, final int termChar, final int statusBeginPos, final int statusEndPos, final int normalChar, final int motionChar, int timeout, final String overcapacity) { //Thread socketThread = new Thread() { // public void run() { //cannot run in thread Socket connection = null;/*www . j a v a2 s . com*/ JSONObject returnObject = new JSONObject(); try { System.out.println("opening socket"); connection = new Socket(host, port); System.out.println("getting stream"); InputStreamReader reader = new InputStreamReader(connection.getInputStream()); System.out.println("creating character buffer"); boolean success = false; java.util.Date beginDate = new java.util.Date(); java.util.Date endDate = (java.util.Date) beginDate.clone(); endDate.setSeconds(endDate.getSeconds() + timeout); while (!success) { beginDate = new java.util.Date(); if (beginDate.after(endDate)) { returnObject.put("error", "the operation timed out"); //out.println(returnObject.toString(5)); return returnObject; } String string = new String(); int count = 0; while (reader.read() != (char) (termChar)) { if (count > 5000) { break; } count++; } if (count > 5000) { returnObject.put("error", "termchar was not found in the stream. are you sure the scale is set up correctly?"); //out.println(returnObject.toString(5)); return returnObject; } for (int i = 0; i < numChars; i++) { string += (char) (reader.read()); } //get negative marker also String weight = string.substring(weightBeginPos - 1, weightEndPos); String status = string.substring(statusBeginPos - 1, statusEndPos); String uom = string.substring(9, 11); System.out.println("weight: '" + weight + "'"); System.out.println("status: '" + status + "'"); System.out.println("uom : '" + uom + "'"); if (string.contains(overcapacity)) { returnObject.put("error", "Over Capacity!"); return returnObject; } else { System.out.println("extracting weight value"); returnObject.put("weight", new Integer(weight).toString()); System.out.println("checking motion"); if (status.charAt(0) == ((char) (normalChar))) { returnObject.put("motion", false); } else if (status.charAt(0) == ((char) (motionChar))) { returnObject.put("motion", true); } else { returnObject.put("error", "Invalid Motion Char!\n(check web service settings)"); } System.out.println("checking uom"); if (uom.equals("LB")) { returnObject.put("uom", "lbs"); } else if (uom.equals("KG")) { returnObject.put("uom", "kg"); } else { //unknown weight type, no cause for error here. } } System.out.println("sending resultant json"); //out.println(returnObject.toString(5)); success = true; } } catch (Exception e) { System.out.println("ERROR"); System.out.println("ERROR: could not connect to scale: " + e.toString()); try { returnObject.put("error", "could not connect to scale: " + e.toString()); return returnObject; //out.println(returnObject.toString(5)); } catch (Exception je) { //out.println("parser error?"); returnObject.put("error", je.toString()); return returnObject; } } finally { try { connection.close(); } catch (Exception e) { //don't care at this point. } return returnObject; } // } //}; //socketThread.start(); }
From source file:org.pentaho.di.trans.steps.httppost.HTTPPOST.java
private Object[] callHTTPPOST(Object[] rowData) throws KettleException { // get dynamic url ? if (meta.isUrlInField()) { data.realUrl = data.inputRowMeta.getString(rowData, data.indexOfUrlField); }/*from w w w. j a v a 2 s .c o m*/ FileInputStream fis = null; try { if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "HTTPPOST.Log.ConnectingToURL", data.realUrl)); } // Prepare HTTP POST // HttpClient HTTPPOSTclient = SlaveConnectionManager.getInstance().createHttpClient(); PostMethod post = new PostMethod(data.realUrl); // post.setFollowRedirects(false); // Set timeout if (data.realConnectionTimeout > -1) { HTTPPOSTclient.getHttpConnectionManager().getParams() .setConnectionTimeout(data.realConnectionTimeout); } if (data.realSocketTimeout > -1) { HTTPPOSTclient.getHttpConnectionManager().getParams().setSoTimeout(data.realSocketTimeout); } if (!Const.isEmpty(data.realHttpLogin)) { HTTPPOSTclient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(data.realHttpLogin, data.realHttpPassword); HTTPPOSTclient.getState().setCredentials(AuthScope.ANY, defaultcreds); } HostConfiguration hostConfiguration = new HostConfiguration(); if (!Const.isEmpty(data.realProxyHost)) { hostConfiguration.setProxy(data.realProxyHost, data.realProxyPort); } // Specify content type and encoding // If content encoding is not explicitly specified // ISO-8859-1 is assumed by the POSTMethod if (!data.contentTypeHeaderOverwrite) { // can be overwritten now if (Const.isEmpty(data.realEncoding)) { post.setRequestHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_XML); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE, CONTENT_TYPE_TEXT_XML)); } } else { post.setRequestHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE, CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding)); } } } // HEADER PARAMETERS if (data.useHeaderParameters) { // set header parameters that we want to send for (int i = 0; i < data.header_parameters_nrs.length; i++) { post.addRequestHeader(data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]))); } } } // BODY PARAMETERS if (data.useBodyParameters) { // set body parameters that we want to send for (int i = 0; i < data.body_parameters_nrs.length; i++) { data.bodyParameters[i] .setValue(data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i])); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.BodyValue", data.bodyParameters[i].getName(), data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i]))); } } post.setRequestBody(data.bodyParameters); } // QUERY PARAMETERS if (data.useQueryParameters) { for (int i = 0; i < data.query_parameters_nrs.length; i++) { data.queryParameters[i] .setValue(data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i])); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.QueryValue", data.queryParameters[i].getName(), data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i]))); } } post.setQueryString(data.queryParameters); } // Set request entity? if (data.indexOfRequestEntity >= 0) { String tmp = data.inputRowMeta.getString(rowData, data.indexOfRequestEntity); // Request content will be retrieved directly // from the input stream // Per default, the request content needs to be buffered // in order to determine its length. // Request body buffering can be avoided when // content length is explicitly specified if (meta.isPostAFile()) { File input = new File(tmp); fis = new FileInputStream(input); post.setRequestEntity(new InputStreamRequestEntity(fis, input.length())); } else { if ((data.realEncoding != null) && (data.realEncoding.length() > 0)) { post.setRequestEntity(new InputStreamRequestEntity( new ByteArrayInputStream(tmp.getBytes(data.realEncoding)), tmp.length())); } else { post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(tmp.getBytes()), tmp.length())); } } } // Execute request // InputStreamReader inputStreamReader = null; Object[] newRow = null; if (rowData != null) { newRow = rowData.clone(); } try { // used for calculating the responseTime long startTime = System.currentTimeMillis(); // Execute the POST method int statusCode = HTTPPOSTclient.executeMethod(hostConfiguration, post); // calculate the responseTime long responseTime = System.currentTimeMillis() - startTime; if (isDetailed()) { logDetailed( BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseTime", responseTime, data.realUrl)); } // Display status code if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseCode", String.valueOf(statusCode))); } String body = null; if (statusCode != -1) { if (statusCode == 204) { body = ""; } else { // if the response is not 401: HTTP Authentication required if (statusCode != 401) { // Use request encoding if specified in component to avoid strange response encodings // See PDI-3815 String encoding = data.realEncoding; // Try to determine the encoding from the Content-Type value // if (Const.isEmpty(encoding)) { String contentType = post.getResponseHeader("Content-Type").getValue(); if (contentType != null && contentType.contains("charset")) { encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "") .replace("\"", "").trim(); } } // Get the response, but only specify encoding if we've got one // otherwise the default charset ISO-8859-1 is used by HttpClient if (Const.isEmpty(encoding)) { if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.Encoding", "ISO-8859-1")); } inputStreamReader = new InputStreamReader(post.getResponseBodyAsStream()); } else { if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.Encoding", encoding)); } inputStreamReader = new InputStreamReader(post.getResponseBodyAsStream(), encoding); } StringBuffer bodyBuffer = new StringBuffer(); int c; while ((c = inputStreamReader.read()) != -1) { bodyBuffer.append((char) c); } inputStreamReader.close(); // Display response body = bodyBuffer.toString(); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseBody", body)); } } else { // the status is a 401 throw new KettleStepException( BaseMessages.getString(PKG, "HTTPPOST.Exception.Authentication", data.realUrl)); } } } int returnFieldsOffset = data.inputRowMeta.size(); if (!Const.isEmpty(meta.getFieldName())) { newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body); returnFieldsOffset++; } if (!Const.isEmpty(meta.getResultCodeFieldName())) { newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode)); returnFieldsOffset++; } if (!Const.isEmpty(meta.getResponseTimeFieldName())) { newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime)); } } finally { if (inputStreamReader != null) { inputStreamReader.close(); } // Release current connection to the connection pool once you are done post.releaseConnection(); if (data.realcloseIdleConnectionsTime > -1) { HTTPPOSTclient.getHttpConnectionManager() .closeIdleConnections(data.realcloseIdleConnectionsTime); } } return newRow; } catch (UnknownHostException uhe) { throw new KettleException( BaseMessages.getString(PKG, "HTTPPOST.Error.UnknownHostException", uhe.getMessage())); } catch (Exception e) { throw new KettleException(BaseMessages.getString(PKG, "HTTPPOST.Error.CanNotReadURL", data.realUrl), e); } finally { if (fis != null) { BaseStep.closeQuietly(fis); } } }