Example usage for java.io DataOutputStream DataOutputStream

List of usage examples for java.io DataOutputStream DataOutputStream

Introduction

In this page you can find the example usage for java.io DataOutputStream DataOutputStream.

Prototype

public DataOutputStream(OutputStream out) 

Source Link

Document

Creates a new data output stream to write data to the specified underlying output stream.

Usage

From source file:com.esri.geoevent.test.performance.bds.BdsEventConsumer.java

private int getMsLayerCount(String url) {
    int cnt = -1;

    try {//from  w  ww.j a v  a  2s.  c o  m
        URL obj = new URL(url + "/query");
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add request header
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Accept", "text/plain");

        String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly="
                + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        String jsonString = response.toString();

        JSONTokener tokener = new JSONTokener(jsonString);

        JSONObject root = new JSONObject(tokener);

        cnt = root.getInt("count");

    } catch (Exception e) {
        cnt = -2;
    } finally {
        return cnt;
    }

}

From source file:com.tonchidot.nfc_contact_exchanger.lib.PictureUploader.java

private String doFileUploadJson(String url, String fileParamName, byte[] data) {
    try {/*from  w w  w . j  ava2  s  . c o m*/
        String boundary = "BOUNDARY" + new Date().getTime() + "BOUNDARY";
        String lineEnd = "\r\n";
        String twoHyphens = "--";

        URL connUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) connUrl.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"" + fileParamName + "\";filename=\"photo.jpg\""
                + lineEnd);
        dos.writeBytes(lineEnd);
        dos.write(data, 0, data.length);
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush();
        dos.close();

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        return result.toString();
    } catch (IOException e) {
        if (Config.LOGD) {
            Log.d(TAG, "IOException : " + e);
        }
    }
    return null;
}

From source file:WriteDoubleUsingSockets.java

public void init() {
    Date d = new Date();
    // Get the portnumber and servername and allow to be called from a
    // java main program also
    try {//from  w w  w.j a  v  a 2 s. c  o  m
        String param;
        param = getParameter("PortNumber");
        if (param != null)
            PortNumber = Integer.parseInt(param);
        param = getParameter("ServerName");
        if (param != null)
            ServerName = param;
    } catch (NullPointerException e) { // Must be called from a main ignore
    }
    try {
        Socket skt = new Socket(ServerName, PortNumber);
        os = new DataOutputStream(skt.getOutputStream());
    } catch (Exception e) {
        Label l = new Label(e.toString());
        add(l);
        System.out.println(e);
        return;
    }
    try {
        s = new ObjectOutputStream(os);
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("Unable to open stream as an object stream");
    }
    try {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 25; i++) {
            s.writeObject(new Double(i));
        }
        os.close();
        long endTime = System.currentTimeMillis() - startTime;
        Label l = new Label(
                "Writing 25 doubles server took: " + new Long(endTime).toString() + " milliseconds.");
        add(l);
        System.out.println("Object written");
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("Unable to write Objects");
    }
}

From source file:com.ning.arecibo.util.timeline.samples.TestSampleCoder.java

@Test(groups = "fast")
public void testScan() throws Exception {
    final DateTime startTime = new DateTime(DateTimeZone.UTC);
    final DateTime endTime = startTime.plusSeconds(5);
    final List<DateTime> dateTimes = ImmutableList.<DateTime>of(startTime.plusSeconds(1),
            startTime.plusSeconds(2), startTime.plusSeconds(3), startTime.plusSeconds(4));
    final byte[] compressedTimes = timelineCoder.compressDateTimes(dateTimes);

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
    final ScalarSample<Short> sample = new ScalarSample<Short>(SampleOpcode.SHORT, (short) 4);
    sampleCoder.encodeSample(dataOutputStream, sample);
    sampleCoder.encodeSample(dataOutputStream, new RepeatSample<Short>(3, sample));
    dataOutputStream.close();//from   ww  w.j  av a 2s  . co  m

    sampleCoder.scan(outputStream.toByteArray(), compressedTimes, dateTimes.size(),
            new TimeRangeSampleProcessor(startTime, endTime) {
                @Override
                public void processOneSample(final DateTime time, final SampleOpcode opcode,
                        final Object value) {
                    Assert.assertTrue(time.isAfter(startTime));
                    Assert.assertTrue(time.isBefore(endTime));
                    Assert.assertEquals(Short.valueOf(value.toString()), sample.getSampleValue());
                }
            });
}

