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:tachyon.master.DependencyIntegrationTest.java

@Test
public void writeImageTest() throws IOException {
    // create the dependency, output streams, and associated objects
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(os);
    ObjectMapper mapper = JsonObject.createObjectMapper();
    ObjectWriter writer = mapper.writer();

    String cmd = "java test.jar $master:$port";
    List<Integer> parents = new ArrayList<Integer>();
    List<Integer> children = new ArrayList<Integer>();
    List<ByteBuffer> data = new ArrayList<ByteBuffer>();
    Collection<Integer> parentDependencies = new ArrayList<Integer>();
    Dependency dep = new Dependency(0, parents, children, cmd, data, "Dependency Test", "Tachyon Tests", "0.4",
            DependencyType.Narrow, parentDependencies, 0L, mMasterTachyonConf);

    // write the image
    dep.writeImage(writer, dos);//from  ww w  .j  a v a2 s.  co m

    // decode the written bytes
    ImageElement decoded = mapper.readValue(os.toByteArray(), ImageElement.class);
    TypeReference<List<Integer>> intListRef = new TypeReference<List<Integer>>() {
    };
    TypeReference<DependencyType> depTypeRef = new TypeReference<DependencyType>() {
    };
    TypeReference<List<ByteBuffer>> byteListRef = new TypeReference<List<ByteBuffer>>() {
    };

    // test the decoded ImageElement
    // can't use equals(decoded) because ImageElement doesn't have an equals method and can have
    // variable fields
    Assert.assertEquals(0, decoded.getInt("depID").intValue());
    Assert.assertEquals(parents, decoded.get("parentFiles", intListRef));
    Assert.assertEquals(children, decoded.get("childrenFiles", intListRef));
    Assert.assertEquals(data, decoded.get("data", byteListRef));
    Assert.assertEquals(parentDependencies, decoded.get("parentDeps", intListRef));
    Assert.assertEquals(cmd, decoded.getString("commandPrefix"));
    Assert.assertEquals("Dependency Test", decoded.getString("comment"));
    Assert.assertEquals("Tachyon Tests", decoded.getString("framework"));
    Assert.assertEquals("0.4", decoded.getString("frameworkVersion"));
    Assert.assertEquals(DependencyType.Narrow, decoded.get("depType", depTypeRef));
    Assert.assertEquals(0L, decoded.getLong("creationTimeMs").longValue());
    Assert.assertEquals(dep.getUncheckpointedChildrenFiles(),
            decoded.get("unCheckpointedChildrenFiles", intListRef));
}

From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java

public String getAuthToken(String apiEndPoint, String encodedCliAndSecret) {

    //receives : apiEndPoint (https://api.test.sabre.com)
    //encodedCliAndSecret : base64Encode(  base64Encode(V1:[user]:[group]:[domain]) + ":" + base64Encode([secret]) )
    String strRet = null;//from   w w  w. j av  a 2s . c  o  m

    try {

        URL urlConn = new URL(apiEndPoint + "/v1/auth/token");
        URLConnection conn = urlConn.openConnection();

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

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Authorization", "Basic " + encodedCliAndSecret);
        conn.setRequestProperty("Accept", "application/json");

        //send request
        DataOutputStream dataOut = new DataOutputStream(conn.getOutputStream());
        dataOut.writeBytes("grant_type=client_credentials");
        dataOut.flush();
        dataOut.close();

        //get response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String strChunk = "";
        StringBuilder sb = new StringBuilder();
        while (null != ((strChunk = rd.readLine())))
            sb.append(strChunk);

        //parse the token
        JSONObject respParser = new JSONObject(sb.toString());
        strRet = respParser.getString("access_token");

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return strRet;

}

From source file:mitm.common.security.crypto.PBEncryptedStreamParameters.java

/**
 * Returns the encoded form of PBEncryptionParameters.
 *//*  w  ww . j a v  a 2 s  . com*/
public byte[] getEncoded() throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    DataOutputStream out = new DataOutputStream(bos);

    out.writeLong(serialVersionUID);

    out.writeUTF(algorithm);
    out.writeInt(salt.length);
    out.write(salt);

    out.writeInt(iterationCount);

    return bos.toByteArray();
}

From source file:moodle.android.moodle.helpers.MoodleWebService.java

