List of usage examples for java.io DataInputStream read
public final int read(byte b[], int off, int len) throws IOException
len
bytes of data from the contained input stream into an array of bytes. From source file:com.lenovo.h2000.services.LicenseServiceImpl.java
@Override public String upload(String filePath, Map<String, String> headers) throws Exception { _logger.info("calling LicenseServiceImpl.upload function"); Map<String, String> params = new HashMap<String, String>(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost( HttpConfig.parseBaseUrl(headers) + "license/import" + "?" + TypeUtil.mapToString(params));// new HttpPost("http://localhost:3002/license/import"); String responseBody = ""; DataInputStream in = null; try {//from www . j av a 2s .co m _logger.info("filePath" + filePath); File file = new File(filePath); in = new DataInputStream(new FileInputStream(filePath)); byte[] bufferOut = new byte[(int) file.length()]; int bytes = 0; int i = 0; int len = (int) (1024 > file.length() ? file.length() : 1024); while ((bytes = in.read(bufferOut, i, len)) > 0) { if (bytes < 1024) break; else { len = (int) (file.length() - bytes); i += bytes; } } ByteArrayEntity requestEntity = new ByteArrayEntity(bufferOut); requestEntity.setContentEncoding("UTF-8"); requestEntity.setContentType("application/octet-stream"); httpPost.setEntity(requestEntity); HttpResponse response = httpClient.execute(httpPost); response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8"); HttpEntity responseEntity = response.getEntity(); responseBody = EntityUtils.toString(responseEntity); if (file.isFile() && file.exists()) { file.delete(); } } catch (ClientProtocolException e) { e.printStackTrace(); _logger.error("throwing HttpClientUtil.doPost ClientProtocolException with " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); _logger.error("throwing HttpClientUtil.doPost IOException with " + e.getMessage()); } finally { httpClient.close(); if (in != null) { in.close(); } } return responseBody; }
From source file:org.wso2.carbon.attachment.mgt.ui.fileupload.AttachmentUploadServlet.java
/** * Get the inputstream from the request and generate a file from t at the tmp directory. *///from w w w.j ava2 s . c om private File generateTemporaryFile(HttpServletRequest request) throws ServletException, IOException { log.warn( "This code can be improved if reviewed thoroughly. Here we get the file from input stream and create" + " a temp file at \"tmp\" directory. May be we can avoid this file creation."); String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { DataInputStream inputStream = new DataInputStream(request.getInputStream()); //we are taking the length of Content type data int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; //this loop converting the uploaded file into byte code while (totalBytesRead < formDataLength) { byteRead = inputStream.read(dataBytes, totalBytesRead, formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); //for saving the file name String saveFile = file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0, saveFile.indexOf("\n")); saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1, contentType.length()); int pos; //extracting the index of file pos = file.indexOf("filename=\""); pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length; int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; //TODO log.warn("Hard-coded directory path:" + "\"tmp/\""); File tmpFile = new File("tmp" + File.separator + saveFile); FileOutputStream fileOut = new FileOutputStream(tmpFile); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); IOUtils.closeQuietly(fileOut); IOUtils.closeQuietly(inputStream); return tmpFile; } else { throw new ServletException("Content type of the request is not multipart/form-data"); } }
From source file:ru.ivanovpv.gorets.psm.mms.transaction.HttpUtils.java
/** * A helper method to send or retrieve data through HTTP protocol. * * @param token The token to identify the sending progress. * @param url The URL used in a GET request. Null when the method is * HTTP_POST_METHOD.// w w w . j a v a 2 s.c om * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD. * @param method HTTP_POST_METHOD or HTTP_GET_METHOD. * @return A byte array which contains the response data. * If an HTTP error code is returned, an IOException will be thrown. * @throws IOException if any error occurred on network interface or * an HTTP error code(>=400) returned from the server. */ public static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method, boolean isProxySet, String proxyHost, int proxyPort) throws IOException { if (url == null) { throw new IllegalArgumentException("URL must not be null."); } if (DEBUG) { Log.v(TAG, "httpConnection: params list"); Log.v(TAG, "\ttoken\t\t= " + token); Log.v(TAG, "\turl\t\t= " + url); Log.v(TAG, "\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN"))); Log.v(TAG, "\tisProxySet\t= " + isProxySet); Log.v(TAG, "\tproxyHost\t= " + proxyHost); Log.v(TAG, "\tproxyPort\t= " + proxyPort); // TODO Print out binary data more readable. //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu)); } AndroidHttpClient client = null; try { // Make sure to use a proxy which supports CONNECT. URI hostUrl = new URI(url); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); client = createHttpClient(context); HttpRequest req = null; switch (method) { case HTTP_POST_METHOD: ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu); // Set request content type. entity.setContentType("application/vnd.wap.mms-message"); HttpPost post = new HttpPost(url); post.setEntity(entity); req = post; break; case HTTP_GET_METHOD: req = new HttpGet(url); break; default: Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD + "] or GET[" + HTTP_GET_METHOD + "]."); return null; } // Set route parameters for the request. HttpParams params = client.getParams(); if (isProxySet) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort)); } req.setParams(params); // Set necessary HTTP headers for MMS transmission. req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT); { String xWapProfileTagName = MmsConfig.getUaProfTagName(); String xWapProfileUrl = MmsConfig.getUaProfUrl(); if (xWapProfileUrl != null) { if (DEBUG) { Log.d(TAG, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl); } req.addHeader(xWapProfileTagName, xWapProfileUrl); } } // Extra http parameters. Split by '|' to get a list of value pairs. // Separate each pair by the first occurrence of ':' to obtain a name and // value. Replace the occurrence of the string returned by // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside // the value. String extraHttpParams = MmsConfig.getHttpParams(); if (extraHttpParams != null) { String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)) .getLine1Number(); String line1Key = MmsConfig.getHttpParamsLine1Key(); String paramList[] = extraHttpParams.split("\\|"); for (String paramPair : paramList) { String splitPair[] = paramPair.split(":", 2); if (splitPair.length == 2) { String name = splitPair[0].trim(); String value = splitPair[1].trim(); if (line1Key != null) { value = value.replace(line1Key, line1Number); } if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) { req.addHeader(name, value); } } } } req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE); HttpResponse response = client.execute(target, req); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { // HTTP 200 is success. throw new IOException("HTTP error: " + status.getReasonPhrase()); } HttpEntity entity = response.getEntity(); byte[] body = null; if (entity != null) { try { if (entity.getContentLength() > 0) { body = new byte[(int) entity.getContentLength()]; DataInputStream dis = new DataInputStream(entity.getContent()); try { dis.readFully(body); } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } if (entity.isChunked()) { Log.v(TAG, "httpConnection: transfer encoding is chunked"); int bytesTobeRead = MmsConfig.getMaxMessageSize(); byte[] tempBody = new byte[bytesTobeRead]; DataInputStream dis = new DataInputStream(entity.getContent()); try { int bytesRead = 0; int offset = 0; boolean readError = false; do { try { bytesRead = dis.read(tempBody, offset, bytesTobeRead); } catch (IOException e) { readError = true; Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage()); break; } if (bytesRead > 0) { bytesTobeRead -= bytesRead; offset += bytesRead; } } while (bytesRead >= 0 && bytesTobeRead > 0); if (bytesRead == -1 && offset > 0 && !readError) { // offset is same as total number of bytes read // bytesRead will be -1 if the data was read till the eof body = new byte[offset]; System.arraycopy(tempBody, 0, body, 0, offset); Log.v(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset) + "]"); } else { Log.e(TAG, "httpConnection: Response entity too large or empty"); } } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } } finally { if (entity != null) { entity.consumeContent(); } } } return body; } catch (URISyntaxException e) { handleHttpConnectionException(e, url); } catch (IllegalStateException e) { handleHttpConnectionException(e, url); } catch (IllegalArgumentException e) { handleHttpConnectionException(e, url); } catch (SocketException e) { handleHttpConnectionException(e, url); } catch (Exception e) { handleHttpConnectionException(e, url); } finally { if (client != null) { client.close(); } } return null; }
From source file:com.geocine.mms.com.android.mms.transaction.HttpUtils.java
/** * A helper method to send or retrieve data through HTTP protocol. * * @param token The token to identify the sending progress. * @param url The URL used in a GET request. Null when the method is * HTTP_POST_METHOD.//from w w w . j a v a 2 s. c om * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD. * @param method HTTP_POST_METHOD or HTTP_GET_METHOD. * @return A byte array which contains the response data. * If an HTTP error code is returned, an IOException will be thrown. * @throws IOException if any error occurred on network interface or * an HTTP error code(>=400) returned from the server. */ protected static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method, boolean isProxySet, String proxyHost, int proxyPort) throws IOException { if (url == null) { throw new IllegalArgumentException("URL must not be null."); } if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "httpConnection: params list"); Log.v(TAG, "\ttoken\t\t= " + token); Log.v(TAG, "\turl\t\t= " + url); Log.v(TAG, "\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN"))); Log.v(TAG, "\tisProxySet\t= " + isProxySet); Log.v(TAG, "\tproxyHost\t= " + proxyHost); Log.v(TAG, "\tproxyPort\t= " + proxyPort); // TODO Print out binary data more readable. //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu)); } AndroidHttpClient client = null; try { // Make sure to use a proxy which supports CONNECT. URI hostUrl = new URI(url); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); client = createHttpClient(context); HttpRequest req = null; switch (method) { case HTTP_POST_METHOD: ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu); // Set request content type. entity.setContentType("application/vnd.wap.mms-message"); HttpPost post = new HttpPost(url); post.setEntity(entity); req = post; break; case HTTP_GET_METHOD: req = new HttpGet(url); break; default: Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD + "] or GET[" + HTTP_GET_METHOD + "]."); return null; } // Set route parameters for the request. HttpParams params = client.getParams(); if (isProxySet) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort)); } req.setParams(params); // Set necessary HTTP headers for MMS transmission. req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT); { String xWapProfileTagName = MmsConfig.getUaProfTagName(); String xWapProfileUrl = MmsConfig.getUaProfUrl(); if (xWapProfileUrl != null) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.d(LogTag.TRANSACTION, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl); } req.addHeader(xWapProfileTagName, xWapProfileUrl); } } // Extra http parameters. Split by '|' to get a list of value pairs. // Separate each pair by the first occurrence of ':' to obtain a name and // value. Replace the occurrence of the string returned by // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside // the value. String extraHttpParams = MmsConfig.getHttpParams(); if (extraHttpParams != null) { String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)) .getLine1Number(); String line1Key = MmsConfig.getHttpParamsLine1Key(); String paramList[] = extraHttpParams.split("\\|"); for (String paramPair : paramList) { String splitPair[] = paramPair.split(":", 2); if (splitPair.length == 2) { String name = splitPair[0].trim(); String value = splitPair[1].trim(); if (line1Key != null) { value = value.replace(line1Key, line1Number); } if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) { req.addHeader(name, value); } } } } req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE); HttpResponse response = client.execute(target, req); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { // HTTP 200 is success. throw new IOException("HTTP error: " + status.getReasonPhrase()); } HttpEntity entity = response.getEntity(); byte[] body = null; if (entity != null) { try { if (entity.getContentLength() > 0) { body = new byte[(int) entity.getContentLength()]; DataInputStream dis = new DataInputStream(entity.getContent()); try { dis.readFully(body); } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } if (entity.isChunked()) { Log.v(TAG, "httpConnection: transfer encoding is chunked"); int bytesTobeRead = MmsConfig.getMaxMessageSize(); byte[] tempBody = new byte[bytesTobeRead]; DataInputStream dis = new DataInputStream(entity.getContent()); try { int bytesRead = 0; int offset = 0; boolean readError = false; do { try { bytesRead = dis.read(tempBody, offset, bytesTobeRead); } catch (IOException e) { readError = true; Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage()); break; } if (bytesRead > 0) { bytesTobeRead -= bytesRead; offset += bytesRead; } } while (bytesRead >= 0 && bytesTobeRead > 0); if (bytesRead == -1 && offset > 0 && !readError) { // offset is same as total number of bytes read // bytesRead will be -1 if the data was read till the eof body = new byte[offset]; System.arraycopy(tempBody, 0, body, 0, offset); Log.v(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset) + "]"); } else { Log.e(TAG, "httpConnection: Response entity too large or empty"); } } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } } finally { if (entity != null) { entity.consumeContent(); } } } return body; } catch (URISyntaxException e) { handleHttpConnectionException(e, url); } catch (IllegalStateException e) { handleHttpConnectionException(e, url); } catch (IllegalArgumentException e) { handleHttpConnectionException(e, url); } catch (SocketException e) { handleHttpConnectionException(e, url); } catch (Exception e) { handleHttpConnectionException(e, url); } finally { if (client != null) { client.close(); } } return null; }
From source file:com.android.mms.service.HttpUtils.java
/** * A helper method to send or retrieve data through HTTP protocol. * * @param url The URL used in a GET request. Null when the method is * HTTP_POST_METHOD./*from w w w.j av a 2 s . c om*/ * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD. * @param method HTTP_POST_METHOD or HTTP_GET_METHOD. * @param isProxySet If proxy is set * @param proxyHost The host of the proxy * @param proxyPort The port of the proxy * @param resolver The custom name resolver to use * @param useIpv6 If we should use IPv6 address when the HTTP client resolves the host name * @param mmsConfig The MmsConfig to use * @return A byte array which contains the response data. * If an HTTP error code is returned, an IOException will be thrown. * @throws com.android.mms.service.exception.MmsHttpException if HTTP request gets error response (>=400) */ public static byte[] httpConnection(Context context, String url, byte[] pdu, int method, boolean isProxySet, String proxyHost, int proxyPort, NameResolver resolver, boolean useIpv6, MmsConfig.Overridden mmsConfig) throws MmsHttpException { final String methodString = getMethodString(method); Log.v(TAG, "HttpUtils: request param list\n" + "url=" + url + "\n" + "method=" + methodString + "\n" + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost + "\n" + "proxyPort=" + proxyPort + "\n" + "size=" + (pdu != null ? pdu.length : 0)); NetworkAwareHttpClient client = null; try { // Make sure to use a proxy which supports CONNECT. URI hostUrl = new URI(url); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); client = createHttpClient(context, resolver, useIpv6, mmsConfig); HttpRequest req = null; switch (method) { case HTTP_POST_METHOD: ByteArrayEntity entity = new ByteArrayEntity(pdu); // Set request content type. entity.setContentType("application/vnd.wap.mms-message"); HttpPost post = new HttpPost(url); post.setEntity(entity); req = post; break; case HTTP_GET_METHOD: req = new HttpGet(url); break; } // Set route parameters for the request. HttpParams params = client.getParams(); if (isProxySet) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort)); } req.setParams(params); // Set necessary HTTP headers for MMS transmission. req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT); // UA Profile URL header String xWapProfileTagName = mmsConfig.getUaProfTagName(); String xWapProfileUrl = mmsConfig.getUaProfUrl(); if (xWapProfileUrl != null) { Log.v(TAG, "HttpUtils: xWapProfUrl=" + xWapProfileUrl); req.addHeader(xWapProfileTagName, xWapProfileUrl); } // Extra http parameters. Split by '|' to get a list of value pairs. // Separate each pair by the first occurrence of ':' to obtain a name and // value. Replace the occurrence of the string returned by // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside // the value. And replace the occurrence of the string returned by // MmsConfig.getHttpParamsNaiKey() with the users NAI(Network Access Identifier) // inside the value. String extraHttpParams = mmsConfig.getHttpParams(); if (!TextUtils.isEmpty(extraHttpParams)) { // Parse the parameter list String paramList[] = extraHttpParams.split("\\|"); for (String paramPair : paramList) { String splitPair[] = paramPair.split(":", 2); if (splitPair.length == 2) { final String name = splitPair[0].trim(); final String value = resolveMacro(context, splitPair[1].trim(), mmsConfig); if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) { req.addHeader(name, value); } } } } req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, getCurrentAcceptLanguage(Locale.getDefault())); final HttpResponse response = client.execute(target, req); final StatusLine status = response.getStatusLine(); final HttpEntity entity = response.getEntity(); Log.d(TAG, "HttpUtils: status=" + status + " size=" + (entity != null ? entity.getContentLength() : -1)); for (Header header : req.getAllHeaders()) { if (header != null) { Log.v(TAG, "HttpUtils: header " + header.getName() + "=" + header.getValue()); } } byte[] body = null; if (entity != null) { try { if (entity.getContentLength() > 0) { body = new byte[(int) entity.getContentLength()]; DataInputStream dis = new DataInputStream(entity.getContent()); try { dis.readFully(body); } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "HttpUtils: Error closing input stream: " + e.getMessage()); } } } if (entity.isChunked()) { Log.d(TAG, "HttpUtils: transfer encoding is chunked"); int bytesTobeRead = mmsConfig.getMaxMessageSize(); byte[] tempBody = new byte[bytesTobeRead]; DataInputStream dis = new DataInputStream(entity.getContent()); try { int bytesRead = 0; int offset = 0; boolean readError = false; do { try { bytesRead = dis.read(tempBody, offset, bytesTobeRead); } catch (IOException e) { readError = true; Log.e(TAG, "HttpUtils: error reading input stream", e); break; } if (bytesRead > 0) { bytesTobeRead -= bytesRead; offset += bytesRead; } } while (bytesRead >= 0 && bytesTobeRead > 0); if (bytesRead == -1 && offset > 0 && !readError) { // offset is same as total number of bytes read // bytesRead will be -1 if the data was read till the eof body = new byte[offset]; System.arraycopy(tempBody, 0, body, 0, offset); Log.d(TAG, "HttpUtils: Chunked response length " + offset); } else { Log.e(TAG, "HttpUtils: Response entity too large or empty"); } } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "HttpUtils: Error closing input stream", e); } } } } finally { if (entity != null) { entity.consumeContent(); } } } if (status.getStatusCode() != 200) { // HTTP 200 is success. StringBuilder sb = new StringBuilder(); if (body != null) { sb.append("response: text=").append(new String(body)).append('\n'); } for (Header header : req.getAllHeaders()) { if (header != null) { sb.append("req header: ").append(header.getName()).append('=').append(header.getValue()) .append('\n'); } } for (Header header : response.getAllHeaders()) { if (header != null) { sb.append("resp header: ").append(header.getName()).append('=').append(header.getValue()) .append('\n'); } } Log.e(TAG, "HttpUtils: error response -- \n" + "mStatusCode=" + status.getStatusCode() + "\n" + "reason=" + status.getReasonPhrase() + "\n" + "url=" + url + "\n" + "method=" + methodString + "\n" + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost + "\n" + "proxyPort=" + proxyPort + (sb != null ? "\n" + sb.toString() : "")); throw new MmsHttpException(status.getReasonPhrase()); } return body; } catch (IOException e) { Log.e(TAG, "HttpUtils: IO failure", e); throw new MmsHttpException(e); } catch (URISyntaxException e) { Log.e(TAG, "HttpUtils: invalid url " + url); throw new MmsHttpException("Invalid url " + url); } finally { if (client != null) { client.close(); } } }
From source file:com.resenworkspace.data.Download.HttpUtils.java
/** * A helper method to send or retrieve data through HTTP protocol. * * @param token The token to identify the sending progress. * @param url The URL used in a GET request. Null when the method is * HTTP_POST_METHOD.//from w w w. jav a2 s . co m * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD. * @param method HTTP_POST_METHOD or HTTP_GET_METHOD. * @return A byte array which contains the response data. * If an HTTP error code is returned, an IOException will be thrown. * @throws IOException if any error occurred on network interface or * an HTTP error code(>=400) returned from the server. */ protected static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method, boolean isProxySet, String proxyHost, int proxyPort) throws IOException { if (url == null) { throw new IllegalArgumentException("URL must not be null."); } { Log.i(TAG, "httpConnection: params list"); Log.i(TAG, "\ttoken\t\t= " + token); Log.i(TAG, "\turl\t\t= " + url); Log.i(TAG, "\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN"))); Log.i(TAG, "\tisProxySet\t= " + isProxySet); Log.i(TAG, "\tproxyHost\t= " + proxyHost); Log.i(TAG, "\tproxyPort\t= " + proxyPort); // TODO Print out binary data more readable. //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu)); } AndroidHttpClient client = null; try { // Make sure to use a proxy which supports CONNECT. URI hostUrl = new URI(url); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); client = createHttpClient(context); HttpRequest req = null; switch (method) { case HTTP_POST_METHOD: ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu); // Set request content type. entity.setContentType("application/vnd.wap.mms-message"); HttpPost post = new HttpPost(url); post.setEntity(entity); req = post; break; case HTTP_GET_METHOD: req = new HttpGet(url); break; default: Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD + "] or GET[" + HTTP_GET_METHOD + "]."); return null; } // Set route parameters for the request. HttpParams params = client.getParams(); if (isProxySet) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort)); } req.setParams(params); // Set necessary HTTP headers for transmission. // req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT); // { // String xWapProfileTagName = MmsConfig.getUaProfTagName(); // String xWapProfileUrl = MmsConfig.getUaProfUrl(); // // if (xWapProfileUrl != null) { // if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { // Log.d(LogTag.TRANSACTION, // "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl); // } // req.addHeader(xWapProfileTagName, xWapProfileUrl); // } // } // Extra http parameters. Split by '|' to get a list of value pairs. // Separate each pair by the first occurrence of ':' to obtain a name and // value. Replace the occurrence of the string returned by // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside // the value. // String extraHttpParams = MmsConfig.getHttpParams(); // if (extraHttpParams != null) { // String line1Number = ((TelephonyManager)context // .getSystemService(Context.TELEPHONY_SERVICE)) // .getLine1Number(); // String line1Key = MmsConfig.getHttpParamsLine1Key(); // String paramList[] = extraHttpParams.split("\\|"); // // for (String paramPair : paramList) { // String splitPair[] = paramPair.split(":", 2); // // if (splitPair.length == 2) { // String name = splitPair[0].trim(); // String value = splitPair[1].trim(); // // if (line1Key != null) { // value = value.replace(line1Key, line1Number); // } // if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) { // req.addHeader(name, value); // } // } // } // } req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE); HttpResponse response = client.execute(target, req); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { // HTTP 200 is success. throw new IOException("HTTP error: " + status.getReasonPhrase()); } HttpEntity entity = response.getEntity(); byte[] body = null; if (entity != null) { try { if (entity.getContentLength() > 0) { body = new byte[(int) entity.getContentLength()]; DataInputStream dis = new DataInputStream(entity.getContent()); try { dis.readFully(body); } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } if (entity.isChunked()) { Log.i(TAG, "httpConnection: transfer encoding is chunked"); //int bytesTobeRead = MmsConfig.getMaxMessageSize(); int bytesTobeRead = 500 * 1024; byte[] tempBody = new byte[bytesTobeRead]; DataInputStream dis = new DataInputStream(entity.getContent()); try { int bytesRead = 0; int offset = 0; boolean readError = false; do { try { bytesRead = dis.read(tempBody, offset, bytesTobeRead); } catch (IOException e) { readError = true; Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage()); break; } if (bytesRead > 0) { bytesTobeRead -= bytesRead; offset += bytesRead; } } while (bytesRead >= 0 && bytesTobeRead > 0); if (bytesRead == -1 && offset > 0 && !readError) { // offset is same as total number of bytes read // bytesRead will be -1 if the data was read till the eof body = new byte[offset]; System.arraycopy(tempBody, 0, body, 0, offset); Log.i(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset) + "]"); } else { Log.e(TAG, "httpConnection: Response entity too large or empty"); } } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } } finally { if (entity != null) { entity.consumeContent(); } } } return body; } catch (URISyntaxException e) { handleHttpConnectionException(e, url); } catch (IllegalStateException e) { handleHttpConnectionException(e, url); } catch (IllegalArgumentException e) { handleHttpConnectionException(e, url); } catch (SocketException e) { handleHttpConnectionException(e, url); } catch (Exception e) { handleHttpConnectionException(e, url); } finally { if (client != null) { client.close(); } } return null; }
From source file:ffx.xray.CCP4MapFilter.java
/** * {@inheritDoc}//from w ww .java2 s . co m */ @Override public Crystal getCrystal(String filename, CompositeConfiguration properties) { int imapdata; int sg = -1; double cella = -1.0; double cellb = -1.0; double cellc = -1.0; double cellalpha = -1.0; double cellbeta = -1.0; double cellgamma = -1.0; ByteOrder b = ByteOrder.nativeOrder(); FileInputStream fis; DataInputStream dis; // first determine byte order of file versus system try { fis = new FileInputStream(filename); dis = new DataInputStream(fis); dis.skipBytes(212); byte bytes[] = new byte[4]; dis.read(bytes, 0, 4); ByteBuffer bb = ByteBuffer.wrap(bytes); imapdata = bb.order(ByteOrder.BIG_ENDIAN).getInt(); String stampstr = Integer.toHexString(imapdata); // System.out.println("stamp: " + stampstr); switch (stampstr.charAt(0)) { case '1': case '3': if (b.equals(ByteOrder.LITTLE_ENDIAN)) { b = ByteOrder.BIG_ENDIAN; } break; case '4': if (b.equals(ByteOrder.BIG_ENDIAN)) { b = ByteOrder.LITTLE_ENDIAN; } break; } fis.close(); } catch (Exception e) { String message = "Fatal exception reading CCP4 map.\n"; logger.log(Level.SEVERE, message, e); System.exit(-1); } try { fis = new FileInputStream(filename); dis = new DataInputStream(fis); dis.skipBytes(40); byte bytes[] = new byte[80]; dis.read(bytes, 0, 80); ByteBuffer bb = ByteBuffer.wrap(bytes); cella = bb.order(b).getFloat(); cellb = bb.order(b).getFloat(); cellc = bb.order(b).getFloat(); cellalpha = bb.order(b).getFloat(); cellbeta = bb.order(b).getFloat(); cellgamma = bb.order(b).getFloat(); for (int i = 0; i < 3; i++) { bb.order(b).getInt(); } for (int i = 0; i < 3; i++) { bb.order(b).getFloat(); } sg = bb.order(b).getInt(); fis.close(); } catch (Exception e) { String message = "Fatal exception reading CCP4 map.\n"; logger.log(Level.SEVERE, message, e); System.exit(-1); } return new Crystal(cella, cellb, cellc, cellalpha, cellbeta, cellgamma, SpaceGroup.spaceGroupNames[sg - 1]); }
From source file:com.serenegiant.media.TLMediaEncoder.java
/** * read raw bit stream from specific intermediate file * @param in//from w ww . j a v a 2 s. c om * @param header * @param buffer * @param readBuffer * @throws IOException * @throws BufferOverflowException */ /*package*/static ByteBuffer readStream(final DataInputStream in, final TLMediaFrameHeader header, ByteBuffer buffer, final byte[] readBuffer) throws IOException { readHeader(in, header); if ((buffer == null) || header.size > buffer.capacity()) { buffer = ByteBuffer.allocateDirect(header.size); } buffer.clear(); final int max_bytes = Math.min(readBuffer.length, header.size); int read_bytes; for (int i = header.size; i > 0; i -= read_bytes) { read_bytes = in.read(readBuffer, 0, Math.min(i, max_bytes)); if (read_bytes <= 0) break; buffer.put(readBuffer, 0, read_bytes); } buffer.flip(); return buffer; }
From source file:com.code4bones.utils.HttpUtils.java
/** * A helper method to send or retrieve data through HTTP protocol. * * @param token The token to identify the sending progress. * @param url The URL used in a GET request. Null when the method is * HTTP_POST_METHOD./*from w w w . j a v a 2 s.com*/ * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD. * @param method HTTP_POST_METHOD or HTTP_GET_METHOD. * @return A byte array which contains the response data. * If an HTTP error code is returned, an IOException will be thrown. * @throws IOException if any error occurred on network interface or * an HTTP error code(>=400) returned from the server. */ public static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method, boolean isProxySet, String proxyHost, int proxyPort) throws IOException { if (url == null) { throw new IllegalArgumentException("URL must not be null."); } NetLog.v("httpConnection: params list"); NetLog.v("\ttoken\t\t= " + token); NetLog.v("\turl\t\t= " + url); NetLog.v("\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN"))); NetLog.v("\tisProxySet\t= " + isProxySet); NetLog.v("\tproxyHost\t= " + proxyHost); NetLog.v("\tproxyPort\t= " + proxyPort); //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu)); AndroidHttpClient client = null; try { // Make sure to use a proxy which supports CONNECT. URI hostUrl = new URI(url); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); client = createHttpClient(context); HttpRequest req = null; switch (method) { case HTTP_POST_METHOD: ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu); // Set request content type. entity.setContentType("application/vnd.wap.mms-message"); HttpPost post = new HttpPost(url); post.setEntity(entity); req = post; break; case HTTP_GET_METHOD: req = new HttpGet(url); break; default: Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD + "] or GET[" + HTTP_GET_METHOD + "]."); return null; } // Set route parameters for the request. HttpParams params = client.getParams(); if (isProxySet) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort)); } req.setParams(params); // Set necessary HTTP headers for MMS transmission. req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT); { //TODO: MmsConfig.getUaProfTagName(); String xWapProfileTagName = "x-wap-profile";//MmsConfig.getUaProfTagName(); String xWapProfileUrl = "mms.beeline.ru"; //MmsConfig.getUaProfUrl(); if (xWapProfileUrl != null) { NetLog.v("[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl); } req.addHeader(xWapProfileTagName, xWapProfileUrl); } // Extra http parameters. Split by '|' to get a list of value pairs. // Separate each pair by the first occurrence of ':' to obtain a name and // value. Replace the occurrence of the string returned by // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside // the value. //TODO: MmsConfig.getHttpParams(); String extraHttpParams = null; //MmsConfig.getHttpParams(); if (extraHttpParams != null) { String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)) .getLine1Number(); String line1Key = "key"; //MmsConfig.getHttpParamsLine1Key(); String paramList[] = extraHttpParams.split("\\|"); for (String paramPair : paramList) { String splitPair[] = paramPair.split(":", 2); if (splitPair.length == 2) { String name = splitPair[0].trim(); String value = splitPair[1].trim(); if (line1Key != null) { value = value.replace(line1Key, line1Number); } if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) { req.addHeader(name, value); } } } } req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE); HttpResponse response = client.execute(target, req); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { // HTTP 200 is success. throw new IOException("HTTP error: " + status.getReasonPhrase()); } HttpEntity entity = response.getEntity(); byte[] body = null; if (entity != null) { try { if (entity.getContentLength() > 0) { body = new byte[(int) entity.getContentLength()]; DataInputStream dis = new DataInputStream(entity.getContent()); try { dis.readFully(body); } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } if (entity.isChunked()) { Log.v(TAG, "httpConnection: transfer encoding is chunked"); //TODO: MmsConfig.getMaxMessageSize(); int bytesTobeRead = 4096; //MmsConfig.getMaxMessageSize(); byte[] tempBody = new byte[bytesTobeRead]; DataInputStream dis = new DataInputStream(entity.getContent()); try { int bytesRead = 0; int offset = 0; boolean readError = false; do { try { bytesRead = dis.read(tempBody, offset, bytesTobeRead); } catch (IOException e) { readError = true; Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage()); break; } if (bytesRead > 0) { bytesTobeRead -= bytesRead; offset += bytesRead; } } while (bytesRead >= 0 && bytesTobeRead > 0); if (bytesRead == -1 && offset > 0 && !readError) { // offset is same as total number of bytes read // bytesRead will be -1 if the data was read till the eof body = new byte[offset]; System.arraycopy(tempBody, 0, body, 0, offset); Log.v(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset) + "]"); } else { Log.e(TAG, "httpConnection: Response entity too large or empty"); } } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } } finally { if (entity != null) { entity.consumeContent(); } } } return body; } catch (URISyntaxException e) { handleHttpConnectionException(e, url); } catch (IllegalStateException e) { handleHttpConnectionException(e, url); } catch (IllegalArgumentException e) { handleHttpConnectionException(e, url); } catch (SocketException e) { handleHttpConnectionException(e, url); } catch (Exception e) { handleHttpConnectionException(e, url); } finally { if (client != null) { client.close(); } } return null; }
From source file:ffx.realspace.CCP4MapFilter.java
/** * {@inheritDoc}/*www. j a va2 s. co m*/ */ @Override public Crystal getCrystal(String fileName, CompositeConfiguration properties) { int imapData; int spaceGroup = -1; double cellA = -1.0; double cellB = -1.0; double cellC = -1.0; double cellAlpha = -1.0; double cellBeta = -1.0; double cellGamma = -1.0; ByteOrder byteOrder = ByteOrder.nativeOrder(); FileInputStream fileInputStream; DataInputStream dataInputStream; // first determine byte order of file versus system try { fileInputStream = new FileInputStream(fileName); dataInputStream = new DataInputStream(fileInputStream); dataInputStream.skipBytes(212); byte bytes[] = new byte[4]; dataInputStream.read(bytes, 0, 4); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); imapData = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt(); String stampString = Integer.toHexString(imapData); switch (stampString.charAt(0)) { case '1': case '3': if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) { byteOrder = ByteOrder.BIG_ENDIAN; } break; case '4': if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) { byteOrder = ByteOrder.LITTLE_ENDIAN; } break; } fileInputStream.close(); } catch (Exception e) { String message = " Fatal exception reading CCP4 map.\n"; logger.log(Level.SEVERE, message, e); } try { fileInputStream = new FileInputStream(fileName); dataInputStream = new DataInputStream(fileInputStream); dataInputStream.skipBytes(40); byte bytes[] = new byte[80]; dataInputStream.read(bytes, 0, 80); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); cellA = byteBuffer.order(byteOrder).getFloat(); cellB = byteBuffer.order(byteOrder).getFloat(); cellC = byteBuffer.order(byteOrder).getFloat(); cellAlpha = byteBuffer.order(byteOrder).getFloat(); cellBeta = byteBuffer.order(byteOrder).getFloat(); cellGamma = byteBuffer.order(byteOrder).getFloat(); for (int i = 0; i < 3; i++) { byteBuffer.order(byteOrder).getInt(); } for (int i = 0; i < 3; i++) { byteBuffer.order(byteOrder).getFloat(); } spaceGroup = byteBuffer.order(byteOrder).getInt(); fileInputStream.close(); } catch (Exception e) { String message = " Fatal exception reading CCP4 map.\n"; logger.log(Level.SEVERE, message, e); } return new Crystal(cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma, SpaceGroup.spaceGroupNames[spaceGroup - 1]); }