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:edu.umn.cs.spatialHadoop.core.RTreeGridRecordWriter.java

/**
 * Closes a cell by writing all outstanding objects and closing current file.
 * Then, the file is read again, an RTree is built on top of it and, finally,
 * the file is written again with the RTree built.
 *///from   w  ww .  j  a v  a  2 s  .c o  m
@Override
protected Path flushAllEntries(Path intermediateCellPath, OutputStream intermediateCellStream,
        Path finalCellPath) throws IOException {
    // Close stream to current intermediate file.
    intermediateCellStream.close();

    // Read all data of the written file in memory
    byte[] cellData = new byte[(int) new File(intermediateCellPath.toUri().getPath()).length()];
    InputStream cellIn = new FileInputStream(intermediateCellPath.toUri().getPath());
    cellIn.read(cellData);
    cellIn.close();

    // Build an RTree over the elements read from file
    // It should create a new stream
    DataOutputStream cellStream = (DataOutputStream) createFinalCellStream(finalCellPath);
    cellStream.writeLong(SpatialSite.RTreeFileMarker);
    int degree = 4096 / RTree.NodeSize;
    RTree.bulkLoadWrite(cellData, 0, cellData.length, degree, cellStream, stockObject.clone(), fastRTree);
    cellStream.close();
    cellData = null; // To allow GC to collect it

    return finalCellPath;
}

From source file:com.netflix.aegisthus.tools.StorageHelper.java

public void logCommit(String file) throws IOException {
    Path log = commitPath(getTaskId());
    if (debug) {//from  www.  ja v a  2  s .  c  om
        LOG.info(String.format("logging (%s) to commit log (%s)", file, log.toUri().toString()));
    }
    FileSystem fs = log.getFileSystem(config);
    DataOutputStream os = null;
    if (fs.exists(log)) {
        os = fs.append(log);
    } else {
        os = fs.create(log);
    }
    os.writeBytes(file);
    os.write('\n');
    os.close();
}

From source file:com.mendhak.gpslogger.senders.googledrive.GoogleDriveJob.java

private String updateFileContents(String authToken, String gpxFileId, byte[] fileContents, String fileName) {
    HttpURLConnection conn = null;
    String fileId = null;//from   ww  w. ja va  2 s .  c  om

    String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId
            + "?uploadType=media";

    try {

        URL url = new URL(fileUpdateUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", getMimeTypeFromFileName(fileName));
        conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length));

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setConnectTimeout(10000);
        conn.setReadTimeout(30000);

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(fileContents);
        wr.flush();
        wr.close();

        String fileMetadata = Streams.getStringFromInputStream(conn.getInputStream());

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        LOG.debug("File updated : " + fileId);

    } catch (Exception e) {
        LOG.error("Could not update contents", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    return fileId;
}

From source file:com.ebay.erl.mobius.core.model.TupleTest.java

/**
 * test serialization and de-serialization
 * // w ww  . jav  a  2 s . co m
 * @throws IOException
 */
@Test
public void test_serde() throws IOException {
    Tuple t = this.prepareTupe();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bos);

    t.write(out);

    out.flush();
    out.close();

    DataInputStream in = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));

    Tuple nt = new Tuple();
    nt.readFields(in);

    // ordering doesn't matter
    nt.setSchema(new String[] { "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10", "C11", "C12" });

    this._assertp_tuple(nt);
}

From source file:com.orchestra.portale.profiler.FbProfiler.java

private HttpURLConnection addParameter(HttpURLConnection connection, Map<String, String> params)
        throws IOException {

    if (params != null) {
        String param_string = "";
        for (String k : params.keySet()) {
            param_string += k + "=" + params.get(k) + "&";
        }//from   www  .  ja  v  a 2  s  . c o m

        param_string = param_string.substring(0, param_string.length() - 1);

        connection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(param_string);
        wr.flush();
        wr.close();
    }
    return connection;
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

public void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

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

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);/* w  w  w. j a  va2 s .c  o  m*/
    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);
    }
    in.close();

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

From source file:de.ingrid.iplug.csw.dsc.cswclient.impl.XMLPostRequest.java

/**
 * Send the given request to the server.
 * @param serverURL/*from w w w  . j  a va 2 s .  c  om*/
 * @param payload
 * @return Document
 * @throws Exception 
 */
