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:org.wso2.carbon.appmgt.sample.deployer.http.HttpHandler.java

/**
 * This method is used to do a https post request
 *
 * @param url         request url//  w  ww  .  j  ava2s  .c o m
 * @param payload     Content of the post request
 * @param sessionId   sessionId for authentication
 * @param contentType content type of the post request
 * @return response
 * @throws java.io.IOException - Throws this when failed to fulfill a https post request
 */
public String doPostHttps(String url, String payload, String sessionId, String contentType) throws IOException {
    URL obj = new URL(url);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    if (!sessionId.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
    }
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (sessionId.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (sessionId.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:it.acubelab.batframework.systemPlugins.TagmeAnnotator.java

@Override
public HashSet<ScoredAnnotation> solveSa2W(String text) throws AnnotationException {
    // System.out.println(text.length()+ " "+text.substring(0,
    // Math.min(text.length(), 15)));
    // TODO: workaround for a bug in tagme. should be deleted afterwards.
    String newText = "";
    for (int i = 0; i < text.length(); i++)
        newText += (text.charAt(i) > 127 ? ' ' : text.charAt(i));
    text = newText;//from www . j  ava 2  s.  c om

    // avoid crashes for empty documents
    int j = 0;
    while (j < text.length() && text.charAt(j) == ' ')
        j++;
    if (j == text.length())
        return new HashSet<ScoredAnnotation>();

    HashSet<ScoredAnnotation> res;
    String params = null;
    try {
        res = new HashSet<ScoredAnnotation>();

        params = "key=" + this.key;
        params += "&lang=en";
        if (epsilon >= 0)
            params += "&epsilon=" + epsilon;
        if (minComm >= 0)
            params += "&min_comm=" + minComm;
        if (minLink >= 0)
            params += "&min_link=" + minLink;
        params += "&text=" + URLEncoder.encode(text, "UTF-8");
        URL wikiApi = new URL(url);

        HttpURLConnection slConnection = (HttpURLConnection) wikiApi.openConnection();
        slConnection.setRequestProperty("accept", "text/xml");
        slConnection.setDoOutput(true);
        slConnection.setDoInput(true);
        slConnection.setRequestMethod("POST");
        slConnection.setRequestProperty("charset", "utf-8");
        slConnection.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
        slConnection.setUseCaches(false);
        slConnection.setReadTimeout(0);

        DataOutputStream wr = new DataOutputStream(slConnection.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();

        Scanner s = new Scanner(slConnection.getInputStream());
        Scanner s2 = s.useDelimiter("\\A");
        String resultStr = s2.hasNext() ? s2.next() : "";
        s.close();

        JSONObject obj = (JSONObject) JSONValue.parse(resultStr);
        lastTime = (Long) obj.get("time");

        JSONArray jsAnnotations = (JSONArray) obj.get("annotations");
        for (Object js_ann_obj : jsAnnotations) {
            JSONObject js_ann = (JSONObject) js_ann_obj;
            System.out.println(js_ann);
            int start = ((Long) js_ann.get("start")).intValue();
            int end = ((Long) js_ann.get("end")).intValue();
            int id = ((Long) js_ann.get("id")).intValue();
            float rho = Float.parseFloat((String) js_ann.get("rho"));
            System.out.println(text.substring(start, end) + "->" + id + " (" + rho + ")");
            res.add(new ScoredAnnotation(start, end - start, id, (float) rho));
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new AnnotationException("An error occurred while querying TagMe API. Message: " + e.getMessage()
                + " Parameters:" + params);
    }
    return res;

}

From source file:com.chinamobile.bcbsp.comm.DiskManager.java

/**
 * Save messages of every partition on disk.
 * @param msgList//w  w  w  .ja  va  2s  .  c  o m
 * @param superStep
 * @param srcPartitionDstBucket
 * @throws IOException e
 */
public void processMessagesSave(ArrayList<IMessage> msgList, int superStep, int srcPartitionDstBucket)
        throws IOException {
    int count = msgList.size();
    int bucket = PartitionRule.getBucket(srcPartitionDstBucket);
    int srcPartition = PartitionRule.getPartition(srcPartitionDstBucket);
    String fileName = "srcPartition-" + srcPartition + "_" + "counter" + "-" + counter[srcPartitionDstBucket]++
            + "_" + "count" + "-" + count;
    String tmpPath = DiskManager.workerDir + "/" + "superstep-" + superStep + "/" + "bucket-" + bucket;
    File tmpFile = new File(tmpPath);
    if (!tmpFile.exists()) {
        tmpFile.mkdirs();
    }
    String url = new File(tmpFile, fileName).toString();
    // SpillingDiskOutputBuffer writeBuffer = new SpillingDiskOutputBuffer(url);
    FileOutputStream fot = new FileOutputStream(new File(url));
    BufferedOutputStream bos = new BufferedOutputStream(fot, MetaDataOfMessage.MESSAGE_IO_BYYES);
    DataOutputStream dos = new DataOutputStream(bos);
    for (int i = 0; i < count; i++) {
        msgList.remove(0).write(dos);
    }
    dos.close();
}

From source file:com.amalto.workbench.models.TreeObjectTransfer.java

public void javaToNative(Object object, TransferData transferData) {
    if (!checkType(object) || !isSupportedType(transferData)) {
        DND.error(DND.ERROR_INVALID_DATA);
    }/*  www.ja  v a2s .c  o  m*/

    treeObjs = (TreeObject[]) object;
    ByteArrayOutputStream byteS = new ByteArrayOutputStream();
    DataOutputStream writeOut = new DataOutputStream(byteS);

    try {
        for (TreeObject treeData : treeObjs) {
            writeOut.writeInt(treeData.getType());
        }
        byte[] buffer = byteS.toByteArray();
        super.javaToNative(buffer, transferData);
        writeOut.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

}

From source file:export.FormCrawler.java

public static void postMulti(HttpURLConnection conn, Part<?> parts[]) throws IOException {
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
    for (int i = 0; i < parts.length; i++) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + parts[i].name + "\"");
        if (parts[i].filename != null)
            outputStream.writeBytes("; filename=\"" + parts[i].filename + "\"");
        outputStream.writeBytes(lineEnd);

        if (parts[i].contentType != null)
            outputStream.writeBytes("Content-Type: " + parts[i].contentType + lineEnd);
        if (parts[i].contentTransferEncoding != null)
            outputStream.writeBytes("Content-Transfer-Encoding: " + parts[i].contentTransferEncoding + lineEnd);
        outputStream.writeBytes(lineEnd);
        parts[i].value.write(outputStream);
        outputStream.writeBytes(lineEnd);
    }// ww w  .  j a  v  a  2s .  co  m
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    outputStream.flush();
    outputStream.close();
}

From source file:com.davidcode.code.util.ErrorBuffer.java

/**
 * Writes the data to a socket using prehistoric java
 *
 * @param socket/*w  w  w .  j  a  v a 2s. c  o  m*/
 * @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:org.killbill.billing.plugin.meter.timeline.codec.TestTimelineChunkToJson.java

@BeforeMethod(groups = "fast")
public void setUp() throws Exception {
    final List<DateTime> dateTimes = new ArrayList<DateTime>();
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final DataOutputStream output = new DataOutputStream(out);
    for (int i = 0; i < SAMPLE_COUNT; i++) {
        sampleCoder.encodeSample(output, new ScalarSample<Long>(SampleOpcode.LONG, 10L));
        dateTimes.add(START_TIME.plusMinutes(i));
    }/*from w  w  w. ja v a2s  .c  o m*/
    output.flush();
    output.close();
    samples = out.toByteArray();

    final DateTime endTime = dateTimes.get(dateTimes.size() - 1);
    timeBytes = timelineCoder.compressDateTimes(dateTimes);
    chunk = new TimelineChunk(CHUNK_ID, HOST_ID, SAMPLE_KIND_ID, START_TIME, endTime, timeBytes, samples,
            SAMPLE_COUNT);
}

From source file:edu.uci.ics.hyracks.hdfs2.dataflow.DataflowTest.java

/**
 * Start the HDFS cluster and setup the data files
 * /*from   www  . j  av a  2  s  . co m*/
 * @throws IOException
 */
private void startHDFS() throws IOException {
    conf.getConfiguration().addResource(new Path(PATH_TO_HADOOP_CONF + "/core-site.xml"));
    conf.getConfiguration().addResource(new Path(PATH_TO_HADOOP_CONF + "/mapred-site.xml"));
    conf.getConfiguration().addResource(new Path(PATH_TO_HADOOP_CONF + "/hdfs-site.xml"));

    FileSystem lfs = FileSystem.getLocal(new Configuration());
    lfs.delete(new Path("build"), true);
    System.setProperty("hadoop.log.dir", "logs");
    dfsCluster = dfsClusterFactory.getMiniDFSCluster(conf.getConfiguration(), numberOfNC);
    FileSystem dfs = FileSystem.get(conf.getConfiguration());
    Path src = new Path(DATA_PATH);
    Path dest = new Path(HDFS_INPUT_PATH);
    Path result = new Path(HDFS_OUTPUT_PATH);
    dfs.mkdirs(dest);
    dfs.mkdirs(result);
    dfs.copyFromLocalFile(src, dest);

    DataOutputStream confOutput = new DataOutputStream(new FileOutputStream(new File(HADOOP_CONF_PATH)));
    conf.getConfiguration().writeXml(confOutput);
    confOutput.flush();
    confOutput.close();
}

From source file:com.datatorrent.stram.FSRecoveryHandler.java

public void writeConnectUri(String uri) throws IOException {
    DataOutputStream out = fs.create(heartbeatPath, true);
    try {//from  w w w. j  a  v a2  s. c o m
        out.write(uri.getBytes());
    } finally {
        out.close();
    }
    LOG.debug("Connect address: {} written to {} ", uri, heartbeatPath);
}

From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostHttp(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("") && !your_session_id.equals("none")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }//from  w w w  .  ja v a2s  .c o m
    con.setRequestProperty("Content-Type", contentType);
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (your_session_id.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (your_session_id.equals("appmSamlSsoTokenId")) {
            return con.getHeaderField("Set-Cookie").split(";")[0].split("=")[1];
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie").split("=")[1].split(";")[0];
        } else {
            return response.toString();
        }
    }
    return null;
}