List of usage examples for java.io DataInputStream readFully
public final void readFully(byte b[]) throws IOException
From source file:JALPTest.java
/** * Creates a Producer using the given command line params. * * @param xml the ApplicationMetadataXML * @param socketPath a String which is the path to the socket * @param privateKeyPath a String which is the path to the private key in DER format * @param publicKeyPath a String which is the path to the public key in DER format * @param certPath a String which is the path to the certificate * @param hasDigest a Boolean, true to set a digest method in the producer * @return the created Producer/*from w w w. ja va 2 s.c o m*/ * @throws Exception */ private static Producer createProducer(ApplicationMetadataXML xml, String socketPath, String privateKeyPath, String publicKeyPath, String certPath, Boolean hasDigest) throws Exception { Producer producer = new Producer(xml); producer.setSocketFile(socketPath); if (privateKeyPath != null && !"".equals(privateKeyPath)) { File privateKeyFile = new File(privateKeyPath); DataInputStream privateDis = new DataInputStream(new FileInputStream(privateKeyFile)); byte[] privateKeyBytes = new byte[(int) privateKeyFile.length()]; privateDis.readFully(privateKeyBytes); privateDis.close(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); KeySpec privateKs = new PKCS8EncodedKeySpec(privateKeyBytes); PrivateKey privateKey = keyFactory.generatePrivate(privateKs); File publicKeyFile = new File(publicKeyPath); DataInputStream publicDis = new DataInputStream(new FileInputStream(publicKeyFile)); byte[] publicKeyBytes = new byte[(int) publicKeyFile.length()]; publicDis.readFully(publicKeyBytes); publicDis.close(); KeySpec publicKs = new X509EncodedKeySpec(publicKeyBytes); PublicKey publicKey = keyFactory.generatePublic(publicKs); producer.setPrivateKey(privateKey); producer.setPublicKey(publicKey); } if (certPath != null && !"".equals(certPath)) { InputStream inputStream = new FileInputStream(certPath); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream); inputStream.close(); producer.setCertificate(cert); } if (hasDigest) { producer.setDigestMethod(DMType.SHA256); } return producer; }
From source file:com.solace.samples.cloudfoundry.securesession.controller.SolaceController.java
/** * This utility function installs a certificate into the JRE's trusted * store. Normally you would not do this, but this is provided to * demonstrate how to use TLS, and have the client validate a self-signed * server certificate./* w ww . j a v a 2 s .c o m*/ * * @throws Exception */ private static void importCertificate() throws Exception { File file = new File(CERTIFICATE_FILE_NAME); logger.info("Loading certificate from " + file.getAbsolutePath()); // This loads the KeyStore from the default location // (i.e. default for a Clound Foundry app) using the default password. FileInputStream is = new FileInputStream(TRUST_STORE); char[] password = TRUST_STORE_PASSWORD.toCharArray(); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(is, password); is.close(); // Create an ByteArrayInputStream stream from the FileInputStream fis = new FileInputStream(CERTIFICATE_FILE_NAME); DataInputStream dis = new DataInputStream(fis); byte[] bytes = new byte[dis.available()]; dis.readFully(bytes); dis.close(); ByteArrayInputStream certstream = new ByteArrayInputStream(bytes); // This takes that Byte Array and creates a certificate out of it. CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate certs = cf.generateCertificate(certstream); // Finally, store the new certificate in the keystore. keystore.setCertificateEntry(CERTIFICATE_ALIAS, certs); // Save the new keystore contents FileOutputStream out = new FileOutputStream(TRUST_STORE); keystore.store(out, password); out.close(); }
From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java
/** * Gets the public key from file./*from ww w .j a va 2 s . c o m*/ * * @param file the file * @return the public * @throws IOException the i/o exception * @throws InvalidKeyException invalid key exception */ public static PublicKey getPublic(File file) throws IOException, InvalidKeyException { DataInputStream dis = null; try { FileInputStream fis = new FileInputStream(file); dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) file.length()]; dis.readFully(keyBytes); return getPublic(keyBytes); } finally { IOUtils.closeQuietly(dis); } }
From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java
/** * Gets the private key from file.// w ww . j a va 2 s .c o m * * @param file the file * @return the private * @throws IOException the i/o exception * @throws InvalidKeyException invalid key exception */ public static PrivateKey getPrivate(File file) throws IOException, InvalidKeyException { DataInputStream dis = null; try { FileInputStream fis = new FileInputStream(file); dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) file.length()]; dis.readFully(keyBytes); return getPrivate(keyBytes); } finally { IOUtils.closeQuietly(dis); } }
From source file:org.locationtech.geomesa.bigtable.spark.BigtableInputFormatBase.java
public static BigtableExtendedScan stringToScan(String encoded) throws IOException { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(encoded))); int tableLength = dis.readInt(); byte[] table = new byte[tableLength]; dis.read(table, 0, tableLength);// w w w .ja v a2s. c o m int available = dis.available(); byte[] rowsetbytes = new byte[available]; dis.readFully(rowsetbytes); RowSet rs = RowSet.parseFrom(rowsetbytes); BigtableExtendedScan scan = new BigtableExtendedScan(); rs.getRowRangesList().forEach(scan::addRange); scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, table); return scan; }
From source file:com.google.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 ww w .j ava2 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. */ 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 (LOCAL_LOGV) { 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()); } } } } 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:it.infn.ct.InstantiateVM.java
public static String doCreate(Properties properties, EntityBuilder eb, Model model, Client client, JSONObject egiInput) {/*from w w w . ja va 2 s . co m*/ URI uri_location = null; String networkInterfaceLocation = ""; String networkInterfaceLocation_stripped = ""; Resource vm_resource = null; try { if (properties.getProperty("RESOURCE").equals("compute")) { String segments[] = properties.getProperty("OCCI_OS_TPL").split("#"); String OCCI_OS_TPL = segments[segments.length - 1]; String segments2[] = properties.getProperty("OCCI_RESOURCE_TPL").split("#"); String OCCI_RESOURCE_TPL = segments2[segments2.length - 1]; System.out.println("[+] Creating a new compute Virtual Machine (VM)"); // Creating a compute instance Resource compute = eb.getResource("compute"); Mixin mixin = model.findMixin(OCCI_OS_TPL); compute.addMixin(mixin); compute.addMixin(model.findMixin(OCCI_OS_TPL, "os_tpl")); compute.addMixin(model.findMixin(OCCI_RESOURCE_TPL, "resource_tpl")); // Checking the context if (properties.getProperty("PUBLIC_KEY_FILE") != null && !properties.getProperty("PUBLIC_KEY_FILE").isEmpty()) { String _public_key_file = properties.getProperty("PUBLIC_KEY_FILE") .substring(properties.getProperty("PUBLIC_KEY_FILE").lastIndexOf(":") + 1); File f = new File(_public_key_file); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) f.length()]; dis.readFully(keyBytes); dis.close(); String _publicKey = new String(keyBytes).trim(); // Add SSH public key compute.addMixin(model .findMixin(URI.create("http://schemas.openstack.org/instance/credentials#public_key"))); compute.addAttribute("org.openstack.credentials.publickey.data", _publicKey); // Add the name for the public key if (OCCI_PUBLICKEY_NAME != null && !OCCI_PUBLICKEY_NAME.isEmpty()) compute.addAttribute("org.openstack.credentials.publickey.name", properties.getProperty("OCCI_PUBLICKEY_NAME")); } if (properties.getProperty("USER_DATA") != null && !properties.getProperty("USER_DATA").isEmpty()) { String _user_data = properties.getProperty("USER_DATA") .substring(properties.getProperty("USER_DATA").lastIndexOf(":") + 1); File f = new File(_user_data); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) f.length()]; dis.readFully(keyBytes); dis.close(); byte[] data = Base64.encodeBase64(keyBytes); String user_data = new String(data); compute.addMixin( model.findMixin(URI.create("http://schemas.openstack.org/compute/instance#user_data"))); compute.addAttribute("org.openstack.compute.user_data", user_data); } // Set VM title compute.setTitle(properties.getProperty("OCCI_CORE_TITLE")); URI location = client.create(compute); return location.toString(); } if (properties.getProperty("RESOURCE").equals("storage")) { System.out.println("[+] Creating a volume storage"); // Creating a storage instance Storage storage = eb.getStorage(); storage.setTitle(properties.getProperty("OCCI_CORE_TITLE")); storage.setSize(properties.getProperty("OCCI_STORAGE_SIZE")); URI storageLocation = client.create(storage); List<URI> list = client.list("storage"); List<URI> storageURIs = new ArrayList<URI>(); for (URI uri : list) { if (uri.toString().contains("storage")) storageURIs.add(uri); } System.out.println("URI = " + storageLocation); } } catch (FileNotFoundException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } catch (EntityBuildingException | AmbiguousIdentifierException | InvalidAttributeValueException | CommunicationException ex) { throw new RuntimeException(ex); } return ""; }
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./* ww w .j a va 2s. c o 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. */ 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: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.// www. ja v a 2 s . c o 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:org.apache.jackrabbit.core.persistence.util.Serializer.java
/** * Deserializes a <code>NodeState</code> object from the given binary * <code>stream</code>.//from w w w . j a v a 2 s . com * * @param state <code>state</code> to deserialize * @param stream the stream where the <code>state</code> should be deserialized from * @throws Exception if an error occurs during the deserialization * @see #serialize(NodeState, OutputStream) */ public static void deserialize(NodeState state, InputStream stream) throws Exception { DataInputStream in = new DataInputStream(stream); // primaryType String s = in.readUTF(); state.setNodeTypeName(NameFactoryImpl.getInstance().create(s)); // parentUUID (may be null) byte[] uuidBytes = new byte[NodeId.UUID_BYTE_LENGTH]; in.readFully(uuidBytes); if (!Arrays.equals(uuidBytes, NULL_UUID_PLACEHOLDER_BYTES)) { state.setParentId(new NodeId(uuidBytes)); } // definitionId in.readUTF(); // mixin types int count = in.readInt(); // count Set<Name> set = new HashSet<Name>(count); for (int i = 0; i < count; i++) { set.add(NameFactoryImpl.getInstance().create(in.readUTF())); } if (set.size() > 0) { state.setMixinTypeNames(set); } // modCount short modCount = in.readShort(); state.setModCount(modCount); // properties (names) count = in.readInt(); // count for (int i = 0; i < count; i++) { state.addPropertyName(NameFactoryImpl.getInstance().create(in.readUTF())); // name } // child nodes (list of name/uuid pairs) count = in.readInt(); // count for (int i = 0; i < count; i++) { Name name = NameFactoryImpl.getInstance().create(in.readUTF()); // name // uuid in.readFully(uuidBytes); state.addChildNodeEntry(name, new NodeId(uuidBytes)); } }