From source file:Main.IrcBot.java

public static void postRequest(String pasteCode, PrintWriter out) {
    try {/*from   w  w w  . j a  va 2 s.c o m*/
        String url = "http://pastebin.com/raw.php?i=" + pasteCode;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine + "\n");
        }
        in.close();

        //print result
        System.out.println(response.toString());

        if (response.length() > 0) {
            IrcBot.postGit(response.toString(), out);
        } else {
            out.println("PRIVMSG #learnprogramming :The PasteBin URL is not valid.");
        }
    } catch (Exception p) {

    }
}

From source file:com.trsst.client.MultiPartRequestEntity.java

public void writeRequest(OutputStream arg0) throws IOException {
    DataOutputStream out = new DataOutputStream(arg0);
    out.writeBytes("--" + boundary + "\r\n");
    writeEntry(base, out);/*from   www.j av  a  2  s.c o m*/
    out.writeBytes("--" + boundary + "\r\n");
    if (content != null) {
        for (int i = 0; i < content.length; i++) {
            writeContent(content[i], contentId[i], contentType[i], out);
            out.writeBytes("\r\n" + "--" + boundary + "--");
        }
    }
    out.flush();
}

From source file:com.github.terma.m.server.Repo.java

public void addEvents(final List<Event> events) throws IOException {
    try (DataOutputStream oos = new DataOutputStream(new FileOutputStream(eventsFile, true))) {
        for (Event event : events) {
            oos.writeShort(event.metricCode);
            oos.writeLong(event.timestamp);
            oos.writeLong(event.value);//from ww  w  .j  a va 2  s  .c o  m
        }
    }
}

From source file:com.facebook.infrastructure.net.UdpConnection.java

public boolean write(Message message, EndPoint to) throws IOException {
    boolean bVal = true;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    Message.serializer().serialize(message, dos);
    byte[] data = bos.toByteArray();
    if (data.length > 0) {
        logger_.trace("Size of Gossip packet " + data.length);
        byte[] protocol = BasicUtilities.intToByteArray(protocol_);
        ByteBuffer buffer = ByteBuffer.allocate(data.length + protocol.length);
        buffer.put(protocol);/*from   w  w  w  .j  ava 2  s .  com*/
        buffer.put(data);
        buffer.flip();

        int n = socketChannel_.send(buffer, to.getInetAddress());
        if (n == 0) {
            bVal = false;
        }
    }
    return bVal;
}

From source file:me.sonarbeserk.lockup.utils.UUIDFetcher.java

private static void writeBody(HttpURLConnection connection, String body) throws Exception {
    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
    writer.write(body.getBytes());//from   ww  w  . j ava2s.com
    writer.flush();
    writer.close();
}

From source file:com.atilika.kuromoji.trie.DoubleArrayTrie.java

public void write(OutputStream output) throws IOException {

    baseBuffer.rewind();//from w  w  w.  j  ava2s.co m
    checkBuffer.rewind();
    tailBuffer.rewind();

    int baseCheckSize = Math.min(maxBaseCheckIndex + 64, baseBuffer.capacity());
    int tailSize = Math.min(tailIndex - TAIL_OFFSET + 64, tailBuffer.capacity());

    DataOutputStream dataOutput = new DataOutputStream(new BufferedOutputStream(output));

    dataOutput.writeBoolean(compact);
    dataOutput.writeInt(baseCheckSize);
    dataOutput.writeInt(tailSize);

    WritableByteChannel channel = Channels.newChannel(dataOutput);

    ByteBuffer tmpBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    IntBuffer tmpIntBuffer = tmpBuffer.asIntBuffer();
    tmpIntBuffer.put(baseBuffer.array(), 0, baseCheckSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    tmpBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    tmpIntBuffer = tmpBuffer.asIntBuffer();
    tmpIntBuffer.put(checkBuffer.array(), 0, baseCheckSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    tmpBuffer = ByteBuffer.allocate(tailSize * 2);
    CharBuffer tmpCharBuffer = tmpBuffer.asCharBuffer();
    tmpCharBuffer.put(tailBuffer.array(), 0, tailSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    dataOutput.flush();
}