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.dagobert_engine.core.service.MtGoxApiAdapter.java

/**
 * Queries the mtgox api with params//from   w  w  w. java 2  s. c  o  m
 * 
 * @param url
 * @return
 */
public String query(String path, HashMap<String, String> args) {

    final String publicKey = mtGoxConfig.getMtGoxPublicKey();
    final String privateKey = mtGoxConfig.getMtGoxPrivateKey();

    if (publicKey == null || privateKey == null || "".equals(publicKey) || "".equals(privateKey)) {
        throw new ApiKeysNotSetException(
                "Either public or private key of MtGox are not set. Please set them up in src/main/resources/META-INF/seam-beans.xml");
    }

    // Create nonce
    final String nonce = String.valueOf(System.currentTimeMillis()) + "000";

    HttpsURLConnection connection = null;
    String answer = null;
    try {
        // add nonce and build arg list
        args.put(ARG_KEY_NONCE, nonce);
        String post_data = buildQueryString(args);

        String hash_data = path + "\0" + post_data; // Should be correct

        // args signature with apache cryptografic tools
        String signature = signRequest(mtGoxConfig.getMtGoxPrivateKey(), hash_data);

        // build URL
        URL queryUrl = new URL(Constants.API_BASE_URL + path);
        // create and setup a HTTP connection
        connection = (HttpsURLConnection) queryUrl.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty(REQ_PROP_USER_AGENT, com.dagobert_engine.core.util.Constants.APP_NAME);
        connection.setRequestProperty(REQ_PROP_REST_KEY, mtGoxConfig.getMtGoxPublicKey());
        connection.setRequestProperty(REQ_PROP_REST_SIGN, signature.replaceAll("\n", ""));

        connection.setDoOutput(true);
        connection.setDoInput(true);

        // Read the response

        DataOutputStream os = new DataOutputStream(connection.getOutputStream());
        os.writeBytes(post_data);
        os.close();

        BufferedReader br = null;

        // Any error?
        int code = connection.getResponseCode();
        if (code >= 400) {
            // get error stream
            br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));

            answer = toString(br);
            logger.severe("HTTP Error on queryin " + path + ": " + code + ", answer: " + answer);
            throw new MtGoxConnectionError(code, answer);

        } else {
            // get normal stream
            br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
            answer = toString(br);

        }
    } catch (UnknownHostException exc) {
        throw new MtGoxConnectionError("Could not connect to MtGox. Please check your internet connection. ("
                + exc.getClass().getName() + ")");
    } catch (IllegalStateException ex) {
        throw new MtGoxConnectionError(ex);
    } catch (IOException ex) {
        throw new MtGoxConnectionError(ex);
    } finally {

        if (connection != null)
            connection.disconnect();
        connection = null;
    }

    return answer;
}

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

private void configure(JobConf conf, Path inDir, Path outDir, String input, Class<? extends Mapper> map,
        Class<? extends Reducer> reduce) 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  . ja va2s .c  o  m
    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 which creates a tempfile in map.
    conf.setJobName("testmap");
    conf.setMapperClass(map);
    conf.setReducerClass(reduce);
    conf.setNumMapTasks(1);
    conf.setNumReduceTasks(0);
    FileInputFormat.setInputPaths(conf, inDir);
    FileOutputFormat.setOutputPath(conf, outDir);
    String TEST_ROOT_DIR = new Path(System.getProperty("test.build.data", "/tmp")).toString().replace(' ', '+');
    conf.set("test.build.data", TEST_ROOT_DIR);
}

From source file:org.cablelabs.widevine.keyreq.KeyRequest.java

/**
 * Perform the key request./* w  w w .  j  av a  2  s.  c  o m*/
 * 
 * @return the response message
 */
