Example usage for java.io DataOutputStream writeBytes

List of usage examples for java.io DataOutputStream writeBytes

Introduction

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

Prototype

public final void writeBytes(String s) throws IOException 

Source Link

Document

Writes out the string to the underlying output stream as a sequence of bytes.

Usage

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   w w  w .  j  a v a2 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:org.uma.jmetal.util.experiment.component.GenerateFriedmanTestTables.java

/**
 * Write the file contents in the output file
 * @param indicator/* w  w  w  .  ja va2s  .  c  o  m*/
 * @param fileContents
 */
private void writeLatexFile(GenericIndicator<?> indicator, String fileContents) {
    String outputFile = latexDirectoryName + "/FriedmanTest" + indicator.getName() + ".tex";

    try {
        File latexOutput;
        latexOutput = new File(latexDirectoryName);
        if (!latexOutput.exists()) {
            latexOutput.mkdirs();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);

        dataOutputStream.writeBytes(fileContents);

        dataOutputStream.close();
        fileOutputStream.close();
    } catch (IOException e) {
        throw new JMetalException("Error writing data ", e);
    }
}

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

public void logCommit(String file) throws IOException {
    Path log = commitPath(getTaskId());
    if (debug) {//  w  w  w  .j a  va  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:edu.ku.brc.specify.toycode.ResFileCompare.java

/**
 * Save as Ascii.//from  ww w.  j  av  a 2  s .c  o  m
 */
public boolean save(final File file, final Vector<String> list) {
    FileOutputStream fos = null;
    DataOutputStream dos = null;

    try {
        fos = new FileOutputStream(file);
        dos = new DataOutputStream(fos);

        for (String line : list) {
            String str = line + '\n';
            dos.writeBytes(str);
        }
        dos.flush();
        dos.close();
        return true;

    } catch (Exception e) {
        System.out.println("e: " + e);
    }
    return false;
}

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 ww  . j av a2  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:de.ingrid.iplug.csw.dsc.cswclient.impl.XMLPostRequest.java

/**
 * Send the given request to the server.
 * @param serverURL/* w  ww. java  2 s .  c o m*/
 * @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:com.Candy.center.AboutCandy.java

private void getLogs(String command) {
    try {/*from ww w.j  a  va2 s  . c o  m*/
        Process process = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(command);
        os.writeBytes("exit\n");
        os.flush();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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);//from w w  w.  j av a2 s .c  om
    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:com.mendhak.gpslogger.senders.googledrive.GoogleDriveJob.java

private String createEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) {

    String fileId = null;//from  www .  ja v  a 2s  . c om
    HttpURLConnection conn = null;

    String createFileUrl = "https://www.googleapis.com/drive/v2/files";

    String createFilePayload = "   {\n" + "             \"title\": \"" + fileName + "\",\n"
            + "             \"mimeType\": \"" + mimeType + "\",\n" + "             \"parents\": [\n"
            + "              {\n" + "               \"id\": \"" + parentFolderId + "\"\n" + "              }\n"
            + "             ]\n" + "            }";

    try {

        URL url = new URL(createFileUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/json");

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

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

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(createFilePayload);
        wr.flush();
        wr.close();

        fileId = null;

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

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        LOG.debug("File created with ID " + fileId + " of type " + mimeType);

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

    }

    return fileId;
}

From source file:honeypot.services.WepawetServiceImpl.java

/**
 * {@inheritDoc}/* ww 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);
    }

}