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:com.amazon.pay.impl.Util.java

/**
 * This method uses HttpURLConnection instance to make requests.
 *
 * @param method The HTTP method (GET,POST,PUT,etc.).
 * @param url The URL//from  ww  w.j a va  2  s  .c  o m
 * @param urlParameters URL Parameters
 * @param headers Header key-value pairs
 * @return ResponseData
 * @throws IOException
 */
public static ResponseData httpSendRequest(String method, String url, String urlParameters,
        Map<String, String> headers) throws IOException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    if (headers != null && !headers.isEmpty()) {
        for (String key : headers.keySet()) {
            con.setRequestProperty(key, headers.get(key));
        }
    }
    con.setDoOutput(true);
    con.setRequestMethod(method);
    if (urlParameters != null) {
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
    }
    int responseCode = con.getResponseCode();

    BufferedReader in;
    if (responseCode != 200) {
        in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
    } else {
        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine).append(LINE_SEPARATOR);
    }
    in.close();
    return new ResponseData(responseCode, response.toString());
}

From source file:net.mybox.mybox.ServerClientConnection.java

public ServerClientConnection(Server _server, Socket _socket) {

    server = _server;//from   w  ww. j a va  2  s .co  m
    socket = _socket;
    handle = socket.getPort();

    try {
        inStream = socket.getInputStream();
        outStream = socket.getOutputStream();
    } catch (Exception e) {
        System.out.println("Error setting socket streams");
    }

    dataInStream = new DataInputStream(inStream);
    dataOutStream = new DataOutputStream(outStream);

    // load the sqlite-JDBC driver using the current class loader
    try {
        Class.forName("org.sqlite.JDBC");
        System.out.println(String.format("SQLiteJDBC is running in %s mode",
                org.sqlite.SQLiteJDBCLoader.isNativeMode() ? "OS native" : "pure-java"));
    } catch (Exception e) {
        System.out.println("Unable to load sqlite driver " + e.getMessage());
        System.exit(1);
    }
    startServerInputListenerThread();

}

From source file:edu.harvard.iq.dvn.unf.Base64Encoding.java

/**
 *
 * @param digest byte array/*www .  j a v  a2 s .  c  o  m*/
 * @param enc String with final encoding
 * @return String the encoded base64 of digest
 * @throws UnsupportedEncodingException
 */
public static String tobase64(byte[] digest, String enc) throws UnsupportedEncodingException {

    ByteArrayOutputStream btstream = new ByteArrayOutputStream();
    //this make sure is written in big-endian

    DataOutputStream stream = new DataOutputStream(btstream);

    byte[] tobase64 = null;
    byte[] revdigest = new byte[digest.length];
    revdigest = changeByteOrder(digest, ByteOrder.nativeOrder());
    try {

        stream.write(revdigest);
        stream.flush();

        tobase64 = Base64.encodeBase64(btstream.toByteArray());

    } catch (IOException io) {
        tobase64 = Base64.encodeBase64(digest);
    }

    return new String(tobase64, enc);
}

From source file:org.killbill.billing.plugin.meter.timeline.codec.TestTimelineChunkToJson.java

@BeforeMethod(groups = "fast")
public void setUp() throws Exception {
    final List<DateTime> dateTimes = new ArrayList<DateTime>();
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final DataOutputStream output = new DataOutputStream(out);
    for (int i = 0; i < SAMPLE_COUNT; i++) {
        sampleCoder.encodeSample(output, new ScalarSample<Long>(SampleOpcode.LONG, 10L));
        dateTimes.add(START_TIME.plusMinutes(i));
    }/*from   ww  w.  j  ava2 s. c o m*/
    output.flush();
    output.close();
    samples = out.toByteArray();

    final DateTime endTime = dateTimes.get(dateTimes.size() - 1);
    timeBytes = timelineCoder.compressDateTimes(dateTimes);
    chunk = new TimelineChunk(CHUNK_ID, HOST_ID, SAMPLE_KIND_ID, START_TIME, endTime, timeBytes, samples,
            SAMPLE_COUNT);
}

From source file:com.fullhousedev.globalchat.bukkit.PluginMessageManager.java

