Example usage for java.io DataOutputStream close

List of usage examples for java.io DataOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:com.webkey.Ipc.java

public void sendMessage(String message) {
    readAuthKey();//from   w w w  . j  a va2  s .  co  m
    try {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context);
        port = prefs.getString("port", "80");
        Socket s = new Socket("127.0.0.1", Integer.parseInt(port));

        //outgoing stream redirect to socket
        DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream());
        byte[] utf = message.getBytes("UTF-8");
        dataOutputStream.writeBytes("POST /" + authKey + "phonewritechatmessage HTTP/1.1\r\n"
                + "Host: 127.0.0.1\r\n" + "Connection: close\r\n" + "Content-Length: "
                + Integer.toString(utf.length) + "\r\n\r\n");
        dataOutputStream.write(utf, 0, utf.length);
        dataOutputStream.flush();
        dataOutputStream.close();
        s.close();
    } catch (IOException e1) {
        //e1.printStackTrace();      
    }

}

From source file:com.formkiq.core.equifax.service.EquifaxServiceImpl.java

/**
 * Sends request to Equifax./*from   ww w .  ja v a  2  s  .  c om*/
 * @param server {@link String}
 * @param send {@link String}
 * @return {@link String}
 * @throws IOException IOException
 */
public String sendToEquifax(final String server, final String send) throws IOException {

    String params = "InputSegments=" + URLEncoder.encode(send, "UTF-8") + "&cmdSubmit=Submit";

    byte[] postData = params.getBytes(StandardCharsets.UTF_8);
    int postDataLength = postData.length;

    URL url = new URL(server);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setInstanceFollowRedirects(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.setRequestProperty("charset", "utf-8");
    conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
    conn.setUseCaches(false);

    Reader in = null;
    DataOutputStream wr = null;

    try {
        wr = new DataOutputStream(conn.getOutputStream());
        wr.write(postData);

        StringBuilder sb = new StringBuilder();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c = in.read(); c != -1; c = in.read()) {
            sb.append((char) c);
        }

        String receive = sb.toString();

        return receive;

    } finally {

        if (in != null) {
            in.close();
        }

        if (wr != null) {
            wr.close();
        }
    }
}

From source file:com.pinterest.deployservice.events.EventSenderImpl.java

public void sendDeployEvent(String what, String tags, String data) throws Exception {
    JsonObject object = new JsonObject();
    object.addProperty("what", what);
    object.addProperty("tags", tags);
    object.addProperty("data", data);
    final String paramsToSend = object.toString();
    DataOutputStream output = null;
    HttpURLConnection connection = null;
    int retry = 0;
    while (retry < TOTAL_RETRY) {
        try {//from w  w w.j a  v  a  2 s  .co  m
            URL requestUrl = new URL(this.URL);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setDoOutput(true);

            connection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            connection.setRequestProperty("Content-Length", Integer.toString(paramsToSend.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setRequestMethod("POST");
            output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(paramsToSend);
            output.flush();
            output.close();
            String result = IOUtils.toString(connection.getInputStream(), "UTF-8").toLowerCase();
            LOG.info("Successfully send events to the statsboard: " + result);
            return;
        } catch (Exception e) {
            LOG.error("Failed to send event", e);
        } finally {
            IOUtils.closeQuietly(output);
            if (connection != null) {
                connection.disconnect();
            }
            retry++;
        }
    }
    throw new DeployInternalException("Failed to send event");
}

From source file:com.hadoopvietnam.cache.memcached.MemcachedCache.java

/**
 * Get the byte[] from a ArrayList&lt;Long&gt;.
 *
 * @param inListOfLongs the list of longs to convert
 * @return the byte[] representation of the ArrayList
 * @throws IOException thrown if any errors encountered
 *//*from  w  ww. j  a v a  2 s .  c om*/
protected byte[] getBytesFromList(final List<Long> inListOfLongs) throws IOException {
    if (inListOfLongs == null) {
        return null;
    }

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bytes);
    byte[] toReturn = null;
    try {
        for (Long oneLong : inListOfLongs) {
            out.writeLong(oneLong);
            out.flush();
        }

        toReturn = bytes.toByteArray();
    } finally {
        out.close();
    }

    return toReturn;
}

From source file:pl.edu.agh.BackgroundServiceConnection.java

/**
 * Compares sent hash to the one in database
 *///w ww.  ja v a2 s  . co  m
public void run() {
    while (true) {
        try {
            LOGGER.info("Accepting connections on port: " + serverPort);
            Socket client = serverSocket.accept();

            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            String message = in.readLine();
            DataOutputStream out = new DataOutputStream(client.getOutputStream());

            LOGGER.info("Daemon message: " + message);

            String[] data = message.trim().split("\\|");
            try {
                Service service = serviceDAO.getById(Integer.parseInt(data[1]));
                if (!data[0].equalsIgnoreCase(service.getPassword()))
                    throw new IllegalArgumentException("Daemon password: " + data[0]
                            + " does not match server password: " + service.getPassword());
                out.writeBytes("OK\r\n");
            } catch (Exception e) {
                LOGGER.error("Could not find server: " + message.trim(), e);
                out.writeBytes("ERROR\r\n");
            }

            in.close();
            out.close();
            client.close();

        } catch (Exception e) {
            LOGGER.error("Error connecting with server: " + e.getMessage());
        }
    }
}

From source file:gr.iit.demokritos.cru.cpserver.CPServer.java

public void httpHandler(BufferedReader input, DataOutputStream output) throws IOException, Exception {

    String request = input.readLine();
    request = request.toUpperCase();//from w  ww  .ja v a 2s.c o  m
    if (request.startsWith("POST")) {

        output.writeBytes(create_response_header(200));
        output.writeBytes(create_response_body(request));
    } else if (request.startsWith("GET")) {
        //ERROR MSG
        //output.writeBytes("ERROR 404");
        output.writeBytes(create_response_header(200));
        output.writeBytes(create_response_body(request));
    } else {
        //ERROR MSG
        output.writeBytes("404");
    }

    output.close();
}

From source file:com.vimc.ahttp.HurlWorker.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void addBodyIfExists(HttpURLConnection connection, Request request) throws IOException {
    if (request.containsMutilpartData()) {
        connection.setDoOutput(true);/*  www .  j  a va2  s . co m*/
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());

        if (request.getStringParams().size() > 0) {
            writeStringFields(request.getStringParams(), out, request.getBoundray());
        }
        if (request.getFileParams().size() > 0) {
            writeFiles(request.getFileParams(), out, request.getBoundray());
        }
        if (request.getByteParams().size() > 0) {
            writeBytes(request.getByteParams(), out, request.getBoundray());
        }
        out.flush();
        out.close();
    } else {
        byte[] body = request.getStringBody();
        if (body != null) {
            connection.setDoOutput(true);
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(body);
            out.flush();
            out.close();
        }
    }
}