protected Document sendRequest(String requestURL, OMElement payload) throws Exception {
    // and make the call
    Document result = null;
    HttpURLConnection conn = null;
    try {
        URL url = new URL(requestURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setAllowUserInteraction(false);
        conn.setReadTimeout(10000);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-type", "text/xml");
        conn.connect();

        // send the request
        String xmlToSend = serializeElement(payload.cloneOMElement());
        if (log.isDebugEnabled())
            log.debug("Request: " + xmlToSend);
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(xmlToSend);
        wr.flush();
        wr.close();

        // Get response data.
        int code = conn.getResponseCode();
        if (code >= 200 && code < 300) {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            result = builder.parse(conn.getInputStream());
        }
        conn.disconnect();
        conn = null;
    } catch (Exception e) {
        throw e;
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return result;
}

From source file:de.kasoki.jfeedly.helper.HTTPConnections.java

private String sendRequest(String apiUrl, String parameters, boolean isAuthenticated, RequestType type,
        String contentType) {// ww  w  . j  a  v  a  2s.  co  m
    try {
        String url = this.jfeedlyHandler.getBaseUrl() + apiUrl.replaceAll(" ", "%20");
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestProperty("User-Agent", "jfeedly");

        if (!contentType.isEmpty()) {
            con.setRequestProperty("Content-Type", contentType);
        }

        if (isAuthenticated) {
            con.setRequestProperty("Authorization",
                    "OAuth " + this.jfeedlyHandler.getConnection().getAccessToken());
        }

        // Send request header
        if (type == RequestType.POST) {
            con.setRequestMethod("POST");

            con.setDoOutput(true);

            DataOutputStream writer = new DataOutputStream(con.getOutputStream());

            writer.write(parameters.getBytes());
            writer.flush();

            writer.close();
        } else if (type == RequestType.GET) {
            con.setRequestMethod("GET");
        } else if (type == RequestType.DELETE) {
            con.setRequestMethod("DELETE");
        } else {
            System.err.println("jfeedly: Unkown RequestType " + type);
        }

        int responseCode = con.getResponseCode();

        if (jfeedlyHandler.getVerbose()) {
            System.out.println("\n" + type + " to: " + url);
            System.out.println("content : " + parameters);
            System.out.println("\nResponse Code : " + responseCode);
        }

        BufferedReader in = null;

        // if error occurred
        if (responseCode >= 400) {
            in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        } else {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        }

        String inputLine;
        StringBuffer response = new StringBuffer();

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

        in.close();

        String serverResponse = response.toString();

        if (jfeedlyHandler.getVerbose()) {
            //print response
            String printableResponse = format(serverResponse);

            if (responseCode >= 400) {
                System.err.println(printableResponse);
            } else {
                System.out.println(printableResponse);
            }
        }

        return serverResponse;
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return null;
}

From source file:moodle.android.moodle.helpers.MoodleWebService.java

private JSONObject getWebServiceResponse(String serverurl, String functionName, String urlParameters,
        int xslRawId) {
    JSONObject jsonobj = null;/*from   w  w  w. j  a  v a  2 s  .c  o m*/

    try {
        HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName).openConnection();
        //HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName + "&moodlewsrestformat=json").openConnection();

        con.setConnectTimeout(30000);
        con.setReadTimeout(30000);

        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Content-Language", "en-US");
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setDoInput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());

        Log.d("URLParameters: ", urlParameters.toString());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        //Get Response
        InputStream is = con.getInputStream();

        Source xmlSource = new StreamSource(is);
        Source xsltSource = new StreamSource(context.getResources().openRawResource(xslRawId));

        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer(xsltSource);
        StringWriter writer = new StringWriter();
        trans.transform(xmlSource, new StreamResult(writer));

        String jsonstr = writer.toString();
        jsonstr = jsonstr.replace("<div class=\"no-overflow\"><p>", "");
        jsonstr = jsonstr.replace("</p></div>", "");
        jsonstr = jsonstr.replace("<p>", "");
        jsonstr = jsonstr.replace("</p>", "");
        Log.d("TransformObject: ", jsonstr);
        jsonobj = new JSONObject(jsonstr);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block 
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        // TODO Auto-generated catch block 
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block 
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jsonobj;
}

From source file:honeypot.services.WepawetServiceImpl.java

/**
 * {@inheritDoc}/*  w w  w .jav  a 2 s  .  c  o m*/
 * @see honeypot.services.WepawetService#process(java.lang.String)
 */
@Transactional
public void process(final String message) {
    try {
        URL url = new URL("http://wepawet.cs.ucsb.edu/services/upload.php");
        String parameters = "resource_type=js&url=" + URLEncoder.encode(message, "UTF-8");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(parameters);
        wr.flush();
        wr.close();

        if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
            InputStream is = connection.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int data;
            while ((data = is.read()) != -1) {
                os.write(data);
            }
            is.close();
            // Process the XML message.
            handleProcessMsg(new ByteArrayInputStream(os.toByteArray()));
            os.close();
        }
    } catch (final Exception e) {
        log.error("Exception occured processing the message.", e);
        WepawetError wepawetError = new WepawetError();
        wepawetError.setCode("-1");
        wepawetError.setMessage(e.getMessage());
        wepawetError.setCreated(new Date());
        // Save the error to the database.
        entityManager.persist(wepawetError);
    }

}