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:net.pms.util.OpenSubtitle.java

public static String postPage(URLConnection connection, String query) throws IOException {
    connection.setDoOutput(true);/*from  w  ww  . j  a v  a 2  s . c  o  m*/
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setDefaultUseCaches(false);
    connection.setRequestProperty("Content-Type", "text/xml");
    connection.setRequestProperty("Content-Length", "" + query.length());
    ((HttpURLConnection) connection).setRequestMethod("POST");
    //LOGGER.debug("opensub query "+query);
    // open up the output stream of the connection
    if (!StringUtils.isEmpty(query)) {
        try (DataOutputStream output = new DataOutputStream(connection.getOutputStream())) {
            output.writeBytes(query);
            output.flush();
        }
    }

    StringBuilder page;
    try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        page = new StringBuilder();
        String str;
        while ((str = in.readLine()) != null) {
            page.append(str.trim());
            page.append("\n");
        }
    }
    //LOGGER.debug("opensubs result page "+page.toString());
    return page.toString();
}

From source file:org.nd4j.linalg.api.test.NDArrayTests.java

@Test
public void testReadWrite() throws Exception {
    Nd4j.dtype = DataBuffer.FLOAT;
    INDArray write = Nd4j.linspace(1, 4, 4);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    Nd4j.write(write, dos);/*from  w  w w .  ja v a  2s  . co m*/

    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    DataInputStream dis = new DataInputStream(bis);
    INDArray read = Nd4j.read(dis);
    assertEquals(write, read);

}

From source file:com.skcraft.launcher.util.HttpRequest.java

/**
 * Execute the request.//w  w w .  jav  a2  s .co m
 * <p/>
 * After execution, {@link #close()} should be called.
 *
 * @return this object
 * @throws java.io.IOException on I/O error
 */
public HttpRequest execute() throws IOException {
    boolean successful = false;

    try {
        if (conn != null) {
            throw new IllegalArgumentException("Connection already executed");
        }

        conn = (HttpURLConnection) reformat(url).openConnection();
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Java) SKMCLauncher");

        if (body != null) {
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Content-Length", Integer.toString(body.length));
            conn.setDoInput(true);
        }

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setReadTimeout(READ_TIMEOUT);

        conn.connect();

        if (body != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(body);
            out.flush();
            out.close();
        }

        inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? conn.getInputStream()
                : conn.getErrorStream();

        successful = true;
    } finally {
        if (!successful) {
            close();
        }
    }

    return this;
}

From source file:com.example.gemswin.screancasttest.SenderAsyncTask.java