public static void userToggleMessage(String username, boolean on, Plugin pl) {
    try {//from  w w w  .j av  a  2s. c  o  m
        ByteArrayOutputStream customData = new ByteArrayOutputStream();
        DataOutputStream outCustom = new DataOutputStream(customData);
        outCustom.writeUTF(username);
        outCustom.writeBoolean(on);

        sendRawMessage("togglemsg", "ALL", customData.toByteArray(), pl);
    } catch (IOException ex) {
        Logger.getLogger(GlobalChat.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ReadWriteStreams.java

public void writeStream(String[] sData, boolean[] bData, int[] iData) {
    try {// w ww .  jav a 2  s  .  c  o  m
        // Write data into an internal byte array
        ByteArrayOutputStream strmBytes = new ByteArrayOutputStream();

        // Write Java data types into the above byte array
        DataOutputStream strmDataType = new DataOutputStream(strmBytes);

        byte[] record;

        for (int i = 0; i < sData.length; i++) {
            // Write Java data types      
            strmDataType.writeUTF(sData[i]);
            strmDataType.writeBoolean(bData[i]);
            strmDataType.writeInt(iData[i]);

            // Clear any buffered data
            strmDataType.flush();

            // Get stream data into byte array and write record
            record = strmBytes.toByteArray();
            rs.addRecord(record, 0, record.length);

            // Toss any data in the internal array so writes 
            // starts at beginning (of the internal array)
            strmBytes.reset();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}

From source file:com.threeti.proxy.RequestFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String path = request.getServletPath();
    String pathInfo = path.substring(path.lastIndexOf("/"));

    if (pathInfo == null) {
        response.getWriter().write("error");
    } else {//from ww w  .  jav a  2  s.  co m
        if (path.contains("/proxy")) {
            pathInfo = path.substring(path.lastIndexOf("/proxy") + 6);
            if ("POST".equals(request.getMethod())) { // POST
                String urlString = this.baseURL + pathInfo;
                logger.info(urlString);
                String s = this.getParams(req).substring(0, this.getParams(req).length() - 1);
                byte[] data = s.getBytes("utf-8");
                HttpURLConnection conn = null;
                DataOutputStream outStream = null;
                URL httpUrl = new URL(urlString);
                conn = (HttpURLConnection) httpUrl.openConnection();
                conn.setConnectTimeout(7000);
                conn.setReadTimeout(7000);
                conn.setUseCaches(false);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Charset", "utf-8");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(data.length));
                outStream = new DataOutputStream(conn.getOutputStream());
                outStream.write(data);
                outStream.flush();
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    IOUtils.copy(in, response.getOutputStream());
                } else {
                    try {
                        throw new Exception("ResponseCode=" + conn.getResponseCode());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else if ("DELETE".equals(request.getMethod())) {
                String urlString = this.baseURL + pathInfo + "?" + this.getParams(req);
                logger.info(urlString);
                HttpURLConnection conn = null;
                URL url = new URL(urlString);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(7000);
                conn.setReadTimeout(7000);
                conn.setUseCaches(false);
                conn.setDoOutput(true);
                conn.setRequestMethod("DELETE");
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    IOUtils.copy(in, response.getOutputStream());
                } else {
                    try {
                        throw new Exception("ResponseCode=" + conn.getResponseCode());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                String urlString = this.baseURL + pathInfo + "?" + this.getParams(req);
                logger.info(urlString);
                URL url = new URL(urlString);
                InputStream input = url.openStream();
                IOUtils.copy(input, response.getOutputStream());
            }
        } else {
            chain.doFilter(req, res);
        }
    }
}

From source file:net.mohatu.bloocoin.miner.SubmitListClass.java

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {// ww w .j a  v a 2  s .  c o  m
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + MainView.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result += inputLine;
            }

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                MainView.updateStatusText(solution + " submitted");
                Thread gc = new Thread(new CoinClass());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                MainView.updateStatusText("Submission of " + solution + " failed, already exists!");
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            MainView.updateStatusText("Submission of " + solution + " failed, connection failed!");
        } catch (IOException e) {
            MainView.updateStatusText("Submission of " + solution + " failed, connection failed!");
        }
    }
    Thread gc = new Thread(new CoinClass());
    gc.start();
}

From source file:com.facebook.infrastructure.db.RowMutation.java

public Message makeRowMutationMessage(String verbHandlerName) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    serializer().serialize(this, dos);
    EndPoint local = StorageService.getLocalStorageEndPoint();
    EndPoint from = (local != null) ? local : new EndPoint(FBUtilities.getHostName(), 7000);
    Message message = new Message(from, StorageService.mutationStage_, verbHandlerName, bos.toByteArray());
    return message;
}

From source file:com.cloudera.seismic.segy.SegyUnloader.java

@Override
public int run(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("input", true, "SU sequence files to export from Hadoop");
    options.addOption("output", true, "The local SU file to write");

    // Parse the commandline and check for required arguments.
    CommandLine cmdLine = new PosixParser().parse(options, args, false);
    if (!cmdLine.hasOption("input") || !cmdLine.hasOption("output")) {
        System.out.println("Mising required input/output arguments");
        new HelpFormatter().printHelp("SegyUnloader", options);
        System.exit(1);//from  w  ww  .  j  ava2s  .c o  m
    }

    Configuration conf = getConf();
    FileSystem hdfs = FileSystem.get(conf);
    Path inputPath = new Path(cmdLine.getOptionValue("input"));
    if (!hdfs.exists(inputPath)) {
        System.out.println("Input path does not exist");
        System.exit(1);
    }

    PathFilter pf = new PathFilter() {
        @Override
        public boolean accept(Path path) {
            return !path.getName().startsWith("_");
        }
    };

    DataOutputStream os = new DataOutputStream(new FileOutputStream(cmdLine.getOptionValue("output")));
    for (FileStatus fs : hdfs.listStatus(inputPath, pf)) {
        write(fs.getPath(), os, conf);
    }
    os.close();

    return 0;
}