public ResponseMessage requestKeys() {

    int i;

    Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    Gson prettyGson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create();

    // Create request object
    RequestMessage requestMessage = new RequestMessage();
    requestMessage.content_id = Base64.encodeBase64String(content_id.getBytes());
    requestMessage.policy = POLICY;
    requestMessage.client_id = CLIENT_ID;
    requestMessage.drm_types = DRM_TYPES;

    // Add the track requests to the message
    requestMessage.tracks = new RequestMessage.Track[tracks.size()];
    i = 0;
    for (Track t : tracks) {
        RequestMessage.Track track = new RequestMessage.Track();
        track.type = t.type;
        requestMessage.tracks[i++] = track;
    }

    // Rolling keys
    if (rollingKeyCount != -1 && rollingKeyStart != -1) {
        requestMessage.crypto_period_count = rollingKeyCount;
        requestMessage.first_crypto_period_index = rollingKeyStart;
    }

    // Convert request message to JSON and base64 encode
    String jsonRequestMessage = gson.toJson(requestMessage);
    System.out.println("Request Message:");
    System.out.println(prettyGson.toJson(requestMessage));

    // Create request JSON
    Request request = new Request();
    request.request = Base64.encodeBase64String(jsonRequestMessage.getBytes());

    String serverURL = null;
    if (sign_request) {
        // Create message signature
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(jsonRequestMessage.getBytes());
            byte[] sha1_b = sha1.digest();
            System.out.println("SHA-1 hash of JSON request message = 0x" + Hex.encodeHexString(sha1_b));

            // Use AES/CBC/PKCS5Padding with CableLabs Key and InitVector
            SecretKeySpec keySpec = new SecretKeySpec(sign_key, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(sign_iv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            // Encrypt the SHA-1 hash of our request message
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] encrypted = cipher.doFinal(sha1_b);
            System.out
                    .println("AES/CBC/PKCS5Padding Encrypted SHA1-hash = 0x" + Hex.encodeHexString(encrypted));

            request.signer = provider;
            request.signature = Base64.encodeBase64String(encrypted);

            serverURL = license_url;
        } catch (Exception e) {
            System.out.println("Error performing message encryption!  Message = " + e.getMessage());
            System.exit(1);
        }
    } else {
        request.signer = TEST_PROVIDER;
        serverURL = TEST_SERVER_URL;
    }

    String jsonRequest = gson.toJson(request);
    System.out.println("Request:");
    System.out.println(prettyGson.toJson(request));

    String jsonResponseStr = null;
    try {

        // Create URL connection
        URL url = new URL(serverURL);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setDoOutput(true);

        System.out.println("Sending HTTP POST to " + serverURL);

        // Write POST data
        DataOutputStream out = new DataOutputStream(con.getOutputStream());
        out.writeBytes(jsonRequest);
        out.flush();
        out.close();

        // Wait for response
        int responseCode = con.getResponseCode();
        System.out.println("Received response code -- " + responseCode);

        // Read response data
        DataInputStream dis = new DataInputStream(con.getInputStream());
        int bytesRead;
        byte responseData[] = new byte[1024];
        StringBuffer sb = new StringBuffer();
        while ((bytesRead = dis.read(responseData)) != -1) {
            sb.append(new String(responseData, 0, bytesRead));
        }
        jsonResponseStr = sb.toString();
    } catch (Exception e) {
        System.err.println("Error in HTTP communication! -- " + e.getMessage());
        System.exit(1);
    }

    Response response = gson.fromJson(jsonResponseStr, Response.class);
    System.out.println("Response:");
    System.out.println(prettyGson.toJson(response));

    String responseMessageStr = new String(Base64.decodeBase64(response.response));
    ResponseMessage responseMessage = gson.fromJson(responseMessageStr, ResponseMessage.class);
    System.out.println("ResponseMessage:");
    System.out.println(prettyGson.toJson(responseMessage));

    return responseMessage;
}

From source file:com.photon.phresco.plugin.commons.PluginUtils.java

