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:edu.pdx.cecs.orcycle.Uploader.java

private boolean uploadOneSegment(long currentNoteId) {
    boolean result = false;
    final String postUrl = mCtx.getResources().getString(R.string.post_url);

    try {/*from  w  ww .j ava 2 s  . com*/
        URL url = new URL(postUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Cycleatl-Protocol-Version", "4");

        SegmentData segmentData = SegmentData.fetchSegment(mCtx, currentNoteId);
        JSONObject json = segmentData.getJSON();
        String deviceId = userId;

        DataOutputStream stream = new DataOutputStream(conn.getOutputStream());
        stream.writeBytes(makeContentField("ratesegment", json.toString()));
        stream.writeBytes(makeContentField("version", String.valueOf(kSaveNoteProtocolVersion)));
        stream.writeBytes(makeContentField("device", deviceId));
        stream.writeBytes(contentFieldPrefix);
        stream.flush();
        stream.close();

        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();
        Log.v(MODULE_TAG, "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
        if (serverResponseCode == 201 || serverResponseCode == 202) {
            segmentData.updateSegmentStatus(SegmentData.STATUS_SENT);
            result = true;
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }
    return result;
}

From source file:org.apache.abdera.protocol.client.util.MultipartRelatedRequestEntity.java

private void writeInput(DataOutputStream out) throws IOException {
    if (contentType == null) {
        throw new NullPointerException("media content type can't be null");
    }//from w w w .ja  v  a  2s .c  o  m
    out.writeBytes("content-type: " + contentType + "\r\n");

    String contentId = entry.getContentSrc().toString();
    if (!contentId.matches("cid:.+")) {
        throw new IllegalArgumentException("entry content source is not a correct content-ID");
    }
    out.writeBytes("content-id: <" + contentId.substring(4) + ">\r\n\r\n");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while (input.read(buffer) != -1) {
        output.write(buffer);
    }

    Base64 base64 = new Base64();
    out.write(base64.encode(output.toByteArray()));
    out.writeBytes("\r\n" + "--" + boundary + "--");
}

From source file:admincommands.Unishell.java

@Override
public void executeCommand(Player admin, String[] params) {
    if (admin.getAccessLevel() < 3) {
        PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
        return;// w  w w  .  j  a v a 2 s  .co  m
    }

    if (params.length < 2) {
        PacketSendUtility.sendMessage(admin, "Syntax: //unishell <useradd|show> <values...>");
        PacketSendUtility.sendMessage(admin, "//unishell useradd username password");
        PacketSendUtility.sendMessage(admin, "//unishell show users");
        return;
    }

    if (params[0].equals("adduser")) {
        if (params.length < 3) {
            PacketSendUtility.sendMessage(admin, "Syntax; //unishell useradd username password");
            return;
        }

        String username = params[1];
        String password = params[2];
        String hashedPassword = CryptoHelper.encodeSHA1(password);

        Map<String, String> actualAuthorizedKeys = AuthorizedKeys.loadAuthorizedKeys();
        Iterator<Entry<String, String>> actualAuthorizedEntries = actualAuthorizedKeys.entrySet().iterator();
        boolean checkResult = false;
        while (actualAuthorizedEntries.hasNext()) {
            if (username.equals(actualAuthorizedEntries.next().getKey())) {
                checkResult = true;
            }
        }

        if (checkResult) {
            PacketSendUtility.sendMessage(admin, "Error: username already exists.");
            return;
        }

        try {
            FileOutputStream file = new FileOutputStream("./config/network/unishell.passwd", true);
            DataOutputStream out = new DataOutputStream(file);
            out.writeBytes(username + ":" + hashedPassword + "\n");
            out.flush();
            out.close();
            PacketSendUtility.sendMessage(admin, "Unishell user '" + username + "' successfully added !");
            return;
        } catch (FileNotFoundException fnfe) {
            log.error("Cannot open unishell password file for writing at ./config/network/unishell.passwd",
                    fnfe);
            PacketSendUtility.sendMessage(admin, "Error: cannot open password file.");
            return;
        } catch (IOException ioe) {
            log.error("Cannot write to unishell password file for writing at ./config/network/unishell.passwd",
                    ioe);
            PacketSendUtility.sendMessage(admin, "Error: cannot write to password file.");
            return;
        }

    } else if (params[0].equals("show")) {
        if (params.length < 2) {
            PacketSendUtility.sendMessage(admin, "Syntax: //unishell show users");
            return;
        }

        if (params[1].equals("users")) {
            Iterator<Entry<String, String>> authorizedKeys = AuthorizedKeys.loadAuthorizedKeys().entrySet()
                    .iterator();
            while (authorizedKeys.hasNext()) {
                Entry<String, String> current = authorizedKeys.next();
                PacketSendUtility.sendMessage(admin,
                        "user: " + current.getKey() + " | password: " + current.getValue());
            }
        }

    } else {
        PacketSendUtility.sendMessage(admin, "Syntax: //unishell <useradd|> <values...>");
        PacketSendUtility.sendMessage(admin, "//unishell useradd username password");
        return;
    }

}

From source file:org.apache.hadoop.mapred.TestMiniCoronaTaskFail.java

public JobClient prepareJob(JobConf conf, Path inDir, Path outDir, String input) throws IOException {
    // set up the input file system and write input text.
    FileSystem inFs = inDir.getFileSystem(conf);
    FileSystem outFs = outDir.getFileSystem(conf);
    outFs.delete(outDir, true);//  w w  w  .  jav  a  2s. com
    if (!inFs.mkdirs(inDir)) {
        throw new IOException("Mkdirs failed to create " + inDir.toString());
    }
    {
        // write input into input file
        DataOutputStream file = inFs.create(new Path(inDir, "part-0"));
        file.writeBytes(input);
        file.close();
    }

    // configure the mapred Job
    conf.setMapperClass(MapperClass.class);
    conf.setReducerClass(IdentityReducer.class);
    conf.setNumReduceTasks(0);
    FileInputFormat.setInputPaths(conf, inDir);
    FileOutputFormat.setOutputPath(conf, outDir);
    conf.setSpeculativeExecution(false);
    String TEST_ROOT_DIR = new Path(System.getProperty("test.build.data", "/tmp")).toString().replace(' ', '+');
    conf.set("test.build.data", TEST_ROOT_DIR);
    // return the RunningJob handle.
    return new JobClient(conf);
}

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

/**
 * This method writes ec reports to a file.
 * //  ww  w  .j  ava 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);
    }
}

From source file:TaxSvc.TaxSvc.java

public CancelTaxResult CancelTax(CancelTaxRequest req) {

    //Create URL/*  w  w  w  .j a v  a  2 s  . c  o m*/
    String taxget = svcURL + "/1.0/tax/cancel";
    URL url;
    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);         //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

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

        conn.disconnect();

        if (conn.getResponseCode() != 200) //Note: tax/cancel will return a 200 response even if the document could not be cancelled. Special attention needs to be paid to the ResultCode.
        { //If we got a more serious error, print out the error message.
            CancelTaxResult res = mapper.readValue(conn.getErrorStream(), CancelTaxResult.class); //Deserialize response
            return res;
        } else {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            CancelTaxResponse res = mapper.readValue(conn.getInputStream(), CancelTaxResponse.class); //Deserialize response
            return res.CancelTaxResult;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:org.jongo.mocks.JongoClient.java

private JongoResponse doRequest(final String url, final List<NameValuePair> parameters) {
    final String urlParameters = URLEncodedUtils.format(parameters, "UTF-8");
    JongoResponse response = null;/*w ww  . j a  v a 2s  .  co m*/

    try {
        HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept", MediaType.APPLICATION_XML);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        con.setDoOutput(true);
        con.setDoInput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        BufferedReader r = null;
        if (con.getResponseCode() != Response.Status.CREATED.getStatusCode()) {
            r = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        } else {
            r = new BufferedReader(new InputStreamReader(con.getInputStream()));
        }

        StringBuilder rawresponse = new StringBuilder();
        String strLine = null;
        while ((strLine = r.readLine()) != null) {
            rawresponse.append(strLine);
            rawresponse.append("\n");
        }

        try {
            response = XmlXstreamTest.successFromXML(rawresponse.toString());
        } catch (Exception e) {
            response = XmlXstreamTest.errorFromXML(rawresponse.toString());
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return response;

}

From source file:com.QuarkLabs.BTCeClientJavaFX.networking.AuthRequest.java

public JSONObject makeRequest(String method, Map<String, String> arguments)
        throws UnsupportedEncodingException {
    if (method == null) {
        return null;
    }/*from w w w  . j  av a2 s.co m*/
    if (arguments == null) {
        arguments = new HashMap<>();
    }
    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = (Map.Entry<String, String>) it.next();
        if (postData.length() > 0) {
            postData += "&";
        }
        postData += ent.getKey() + "=" + ent.getValue();
    }
    try {
        _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512");
    } catch (UnsupportedEncodingException uee) {
        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    try {
        mac = Mac.getInstance("HmacSHA512");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    try {
        mac.init(_key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }
    StringBuilder out = new StringBuilder();
    try {
        HttpURLConnection urlConnection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        urlConnection.setRequestProperty("Key", key);
        String sign = byteArrayToHexString(mac.doFinal(postData.getBytes("UTF-8")));
        urlConnection.setRequestProperty("Sign", sign);
        urlConnection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.close();
        if (urlConnection.getResponseCode() == 200) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;

            while ((line = rd.readLine()) != null) {
                out.append(line);
            }
            rd.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return new JSONObject(out.toString());
}

From source file:org.jongo.mocks.JongoClient.java

private JongoResponse doRequest(final String url, final String method, final String jsonParameters) {
    JongoResponse response = null;//  w w  w. ja  v a 2  s.c o m

    try {
        HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection();
        con.setRequestMethod(method);
        con.setRequestProperty("Accept", MediaType.APPLICATION_XML);
        con.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
        con.setRequestProperty("Content-Length", "" + Integer.toString(jsonParameters.getBytes().length));
        con.setDoOutput(true);
        con.setDoInput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonParameters);
        wr.flush();
        wr.close();

        //            BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream()));

        BufferedReader r = null;
        if (con.getResponseCode() != Response.Status.OK.getStatusCode()
                && con.getResponseCode() != Response.Status.CREATED.getStatusCode()) {
            r = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        } else {
            r = new BufferedReader(new InputStreamReader(con.getInputStream()));
        }

        StringBuilder rawresponse = new StringBuilder();
        String strLine = null;
        while ((strLine = r.readLine()) != null) {
            rawresponse.append(strLine);
            rawresponse.append("\n");
        }

        try {
            response = XmlXstreamTest.successFromXML(rawresponse.toString());
        } catch (Exception e) {
            response = XmlXstreamTest.errorFromXML(rawresponse.toString());
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return response;
}

From source file:com.phearom.um.model.RemoteJSONSource.java

private JSONObject sendPost(String urlString) throws Exception {
    URL url = new URL(urlString);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

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

    Map<String, String> params = new HashMap<>();
    params.put("limit", "25");
    params.put("offset", "0");

    String parameter = params.toString().replace(",", "&");

    // Send post request
    con.setDoOutput(true);//from   w  w  w .java  2  s .  c o m
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(parameter);
    wr.flush();
    wr.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

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

    return new JSONObject(response.toString());
}