@Override
protected Void doInBackground(Void... params) {

    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    //String portget = MainActivity.portString;

    List<NameValuePair> params1 = new ArrayList<NameValuePair>();
    params1.add(new BasicNameValuePair("class", pref.getclass()));

    String url = "http://176.32.230.250/anshuli.com/ScreenCast/getIPs.php";

    json = jparser.makeHttpRequest(url, "POST", params1);

    try {//  w w w . j  a v  a2  s .co  m
        // Checking for SUCCESS TAG

        //forjson.clear();

        String heading = "";
        String message = "";
        //Toast.makeText(MainActivity.this, (CharSequence) json, 1).show();
        ipArray = new ArrayList<String>();

        JSONArray account = json.getJSONArray("IPs");
        for (int i = 0; i < account.length(); i++) {
            json = account.getJSONObject(i);

            String IpString = json.getString("IP");

            if (!IpString.equals("0.0.0.0"))
                ipArray.add(IpString);
            // forjson.add(Roll+"-"+ NAME);
            //categories_description.add(description);

        }

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

    int port = Integer.parseInt(pref.getSerialNo());

    java.net.Socket socket = null;

    //   ip.add("192.168.15.105");
    //   ip.add("192.168.15.103");
    int len = ipArray.size();
    /*   try {
    for(int i=0;i<ip.size();i++)
    socket[i] = new java.net.Socket(ip.get(i),port);
       //   socket1 = new java.net.Socket("192.168.15.105", port);
     // connect to server
       } catch (IOException e) {
    e.printStackTrace();
       }*/
    dataOut = new DataOutputStream[len];
    try {
        for (int i = 0; i < len; i++) {
            socket = new java.net.Socket(ipArray.get(i), port);
            dataOut[i] = new DataOutputStream(socket.getOutputStream());
        }

        //   dataOut1 = new DataOutputStream(socket1.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }

    while (!isCancelled()) {

        VideoChunk chunk = null;
        try {
            //Log.d(LOG_TAG, "waiting for data to send");
            chunk = mVideoChunks.takeLast();
            //Log.d(LOG_TAG,"got data. writing to socket");
            int length = chunk.getData().length;
            for (int i = 0; i < ipArray.size(); i++) {

                dataOut[i].writeInt(length);
                dataOut[i].writeInt(chunk.getFlags());
                dataOut[i].writeLong(chunk.getTimeUs());
                dataOut[i].write(chunk.getData());
                dataOut[i].flush();

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            continue;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    return null;
}

From source file:net.sf.jabref.logic.net.URLDownload.java

private URLConnection openConnection() throws IOException {
    URLConnection connection = source.openConnection();
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
    }//from ww  w.  j  a  v a  2  s.  c  om
    if (!postData.isEmpty()) {
        connection.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.writeBytes(postData);
        }

    }
    // this does network i/o: GET + read returned headers
    connection.connect();

    return connection;
}

From source file:net.sheehantech.cherry.ProtocolTest.java

private byte[] expected(byte command, byte[] token, byte[] payload) {
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    DataOutputStream dataStream = new DataOutputStream(byteStream);
    try {//from   w  w  w  .java2s  .c  o  m
        dataStream.writeByte(command);
        dataStream.writeShort(token.length);
        dataStream.write(token);
        dataStream.writeShort(payload.length);
        dataStream.write(payload);
        return (byteStream.toByteArray());
    } catch (final IOException e) {
        throw new AssertionError();
    }
}

From source file:com.synapticpath.pisecure.modules.LogglyEventLoggerModule.java

private void logEvent(SystemEvent event) {

    try {/*from  www.  ja  v a 2  s  .co  m*/
        byte[] postData = event.toJson().getBytes(StandardCharsets.UTF_8);

        int postDataLength = postData.length;
        URL url = new URL(String.format(postRequestUrl, token, tag));

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        conn.setUseCaches(false);
        try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
            wr.write(postData);
        }

        if (conn.getResponseCode() == 200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }

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

From source file:TaxSvc.TaxSvc.java

public CancelTaxResult CancelTax(CancelTaxRequest req) {

    //Create URL/*from   w w w . j  a  v  a  2s .c  om*/
    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:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;/*from   www .j  a v a 2 s .c o m*/
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));

        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);

        InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));

        in = new BufferedReader(new InputStreamReader(stream));
    } else {
        URL obj = new URL(SingleDataHolder.getInstance().hostAdress);
        HttpURLConnection con = (HttpURLConnection) 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 = "apideskviewer.getAllLessons={}";

        // Send post request
        con.setDoOutput(true);
        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 : " + SingleDataHolder.getInstance().hostAdress);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }

    JSONParser parser = new JSONParser();
    try {
        Object parsedResponse = parser.parse(in);

        JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

        for (int i = 0; i < jsonParsedResponse.size(); i++) {
            String s = (String) jsonParsedResponse.get(String.valueOf(i));
            String[] splittedPath = s.split("/");
            DateFormat DF = new SimpleDateFormat("yyyyMMdd");
            Date d = DF.parse(splittedPath[1].replaceAll(".bin", ""));
            Lesson lesson = new Lesson(splittedPath[0], d, false);
            String group = splittedPath[0];
            String date = new SimpleDateFormat("dd.MM.yyyy").format(d);

            if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) {
                comboGroups.addItem(group);
            }
            if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) {
                comboDates.addItem(date);
            }
            tableModel.addLesson(lesson);
        }
    } catch (Exception ex) {
    }
}

From source file:com.microsoft.speech.tts.Authentication.java

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;//  ww  w.  ja  va 2  s . c  o m
    HttpsURLConnection webRequest = null;

    this.accessToken = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("Ocp-Apim-Subscription-Key", apiKey);
        webRequest.setRequestMethod("POST");

        String request = "";
        byte[] bytes = request.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        this.accessToken = strBuffer.toString();

    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}