private JSONObject getWebServiceResponse(String serverurl, String functionName, String urlParameters,
        int xslRawId) {
    JSONObject jsonobj = null;/* w ww  . ja va2  s  . com*/

    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:com.krawler.esp.utils.HttpPost.java

public static String GetResponse(String postdata) {
    try {/*from   w  w w .j a  v  a2 s .c  om*/
        String s = URLEncoder.encode(postdata, "UTF-8");
        // URL u = new URL("http://google.com");
        URL u = new URL("http://localhost:7070/service/soap/");
        URLConnection uc = u.openConnection();
        uc.setDoOutput(true);
        uc.setDoInput(true);
        uc.setAllowUserInteraction(false);

        DataOutputStream dstream = new DataOutputStream(uc.getOutputStream());

        // The POST line
        dstream.writeBytes(s);
        dstream.close();

        // Read Response
        InputStream in = uc.getInputStream();
        int x;
        while ((x = in.read()) != -1) {
            System.out.write(x);
        }
        in.close();

        BufferedReader r = new BufferedReader(new InputStreamReader(in));
        StringBuffer buf = new StringBuffer();
        String line;
        while ((line = r.readLine()) != null) {
            buf.append(line);
        }
        return buf.toString();
    } catch (Exception e) {
        // throw e;
        return e.toString();
    }
}

From source file:com.uber.hoodie.common.BloomFilter.java

/**
 * Serialize the bloom filter as a string.
 *//* w  w w.  j  a v  a2  s  . c o  m*/
public String serializeToString() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    try {
        filter.write(dos);
        byte[] bytes = baos.toByteArray();
        dos.close();
        return DatatypeConverter.printBase64Binary(bytes);
    } catch (IOException e) {
        throw new HoodieIndexException("Could not serialize BloomFilter instance", e);
    }
}

From source file:MethodHashing.java

public static long constructorHash(Constructor method) throws Exception {
    Class[] parameterTypes = method.getParameterTypes();
    String methodDesc = method.getName() + "(";
    for (int j = 0; j < parameterTypes.length; j++) {
        methodDesc += getTypeString(parameterTypes[j]);
    }/*ww  w .  j  av a  2 s.c o m*/
    methodDesc += ")";

    long hash = 0;
    ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512);
    MessageDigest messagedigest = MessageDigest.getInstance("SHA");
    DataOutputStream dataoutputstream = new DataOutputStream(
            new DigestOutputStream(bytearrayoutputstream, messagedigest));
    dataoutputstream.writeUTF(methodDesc);
    dataoutputstream.flush();
    byte abyte0[] = messagedigest.digest();
    for (int j = 0; j < Math.min(8, abyte0.length); j++)
        hash += (long) (abyte0[j] & 0xff) << j * 8;
    return hash;
}

From source file:HttpPOSTMIDlet.java

private String requestUsingGET(String URLString) throws IOException {
    HttpConnection hpc = null;// w  w w  .ja  va2 s .c  om
    DataInputStream dis = null;
    DataOutputStream dos = null;

    boolean newline = false;
    String content = "";
    try {
        hpc = (HttpConnection) Connector.open(defaultURL);
        hpc.setRequestMethod(HttpConnection.POST);
        hpc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
        hpc.setRequestProperty("Content-Language", "zh-tw");
        hpc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        hpc.setRequestProperty("Content-Length", String.valueOf(URLString.length()));

        dos = new DataOutputStream(hpc.openOutputStream());
        dos.write(URLString.getBytes());
        dos.flush();

        InputStreamReader xdis = new InputStreamReader(hpc.openInputStream());

        int character;
        while ((character = xdis.read()) != -1) {
            if ((char) character == '\\') {
                newline = true;
                continue;
            } else {
                if ((char) character == 'n' && newline) {
                    content += "\n";
                    newline = false;
                } else if (newline) {
                    content += "\\" + (char) character;
                    newline = false;
                } else {
                    content += (char) character;
                    newline = false;
                }
            }

        }
        if (hpc != null)
            hpc.close();
        if (dis != null)
            dis.close();
    } catch (IOException e2) {
    }

    return content;
}

From source file:com.lightboxtechnologies.spectrum.MRCoffeeClient.java

public void open(File pipe) throws IOException {
    sock.connect(new AFUNIXSocketAddress(pipe));
    in = new DataInputStream(sock.getInputStream());
    out = new DataOutputStream(sock.getOutputStream());
}

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

public String doPostHttps(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }//  w ww  .j  a  v a2s  .  co  m
    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 (your_session_id.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

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