Example usage for java.io DataOutputStream close

List of usage examples for java.io DataOutputStream close

Introduction

In this page you can find the example usage for java.io DataOutputStream close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

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

public String getProfilePicOfUser(final String code) {

    String profilePic = null;/*  w ww.  jav a2s  . c  o  m*/
    //      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: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);//from   ww  w.  j a v  a2s. c  om
    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());

}

From source file:org.wisdom.openid.connect.service.internal.DefaultIssuer.java

@Override
public TokenResponse authorizationToken(final String redirectUrl, final String code) throws IOException {

    StringBuilder sb = new StringBuilder();
    sb.append("grant_type=authorization_code");
    sb.append(format("&code=%s", code));
    sb.append(format("&client_id=%s", clientId));
    sb.append(format("&client_secret=%s", clientSecret));
    sb.append(format("&redirect_uri=%s", redirectUrl));

    String parameters = sb.toString();

    URL tokenEndpoint = new URL(config.getTokenEndpoint());
    HttpURLConnection connection = (HttpURLConnection) tokenEndpoint.openConnection();
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //connection.addRequestProperty("Authorization", format("Basic %s", credentials()));
    connection.setRequestProperty("Content-Length", valueOf(parameters.getBytes().length));

    connection.setUseCaches(false);//from   ww  w . ja  v  a  2 s .  co  m
    connection.setDoInput(true);
    connection.setDoOutput(true);

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

    //Get Response
    return buildTokenResponse(connection.getInputStream());
}

From source file:net.mms_projects.copy_it.server.push.android.GCMRunnable.java

public void run() {
    try {// w ww  . j  av a2 s .  co  m
        URL url = new URL(GCM_URL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(POST);
        conn.setRequestProperty(CONTENT_TYPE, Page.ContentTypes.JSON_TYPE);
        conn.setRequestProperty(AUTHORIZATION, KEY);
        final String output_json = full.toString();
        System.err.println("Input json: " + output_json);
        conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(output_json.length()));
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream outputstream = new DataOutputStream(conn.getOutputStream());
        outputstream.writeBytes(output_json);
        outputstream.close();
        DataInputStream input = new DataInputStream(conn.getInputStream());
        StringBuilder builder = new StringBuilder(input.available());
        for (int c = input.read(); c != -1; c = input.read())
            builder.append((char) c);
        input.close();
        output = new JSONObject(builder.toString());
        System.err.println("Output json: " + output.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cloudera.recordbreaker.analyzer.UnknownTextSchemaDescriptor.java

public byte[] getPayload() {
    // Serialize the parser, return the resulting string
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);
    try {/*from   w w w. ja  v  a2  s .  c o  m*/
        this.typeTree.write(out);
        out.close();
    } catch (IOException iex) {
        return new byte[0];
    } finally {
    }
    return baos.toByteArray();
}

From source file:Main.java

public static void writeSettings(String file, Object... objs) throws IOException {
    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file), 1024));
    try {//from   ww w . java2 s .c o m
        out.writeInt(objs.length);
        for (Object obj : objs) {
            char cl;
            if (obj instanceof Byte) {
                cl = 'Y';
            } else {
                cl = obj.getClass().getSimpleName().charAt(0);
            }

            out.writeChar(cl);
            if (obj instanceof String) {
                out.writeUTF((String) obj);
            } else if (obj instanceof Float) {
                out.writeFloat((Float) obj);
            } else if (obj instanceof Double) {
                out.writeDouble((Double) obj);
            } else if (obj instanceof Integer) {
                out.writeInt((Integer) obj);
            } else if (obj instanceof Long) {
                out.writeLong((Long) obj);
            } else if (obj instanceof Boolean) {
                out.writeBoolean((Boolean) obj);
            } else {
                throw new IllegalStateException("Unsupported type");
            }
        }
    } finally {
        out.close();
    }
}

From source file:com.snaker.ocr.TesseractOCR.java

@Override
public String recognize(byte[] image) throws OCRException {
    if (tessExecutable == null) {
        tessExecutable = getDefaultTessExecutable();
    }// w ww.  j a  v  a  2  s .c o m

    File source = null;
    File dest = null;
    try {
        String prefix = System.nanoTime() + "";
        source = File.createTempFile(prefix, ".jpg");
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(source));
        dos.write(image);
        dos.flush();
        dos.close();
        String sourceFileName = source.getAbsolutePath();
        Process p = Runtime.getRuntime().exec(String.format("%s %s %s -l eng nobatch digits", tessExecutable,
                sourceFileName, sourceFileName));
        String destFileName = sourceFileName + ".txt";
        dest = new File(destFileName);
        int result = p.waitFor();
        if (result == 0) {
            BufferedReader in = new BufferedReader(new FileReader(dest));
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = in.readLine()) != null) {
                sb.append(str).append("\n");
            }
            in.close();
            return sb.toString().trim();
        } else {
            String msg;
            switch (result) {
            case 1:
                msg = "Errors accessing files. There may be spaces in your image's filename.";
                break;
            case 29:
                msg = "Cannot recognize the image or its selected region.";
                break;
            case 31:
                msg = "Unsupported image format.";
                break;
            default:
                msg = "Errors occurred.";
            }
            throw new OCRException(msg);
        }
    } catch (IOException e) {
        throw new OCRException("recognize failed", e);
    } catch (InterruptedException e) {
        logger.error("interrupted", e);
    } finally {
        if (source != null) {
            source.delete();
        }
        if (dest != null) {
            dest.delete();
        }
    }
    return null;
}

From source file:KMeansNDimension.java

private static void solutionWriter(DataSet<Tuple2<Integer, DenseVector>> res) {
    File tT = new File("/Kmeans_results.csv");
    DataOutputStream wTT = null;
    try {/* www  .  j  a  v  a2 s . co  m*/
        wTT = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tT)));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        List<Tuple2<Integer, DenseVector>> tuples = res.collect();

        for (Tuple2<Integer, DenseVector> t : tuples) {
            try {
                wTT.writeChars((double) t.f0 + ","
                        + t.f1.toString().replace("DenseVector", "").replace("(", "").replace(")", "").trim()
                        + "\n");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        wTT.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //System.out.println(id+","+maxDensity+","+vector.toString());
}

From source file:com.base2.kagura.core.authentication.RestAuthentication.java

public InputStream httpPost(String suffix, HashMap<String, String> values) {
    try {//  www  .  j  a v  a  2s .c  om
        URL obj = new URL(url + "/" + suffix);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("POST");

        String data = new ObjectMapper().writeValueAsString(values);

        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(data);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        if (responseCode != 200)
            throw new Exception("Got error code: " + responseCode);
        return con.getInputStream();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:edu.isi.wings.util.oodt.CurationServiceAPI.java

private String query(String method, String op, Object... args) {
    String url = this.curatorurl + this.service + op;
    try {//  w  ww .j  a va  2  s.  c o m
        String params = "policy=" + URLEncoder.encode(this.policy, "UTF-8");
        for (int i = 0; i < args.length; i += 2) {
            params += "&" + args[i] + "=" + URLEncoder.encode(args[i + 1].toString(), "UTF-8");
        }

        URL urlobj = new URL(url);
        if ("GET".equals(method))
            urlobj = new URL(url + "?" + params);
        HttpURLConnection con = (HttpURLConnection) urlobj.openConnection();
        con.setRequestMethod(method);
        if (!"GET".equals(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;
}