private void writeXml(String encrStr, String fileName) throws PhrescoException {
    DataOutputStream dos = null;
    FileOutputStream fos = null;/*w w  w.j  a v  a2 s.c o m*/
    try {
        fos = new FileOutputStream(fileName);
        dos = new DataOutputStream(fos);
        dos.writeBytes(encrStr);
    } catch (FileNotFoundException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } finally {
        try {
            if (dos != null) {
                dos.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            throw new PhrescoException(e);
        }
    }
}

From source file:org.apache.hadoop.hdfs.TestLease.java

@Test
public void testLease() throws Exception {
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
    try {//w ww.ja  v  a2  s .  c  o  m
        FileSystem fs = cluster.getFileSystem();
        Assert.assertTrue(fs.mkdirs(dir));

        Path a = new Path(dir, "a");
        Path b = new Path(dir, "b");

        DataOutputStream a_out = fs.create(a);
        a_out.writeBytes("something");

        Assert.assertTrue(hasLease(cluster, a));
        Assert.assertTrue(!hasLease(cluster, b));

        DataOutputStream b_out = fs.create(b);
        b_out.writeBytes("something");

        Assert.assertTrue(hasLease(cluster, a));
        Assert.assertTrue(hasLease(cluster, b));

        a_out.close();
        b_out.close();

        Assert.assertTrue(!hasLease(cluster, a));
        Assert.assertTrue(!hasLease(cluster, b));

        fs.delete(dir, true);
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:org.openhim.mediator.denormalization.ATNAAuditingActor.java

private void sendUsingTCP(final MediatorSocketRequest request) throws IOException {
    final Socket socket = getSocket(request);

    ExecutionContext ec = getContext().dispatcher();
    Future<Boolean> f = future(new Callable<Boolean>() {
        public Boolean call() throws IOException {
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            out.writeBytes(request.getBody());
            return Boolean.TRUE;
        }/*from   ww  w .j a  va  2s . c  o  m*/
    }, ec);
    f.onComplete(new OnComplete<Boolean>() {
        @Override
        public void onComplete(Throwable ex, Boolean result) throws Throwable {
            IOUtils.closeQuietly(socket);

            if (ex != null) {
                log.error(ex, "Exception during TCP send");
            }
        }
    }, ec);
}

From source file:org.apache.synapse.message.custom.processor.impl.BlockingTCPMsgSender.java

public String send(Endpoint endpoint, MessageContext synapseInMsgCtx) throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Start Sending the Message ");
    }//from   w  w w.j  a v  a2  s  .  com

    AbstractEndpoint abstractEndpoint = (AbstractEndpoint) endpoint;
    if (!abstractEndpoint.isLeafEndpoint()) {
        handleException("Endpoint Type not supported");
    }
    abstractEndpoint.executeEpTypeSpecificFunctions(synapseInMsgCtx);
    EndpointDefinition endpointDefinition = abstractEndpoint.getDefinition();

    org.apache.axis2.context.MessageContext axisInMsgCtx = ((Axis2MessageContext) synapseInMsgCtx)
            .getAxis2MessageContext();

    String endpointReferenceValue = null;
    if (endpointDefinition.getAddress() != null) {
        endpointReferenceValue = endpointDefinition.getAddress();
    } else if (axisInMsgCtx.getTo() != null) {
        endpointReferenceValue = axisInMsgCtx.getTo().getAddress();
    } else {
        handleException("Service url, Endpoint or 'To' header is required");
    }

    Options clientOptions;
    if (initClientOptions) {
        clientOptions = new Options();
    } else {
        clientOptions = axisInMsgCtx.getOptions();
    }
    // Fill Client options
    BlockingMsgSenderUtils.fillClientOptions(endpointDefinition, clientOptions, synapseInMsgCtx);

    // Invoke
    String clientIp = endpointReferenceValue.substring(6).split(":")[0];
    int clientPort = Integer.parseInt(endpointReferenceValue.substring(6).split(":")[1]);

    Socket clientSocket = new Socket(clientIp, clientPort);
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
    String message = synapseInMsgCtx.getProperty("updateInfoMessage").toString();
    boolean isOutOnly = isOutOnly(synapseInMsgCtx);
    try {
        if (isOutOnly) {
            outToServer.writeBytes(message + '\n');
            clientSocket.close();
            return "true";
        } else {
            BufferedReader inFromServer = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));
            String responseMessage = inFromServer.readLine();
            log.info("FROM SERVER: " + responseMessage);
            clientSocket.close();
            return responseMessage;
        }
    } catch (Exception ex) {
        handleException(
                "Error sending Message to url : " + ((AbstractEndpoint) endpoint).getDefinition().getAddress(),
                ex);
    }

    return null;
}

From source file:httpRequests.GetPost.java

private 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   ww w.j  av a 2 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:com.reddit.util.ApiUtil.java

/**
 * Experimental right now.  I messed around with this but never really used it for anything.
 * /* w  w  w  .ja  v  a 2 s  .  c o  m*/
 * @param url should be new URL("https://ssl.reddit.com/api/login/myusername");
 * @param user
 * @param pw
 * @throws IOException
 * @throws JSONException
 */
public void login(URL url, String user, String pw) throws IOException, JSONException {

    String data = "api_type=json&user=" + user + "&passwd=" + pw;
    HttpURLConnection httpUrlConn = null;
    httpUrlConn = (HttpURLConnection) url.openConnection();
    httpUrlConn.setRequestMethod("POST");
    httpUrlConn.setDoOutput(true);
    httpUrlConn.setUseCaches(false);
    httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    httpUrlConn.setRequestProperty("Content-Length", String.valueOf(data.length()));

    DataOutputStream dataOutputStream = new DataOutputStream(httpUrlConn.getOutputStream());
    dataOutputStream.writeBytes(data);
    dataOutputStream.flush();
    dataOutputStream.close();
    InputStream is = httpUrlConn.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuffer response = new StringBuffer();
    while ((line = bufferedReader.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    for (Entry<String, List<String>> r : httpUrlConn.getHeaderFields().entrySet()) {
        System.out.println(r.getKey() + ": " + r.getValue());
    }
    bufferedReader.close();
    System.out.println("Response: " + response.toString());
    this.setModHash(new JSONObject(response.toString()).getJSONObject("json").getJSONObject("data")
            .getString("modhash"));
    this.setCookie(new JSONObject(response.toString()).getJSONObject("json").getJSONObject("data")
            .getString("cookie"));

}

From source file:com.stratuscom.harvester.codebase.ClassServer.java

private void writeHeader(DataOutputStream out, byte[] bytes) throws IOException {
    out.writeBytes("HTTP/1.0 200 OK\r\n");
    out.writeBytes("Content-Length: " + bytes.length + "\r\n");
    out.writeBytes("Content-Type: application/java\r\n\r\n");
}