From source file:com.kyne.webby.rtk.web.WebServer.java

/**
 * Print the given String as plain text/*from  ww  w.  jav a2 s .  c  om*/
 * @param text the text to print
 * @param clientSocket the client-side socket
 */
public void printPlainText(final String text, final Socket clientSocket) {
    try {
        final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        out.writeBytes("HTTP/1.1 200 OK\r\n");
        out.writeBytes("Content-Type: text/plain; charset=utf-8\r\n");
        out.writeBytes("Cache-Control: no-cache \r\n");
        out.writeBytes("Server: Bukkit Webby\r\n");
        out.writeBytes("Connection: Close\r\n\r\n");
        out.writeBytes(text);
        out.flush();
        out.close();

    } catch (final SocketException e) {
        /* .. */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

From source file:eu.stratosphere.nephele.services.iomanager.IOManagerPerformanceBenchmark.java

private final void speedTestStream(int bufferSize) throws IOException {
    final Channel.ID tmpChannel = ioManager.createChannel();
    final IntegerRecord rec = new IntegerRecord(0);

    File tempFile = null;/* ww w.  j ava  2  s.c  o  m*/
    DataOutputStream daos = null;
    DataInputStream dais = null;

    try {
        tempFile = new File(tmpChannel.getPath());

        FileOutputStream fos = new FileOutputStream(tempFile);
        daos = new DataOutputStream(new BufferedOutputStream(fos, bufferSize));

        long writeStart = System.currentTimeMillis();

        int valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            rec.setValue(valsLeft);
            rec.write(daos);
        }
        daos.close();
        daos = null;

        long writeElapsed = System.currentTimeMillis() - writeStart;

        // ----------------------------------------------------------------

        FileInputStream fis = new FileInputStream(tempFile);
        dais = new DataInputStream(new BufferedInputStream(fis, bufferSize));

        long readStart = System.currentTimeMillis();

        valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            rec.read(dais);
        }
        dais.close();
        dais = null;

        long readElapsed = System.currentTimeMillis() - readStart;

        LOG.info("File-Stream with buffer " + bufferSize + ": write " + writeElapsed + " msecs, read "
                + readElapsed + " msecs.");
    } finally {
        // close if possible
        if (daos != null) {
            daos.close();
        }
        if (dais != null) {
            dais.close();
        }
        // try to delete the file
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:BugTracker.java

private void saveBugs() {
    // Save bugs to a file.
    DataOutputStream out = null;
    try {//w  w  w  . j ava2  s . co  m
        File file = new File("bugs.dat");

        out = new DataOutputStream(new FileOutputStream(file));

        for (int i = 0; i < table.getItemCount(); i++) {
            TableItem item = table.getItem(i);
            out.writeUTF(item.getText(0));
            out.writeUTF(item.getText(1));
            out.writeUTF(item.getText(2));
            out.writeBoolean(item.getText(3).equalsIgnoreCase("YES"));
        }
    } catch (IOException ioe) {
        // Ignore.
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}