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: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);
    }/*from   w ww  .j  a  va 2 s  .co m*/
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    outputStream.flush();
    outputStream.close();
}

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

/**
 * 1. Sends data to service: console password | service password | service id
 *//*from   www  .j  av  a2  s.co  m*/
public void connect(Service service) {
    try {
        LOGGER.info("Connecting to service: " + service);
        Socket socket = new Socket(service.getHost(), service.getPort());
        socket.setSoTimeout(300);
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        out.writeBytes(service.getPassword() + "|" + service.getId() + "\r\n");
        String response = in.readLine();

        in.close();
        out.close();
        socket.close();

        LOGGER.info("Service response: " + response);

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

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  w w. j  a  v  a  2  s.  c om
 * @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:db.dao.ArticleDao.java

public void deletebyId(String deleteId) {
    try {/*from   w w  w  . ja va 2s.c o m*/
        String url = this.checkIfLocal("article/delete");
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) 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 = "id=" + URLEncoder.encode(deleteId);

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

        int responseCode = con.getResponseCode();

        //print result
        System.out.println(responseCode);

    } catch (MalformedURLException ex) {
        Logger.getLogger(ArticleDao.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ArticleDao.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.microsoft.azure.management.TestContainerService.java

private String getSshKey() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);//from   w w  w. j  av  a 2 s . co m
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(byteOs);
    dos.writeInt("ssh-rsa".getBytes().length);
    dos.write("ssh-rsa".getBytes());
    dos.writeInt(publicKey.getPublicExponent().toByteArray().length);
    dos.write(publicKey.getPublicExponent().toByteArray());
    dos.writeInt(publicKey.getModulus().toByteArray().length);
    dos.write(publicKey.getModulus().toByteArray());
    String publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray()));
    return "ssh-rsa " + publicKeyEncoded + " ";
}

From source file:com.proofpoint.zookeeper.io.TempLocalDirectory.java

public TempFileBackedOutputStream newTempFileBackedOutputStream(String destinationPath) throws IOException {
    final File tempFile = newFile();
    final File destinationFile = new File(destinationPath);
    final DataOutputStream tempFileOutputStream = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(tempFile)));

    return new TempFileBackedOutputStream() {
        @Override/*www. ja va  2 s .c  o m*/
        public DataOutputStream getStream() {
            return tempFileOutputStream;
        }

        @Override
        public void commit() throws IOException {
            close(true);
        }

        @Override
        public void release() throws IOException {
            close(false);
        }

        private void close(boolean upload) throws IOException {
            if (isOpen) {
                isOpen = false;

                tempFileOutputStream.close();
                if (upload) {
                    if (!tempFile.renameTo(destinationFile)) {
                        throw new IOException(
                                "Could not rename " + tempFile.getPath() + " to " + destinationFile.getPath());
                    }
                } else {
                    deleteFile(tempFile);
                }
            }
        }

        private boolean isOpen = true;
    };
}

From source file:com.anrisoftware.prefdialog.miscswing.docks.dockingframes.layoutsaver.SaveLayoutWorker.java

@Override
protected void process(List<OutputStream> chunks) {
    try {//from   w  ww  .  j a va 2  s  . co  m
        control.save(name);
        control.write(new DataOutputStream(outputStream));
        fireLayoutSaved();
    } catch (IOException e) {
        fireLayoutError(e);
    }
    synchronized (this) {
        notify();
    }
}

From source file:org.hyperic.lather.client.LatherHTTPClient.java

public LatherValue invoke(String method, LatherValue args) throws IOException, LatherRemoteException {
    ByteArrayOutputStream bOs = new ByteArrayOutputStream();
    DataOutputStream dOs = new DataOutputStream(bOs);

    this.xCoder.encode(args, dOs);

    byte[] rawData = bOs.toByteArray();
    String encodedArgs = Base64.encode(rawData);
    Map<String, String> postParams = new HashMap<String, String>();

    postParams.put("method", method);
    postParams.put("args", encodedArgs);
    postParams.put("argsClass", args.getClass().getName());

    HttpResponse response = client.post(baseURL, postParams);

    if ((response != null) && (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)) {
        ByteArrayInputStream bIs;
        DataInputStream dIs;//w w  w .ja v a 2  s . co m
        Header errHeader = response.getFirstHeader(HDR_ERROR);
        Header clsHeader = response.getFirstHeader(HDR_VALUECLASS);
        HttpEntity entity = response.getEntity();
        String responseBody = EntityUtils.toString(entity);

        if (errHeader != null) {
            throw new LatherRemoteException(responseBody);
        }

        if (clsHeader == null) {
            throw new IOException("Server returned malformed result: did not contain a value class header");
        }

        Class<?> resClass;

        try {
            resClass = Class.forName(clsHeader.getValue());
        } catch (ClassNotFoundException exc) {
            throw new LatherRemoteException("Server returned a class '" + clsHeader.getValue()
                    + "' which the client did not have access to");
        }

        try {
            bIs = new ByteArrayInputStream(Base64.decode(responseBody));
        } catch (IllegalArgumentException e) {
            throw new SystemException("could not decode response from server body=" + responseBody, e);
        }
        dIs = new DataInputStream(bIs);

        return this.xCoder.decode(dIs, resClass);
    } else {
        throw new IOException("Connection failure: " + response.getStatusLine());
    }
}

From source file:org.openxdata.server.servlet.WMDownloadServlet.java

private void downloadForms(HttpServletResponse response, int studyId) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    formDownloadService.downloadForms(studyId, dos, "", "");
    baos.flush();//w w  w .j a va 2s.co  m
    dos.flush();
    byte[] data = baos.toByteArray();
    baos.close();
    dos.close();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    PrintWriter out = response.getWriter();
    out.println("<study>");

    try {
        dis.readByte(); //reads the size of the studies

        while (true) {
            String value = dis.readUTF();
            out.println("<form>" + value + "</form>");
        }
    } catch (EOFException exe) {
        //exe.printStackTrace();
    }

    out.println("</study>");
    out.flush();
    dis.close();
}

From source file:org.fosstrak.ale.server.type.FileSubscriberOutputChannel.java

/**
 * This method writes ec reports to a file.
 * //w w  w.  ja v  a 2  s  .  c  o  m
 * @param reports to write to the file
 * @throws ImplementationException if an implementation exception occures
 */
private void writeNotificationToFile(ECReports reports) throws ImplementationException {
    // append reports as xml to file
    LOG.debug("Append reports '" + reports.getSpecName() + "' as xml to file '" + getPath() + "'.");

    File file = getFile();

    // create file if it does not already exists
    if (!file.exists() || !file.isFile()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            throw new ImplementationException("Could not create new file '" + getPath() + "'.", e);
        }
    }

    try {

        // open streams
        FileOutputStream fileOutputStream = new FileOutputStream(file, true);
        DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);

        // append reports as xml to file
        dataOutputStream.writeBytes(getPrettyXml(reports));
        dataOutputStream.writeBytes("\n\n");
        dataOutputStream.flush();

        // close streams
        dataOutputStream.close();
        fileOutputStream.close();

    } catch (IOException e) {
        throw new ImplementationException("Could not write to file '" + getPath() + "'.", e);
    }
}