List of usage examples for java.io DataOutputStream DataOutputStream
public DataOutputStream(OutputStream out)
From source file:gaffer.accumulostore.operation.spark.handler.GetJavaRDDOfAllElementsHandlerTest.java
@Test public void checkGetAllElementsInJavaRDD() throws OperationException, IOException { final Graph graph1 = new Graph.Builder() .addSchema(getClass().getResourceAsStream("/schema/dataSchema.json")) .addSchema(getClass().getResourceAsStream("/schema/dataTypes.json")) .addSchema(getClass().getResourceAsStream("/schema/storeTypes.json")) .storeProperties(getClass().getResourceAsStream("/store.properties")).build(); final List<Element> elements = new ArrayList<>(); final Set<Element> expectedElements = new HashSet<>(); for (int i = 0; i < 10; i++) { final Entity entity = new Entity(TestGroups.ENTITY); entity.setVertex("" + i); final Edge edge1 = new Edge(TestGroups.EDGE); edge1.setSource("" + i); edge1.setDestination("B"); edge1.setDirected(false);// w ww. jav a 2 s .c om edge1.putProperty(TestPropertyNames.COUNT, 2); final Edge edge2 = new Edge(TestGroups.EDGE); edge2.setSource("" + i); edge2.setDestination("C"); edge2.setDirected(false); edge2.putProperty(TestPropertyNames.COUNT, 4); elements.add(edge1); elements.add(edge2); elements.add(entity); expectedElements.add(edge1); expectedElements.add(edge2); expectedElements.add(entity); } final User user = new User(); graph1.execute(new AddElements(elements), user); final SparkConf sparkConf = new SparkConf().setMaster("local") .setAppName("testCheckGetCorrectElementsInJavaRDDForEntitySeed") .set("spark.serializer", "org.apache.spark.serializer.KryoSerializer") .set("spark.kryo.registrator", "gaffer.serialisation.kryo.Registrator") .set("spark.driver.allowMultipleContexts", "true"); final JavaSparkContext sparkContext = new JavaSparkContext(sparkConf); // Create Hadoop configuration and serialise to a string final Configuration configuration = new Configuration(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); configuration.write(new DataOutputStream(baos)); final String configurationString = new String(baos.toByteArray(), CommonConstants.UTF_8); // Check get correct edges for "1" final GetJavaRDDOfAllElements rddQuery = new GetJavaRDDOfAllElements.Builder() .javaSparkContext(sparkContext).build(); rddQuery.addOption(AbstractGetRDDOperationHandler.HADOOP_CONFIGURATION_KEY, configurationString); final JavaRDD<Element> rdd = graph1.execute(rddQuery, user); if (rdd == null) { fail("No RDD returned"); } final Set<Element> results = new HashSet<>(rdd.collect()); assertEquals(expectedElements, results); sparkContext.stop(); }
From source file:brickhouse.udf.bloom.BloomFactory.java
public static String WriteBloomToString(Filter bloom) throws IOException { if (bloom != null) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); bloom.write(new DataOutputStream(buffer)); byte[] encodedBloom = Base64.encodeBase64(buffer.toByteArray()); return new String(encodedBloom); } else {//from ww w. jav a 2s . c o m return null; } }
From source file:org.jongo.mocks.JongoClient.java
private JongoResponse doRequest(final String url, final String method, final String jsonParameters) { JongoResponse response = null;// w w w. j a va 2 s. co m try { HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection(); con.setRequestMethod(method); con.setRequestProperty("Accept", MediaType.APPLICATION_XML); con.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); con.setRequestProperty("Content-Length", "" + Integer.toString(jsonParameters.getBytes().length)); con.setDoOutput(true); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(jsonParameters); wr.flush(); wr.close(); // BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream())); BufferedReader r = null; if (con.getResponseCode() != Response.Status.OK.getStatusCode() && con.getResponseCode() != Response.Status.CREATED.getStatusCode()) { r = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { r = new BufferedReader(new InputStreamReader(con.getInputStream())); } StringBuilder rawresponse = new StringBuilder(); String strLine = null; while ((strLine = r.readLine()) != null) { rawresponse.append(strLine); rawresponse.append("\n"); } try { response = XmlXstreamTest.successFromXML(rawresponse.toString()); } catch (Exception e) { response = XmlXstreamTest.errorFromXML(rawresponse.toString()); } } catch (Exception ex) { ex.printStackTrace(); } return response; }
From source file:com.nokia.dempsy.messagetransport.tcp.TcpSender.java
private DataOutputStream getDataOutputStream() throws MessageTransportException, IOException { if (dataOutputStream == null) // socket must also be null. {/* ww w .ja v a2s . c o m*/ socket = makeSocket(destination); // There is a really odd circumstance (at least on Linux) where a connection // to a port in the dynamic range, while there is no listener on that port, // from the same system/network interface, can result in a local port selection // that's the same as the port that the connection attempt is to. In this case, // for some reason the Socket instantiation (and connection) succeeds without // a listener. We need to force a failure if this is the case. if (isLocalAddress == IsLocalAddress.Unknown) { if (socket.isBound()) { InetAddress localSocketAddress = socket.getLocalAddress(); isLocalAddress = (Arrays.equals(localSocketAddress.getAddress(), destination.inetAddress.getAddress())) ? IsLocalAddress.Yes : IsLocalAddress.No; } } if (isLocalAddress == IsLocalAddress.Yes) { if (socket.getLocalPort() == destination.port) throw new IOException("Connection to self same port!!!"); } dataOutputStream = new DataOutputStream(socket.getOutputStream()); } return dataOutputStream; }
From source file:edu.harvard.iq.dvn.unf.Base64Encoding.java
/** * Alternative tobase64 method.Encodes the String(byte[]) instead of the array * * @param digest byte array for encoding in base 64, * @param cset String with name of charset * @return String base 64 the encoded base64 of digest *///from ww w . ja v a2s .co m public static String tobase641(byte[] digest, String cset) { byte[] revdigest = changeByteOrder(digest, ByteOrder.nativeOrder()); String str = null; str = new String(revdigest); ByteArrayOutputStream btstream = new ByteArrayOutputStream(); //this make sure is written in big-endian DataOutputStream stream = new DataOutputStream(btstream); String tobase64 = null; //use a charset for encoding if (cset == null) { cset = DEFAULT_CHAR_ENCODING; } BCodec bc = new BCodec(cset); try { tobase64 = (String) bc.encode(str); } catch (EncoderException err) { mLog.info("base64Encoding: exception" + err.getMessage()); } return tobase64; }
From source file:com.fullhousedev.globalchat.bukkit.PluginMessageManager.java
public static void chatMessage(String userTo, String userFrom, String message, Plugin pl) { try {//from w w w . j a va 2 s. c o m ByteArrayOutputStream customData = new ByteArrayOutputStream(); DataOutputStream outCustom = new DataOutputStream(customData); outCustom.writeUTF(userTo); outCustom.writeUTF(userFrom); outCustom.writeUTF(message); sendRawMessage("chatmessage", "ALL", customData.toByteArray(), pl); } catch (IOException ex) { Logger.getLogger(GlobalChat.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:net.mms_projects.copy_it.server.push.android.GCMRunnable.java
public void run() { try {// w w w . jav a2 s . co m URL url = new URL(GCM_URL); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod(POST); conn.setRequestProperty(CONTENT_TYPE, Page.ContentTypes.JSON_TYPE); conn.setRequestProperty(AUTHORIZATION, KEY); final String output_json = full.toString(); System.err.println("Input json: " + output_json); conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(output_json.length())); conn.setDoOutput(true); conn.setDoInput(true); DataOutputStream outputstream = new DataOutputStream(conn.getOutputStream()); outputstream.writeBytes(output_json); outputstream.close(); DataInputStream input = new DataInputStream(conn.getInputStream()); StringBuilder builder = new StringBuilder(input.available()); for (int c = input.read(); c != -1; c = input.read()) builder.append((char) c); input.close(); output = new JSONObject(builder.toString()); System.err.println("Output json: " + output.toString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.davidcode.code.util.ErrorBuffer.java
/** * Writes the data to a socket using prehistoric java * * @param socket/*from w w w.jav a2 s. com*/ * @throws IOException */ public void write(Socket socket) throws IOException { //Get the data in byte form byte[] outputBuf = asByteArray(); outputBuf = xor(outputBuf); //Write the data to the socket which is connected to a server for recieving this data DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); dataOutputStream.write(outputBuf); //Flush and close the stream dataOutputStream.flush(); dataOutputStream.close(); }
From source file:com.jivesoftware.os.amza.service.replication.http.endpoints.AmzaReplicationRestEndpoints.java
@POST @Consumes(MediaType.APPLICATION_JSON)/* w w w . j ava 2s . co m*/ @Produces(MediaType.APPLICATION_OCTET_STREAM) @Path("/rows/stream/{ringMemberString}/{versionedPartitionName}/{takeSessionId}/{txId}/{leadershipToken}/{limit}") public Response rowsStream(@PathParam("ringMemberString") String ringMemberString, @PathParam("versionedPartitionName") String versionedPartitionName, @PathParam("takeSessionId") long takeSessionId, @PathParam("txId") long txId, @PathParam("leadershipToken") long leadershipToken, @PathParam("limit") long limit, byte[] takeSharedKey) { try { amzaStats.rowsStream.increment(); StreamingOutput stream = (OutputStream os) -> { os.flush(); BufferedOutputStream bos = new BufferedOutputStream(new SnappyOutputStream(os), 8192); // TODO expose to config final DataOutputStream dos = new DataOutputStream(bos); try { amzaInstance.rowsStream(dos, new RingMember(ringMemberString), VersionedPartitionName.fromBase64(versionedPartitionName, amzaInterner), takeSessionId, objectMapper.readValue(takeSharedKey, Long.class), txId, leadershipToken, limit); } catch (IOException x) { if (x.getCause() instanceof TimeoutException) { LOG.error("Timed out while streaming takes"); } else { LOG.error("Failed to stream takes.", x); } throw x; } catch (Exception x) { LOG.error("Failed to stream takes.", x); throw new IOException("Failed to stream takes.", x); } finally { dos.flush(); amzaStats.rowsStream.decrement(); amzaStats.completedRowsStream.increment(); } }; return Response.ok(stream).build(); } catch (Exception x) { Object[] vals = new Object[] { ringMemberString, versionedPartitionName, txId }; LOG.warn("Failed to rowsStream {} {} {}. ", vals, x); return ResponseHelper.INSTANCE.errorResponse("Failed to rowsStream " + Arrays.toString(vals), x); } }
From source file:com.csipsimple.backup.SipSharedPreferencesHelper.java
@Override public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) { boolean forceBackup = (oldState == null); long fileModified = 1; if (prefsFiles != null) { fileModified = prefsFiles.lastModified(); }/*from w w w . j av a2 s. com*/ try { if (!forceBackup) { FileInputStream instream = new FileInputStream(oldState.getFileDescriptor()); DataInputStream in = new DataInputStream(instream); long lastModified = in.readLong(); in.close(); if (lastModified < fileModified) { forceBackup = true; } } } catch (IOException e) { Log.e(THIS_FILE, "Cannot manage previous local backup state", e); forceBackup = true; } Log.d(THIS_FILE, "Will backup profiles ? " + forceBackup); if (forceBackup) { JSONObject settings = SipProfileJson.serializeSipSettings(mContext); try { writeData(data, settings.toString()); } catch (IOException e) { Log.e(THIS_FILE, "Cannot manage remote backup", e); } } try { FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor()); DataOutputStream out = new DataOutputStream(outstream); out.writeLong(fileModified); out.close(); } catch (IOException e) { Log.e(THIS_FILE, "Cannot manage final local backup state", e); } }