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:db.dao.ArticleDao.java

public void deletebyId(String deleteId) {
    try {//w w w. ja v  a 2 s . c o  m
        String url = this.checkIfLocal("article/delete");
        URL obj = new URL(url);
        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 = "id=" + URLEncoder.encode(deleteId);

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();

        //print result
        System.out.println(responseCode);

    } catch (MalformedURLException ex) {
        Logger.getLogger(ArticleDao.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ArticleDao.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.example.jarida.http.AsyncConnection.java

@Override
public String doInBackground(String... params) {
    final String method = params[0];
    final String urlString = params[1];

    final StringBuilder builder = new StringBuilder();

    try {//from   w ww .j av  a 2  s . c o  m
        final URL url = new URL(urlString);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);

        if (method.equals(METHOD_POST)) {
            final String urlParams = params[2];
            conn.setRequestProperty(HTTP.CONTENT_LEN, "" + Integer.toString(urlParams.getBytes().length));
            System.out.println(urlParams);
            // Send request
            final DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(urlParams);
            wr.flush();
            wr.close();
        }

        // Get Response
        final InputStream is = conn.getInputStream();
        final BufferedReader rd = new BufferedReader(new InputStreamReader(is));

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

    return builder.toString();
}

From source file:com.noshufou.android.su.util.Util.java

public static VersionInfo getSuVersionInfo() {
    VersionInfo info = new VersionInfo();
    Process process = null;//ww w .j av a 2  s. c  om
    String inLine = null;

    try {
        process = Runtime.getRuntime().exec("sh");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        BufferedReader is = new BufferedReader(
                new InputStreamReader(new DataInputStream(process.getInputStream())), 64);
        os.writeBytes("su -v\n");

        // We have to hold up the thread to make sure that we're ready to read
        // the stream, using increments of 5ms makes it return as quick as
        // possible, and limiting to 1000ms makes sure that it doesn't hang for
        // too long if there's a problem.
        for (int i = 0; i < 400; i++) {
            if (is.ready()) {
                break;
            }
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                Log.w(TAG, "Sleep timer got interrupted...");
            }
        }
        if (is.ready()) {
            inLine = is.readLine();
            if (inLine != null) {
                info.version = inLine;
            }
        } else {
            // If 'su -v' isn't supported, neither is 'su -V'. return legacy info
            os.writeBytes("exit\n");
            info.version = "legacy";
            info.versionCode = 0;
            return info;
        }

        os.writeBytes("su -v\n");

        // We have to hold up the thread to make sure that we're ready to read
        // the stream, using increments of 5ms makes it return as quick as
        // possible, and limiting to 1000ms makes sure that it doesn't hang for
        // too long if there's a problem.
        for (int i = 0; i < 400; i++) {
            if (is.ready()) {
                break;
            }
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                Log.w(TAG, "Sleep timer got interrupted...");
            }
        }
        if (is.ready()) {
            inLine = is.readLine();
            if (inLine != null && Integer.parseInt(inLine.substring(0, 1)) > 2) {
                inLine = null;
                os.writeBytes("su -V\n");
                inLine = is.readLine();
                if (inLine != null) {
                    info.versionCode = Integer.parseInt(inLine);
                }
            } else {
                info.versionCode = 0;
            }
        } else {
            os.writeBytes("exit\n");
        }
    } catch (IOException e) {
        Log.e(TAG, "Problems reading current version.", e);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return info;
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

/** returns an oauth token for the user's CSE. returns null if login failed. */
public static String authenticate(String login, String password) {
    //System.out.println("About to post\nURL: "+target+ "content: " + content);
    String authToken = null;//from   www.ja  va2 s  .c o m
    String response = "";
    try {
        URL url = new URL("https://www.google.com/accounts/ClientLogin");
        URLConnection conn = url.openConnection();
        // Set connection parameters.
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        // Make server believe we are form data...

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        // TODO: escape password, we'll fail if password has &
        // login = "musetestlogin1";
        // password = "whowonthelottery";
        String content = "accountType=HOSTED_OR_GOOGLE&Email=" + login + "&Passwd=" + password
                + "&service=cprose&source=muse.chrome.extension";
        out.writeBytes(content);
        out.flush();
        out.close();

        // Read response from the input stream.
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String temp;
        while ((temp = in.readLine()) != null) {
            response += temp + "\n";
        }
        temp = null;
        in.close();
        log.info("Obtaining auth token: Server response:\n'" + response + "'");

        String delimiter = "Auth=";
        /* given string will be split by the argument delimiter provided. */
        String[] token = response.split(delimiter);
        authToken = token[1];
        authToken = authToken.trim();
        authToken = authToken.replaceAll("(\\r|\\n)", "");
        log.info("auth token: " + authToken);
        return authToken;
    } catch (Exception e) {
        log.warn("Unable to authorize: " + e.getMessage());
        return null;
    }
}

From source file:lk.appzone.client.MchoiceAventuraSmsSender.java

private void sendRequest(String urlParameters, HttpURLConnection connection) throws IOException {

    if (logger.isDebugEnabled()) {
        logger.debug("sending the request: " + urlParameters);
    }// w ww  . j  a  v  a 2  s.co m
    //Send request
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
}

From source file:com.acc.util.InstagramClient.java

public String getProfilePicOfUser(final String code) {

    String profilePic = null;/* ww w .j  a  va  2s  .com*/
    //      final String inputJson = "client_id=e580d04d0687403189f86d49545b69a4&client_secret=a2943297f601402d894f8d21400bdfd5&grant_type=authorization_code&redirect_uri=http://electronics.local:9001/yacceleratorstorefront/electronics/en/facerecognitionpage&code="
    //            + code;

    //String inputJson1 = "{\"Identities\": [{\"Score\": \"99.99986\",\"IdentityDetails\": {\"BiographicData\": [{\"Key\": \"Name\",\"Value\": \"Ravi\"},{\"Key\": \"ID\",\"Value\": \"DRIVING_LICENSE_ID\"}],\"BiometricDatas\": [{\"Base64Data\": \"/9j/4AAQSkZJ\",\"Modality\": \"Face_Face2D\",\"Type\": \"Image\"}],\"IdentityId\": \"BiometricDev[1:S:58840];\"}}],\"InWatchList\": false}";
    //      System.out.println(inputJson);

    // Make Web Service Call

    //      final Client client = ClientBuilder.newClient();
    //      final String instagramOutputJson = client.target("https://api.instagram.com/oauth/access_token").request()
    //            .method("POST", Entity.entity(inputJson, MediaType.APPLICATION_JSON), String.class);

    try {
        final URL url = new URL("https://api.instagram.com/oauth/access_token");
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        final String urlParameters = "client_id=e580d04d0687403189f86d49545b69a4"
                + "&client_secret=a2943297f601402d894f8d21400bdfd5" + "&grant_type=authorization_code"
                + "&redirect_uri=http://electronics.local:9001/yacceleratorstorefront/electronics/en/facerecognitionpage"
                + "&code=" + code;

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        final DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        final BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        System.out.println(result.toString());
        System.out.println("Output Json from Instagram is " + result);
        profilePic = processJson(result.toString());
    } catch (final MalformedURLException e) {
        // YTODO Auto-generated catch block
        e.printStackTrace();
    } catch (final IOException e) {
        // YTODO Auto-generated catch block
        e.printStackTrace();
    }
    return profilePic;

}

From source file:org.apache.oodt.cas.wmservices.client.WmServicesClient.java

private String query(String method, String op, Object... args) {
    String url = this.serverurl + this.service + op;
    try {//from w  w w  .j  a va  2s .  c  o m
        String params = "";
        for (int i = 0; i < args.length; i += 2) {
            if (i > 0)
                params += "&";
            params += args[i] + "=" + URLEncoder.encode(args[i + 1].toString(), "UTF-8");
        }
        if ("GET".equals(method)) {
            URL urlobj = new URL(url + "?" + params);
            return IOUtils.toString(urlobj.openStream());
        } else {
            URL urlobj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) urlobj.openConnection();
            con.setRequestMethod(method);
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();

            String result = IOUtils.toString(con.getInputStream());
            con.disconnect();
            return result;
        }

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

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

/**
 * Launch tests /*from   ww w .j  a  v a2 s . com*/
 * @param conf Configuration of the mapreduce job.
 * @param inDir input path
 * @param outDir output path
 * @param input Input text
 * @throws IOException
 */
public void launchTest(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);
    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(MapClass.class);
    conf.setReducerClass(IdentityReducer.class);
    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);

    // Launch job with default option for temp dir. 
    // i.e. temp dir is ./tmp 
    JobClient.runJob(conf);
    outFs.delete(outDir, true);

    // Launch job by giving relative path to temp dir.
    conf.set("mapred.child.tmp", "../temp");
    JobClient.runJob(conf);
    outFs.delete(outDir, true);

    // Launch job by giving absolute path to temp dir
    conf.set("mapred.child.tmp", "/tmp");
    JobClient.runJob(conf);
    outFs.delete(outDir, true);
}

From source file:com.juhnowski.sanskrvar.Main.java

public Entry checkWord(String word) {
    StringBuilder sb = new StringBuilder();
    sb.append("http://www.sanskrit-lexicon.uni-koeln.de/scans/WILScan/2014/web/webtc/getword.php?key=");
    sb.append(word);//from  w  w  w. j  a  v  a  2 s. c o  m
    sb.append("&filter=roman&noLit=off&transLit=hk");
    String targetURL = sb.toString();
    String urlParameters = "";

    HttpURLConnection connection = null;

    try {
        //Create connection
        URL url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/xhr");

        connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.close();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        String s = response.toString();
        if (!s.contains("<h2>not found:")) {
            return new Entry(word, s);
        } else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:junit.org.rapidpm.microservice.demo.ServletTest.java

@Test
public void testServletPostRequest() throws Exception {
    URL obj = new URL(url);
    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 = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);/*w w  w .  j a v  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
    Assert.assertEquals("Hello World CDI Service", response.toString());

}