Example usage for java.io DataOutputStream flush

List of usage examples for java.io DataOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this data output stream.

Usage

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 w  w .jav a2  s.co  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;
}

From source file:com.googlecode.fascinator.portal.quartz.ExternalJob.java

/**
 * The real work happens here/*from  w  ww  .j a v a2 s. c  o  m*/
 *
 */
private void runJob() {
    HttpURLConnection conn = null;
    log.debug("Job firing: '{}'", name);

    try {
        // Open tasks... much simpler
        if (token == null) {
            conn = (HttpURLConnection) url.openConnection();

            // Secure tasks
        } else {
            String param = "token=" + URLEncoder.encode(token, "UTF-8");

            // Prepare our request
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", "" + Integer.toString(param.getBytes().length));
            conn.setUseCaches(false);
            conn.setDoOutput(true);

            // Send request
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(param);
            wr.flush();
            wr.close();
        }

        // Get Response
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            log.error("Error hitting external script: {}", conn.getResponseMessage());
        }
    } catch (IOException ex) {
        log.error("Error connecting to URL: ", ex);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

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

@Override
public String recognize(byte[] image) throws OCRException {
    if (tessExecutable == null) {
        tessExecutable = getDefaultTessExecutable();
    }//from  www .j  a va 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:com.base2.kagura.core.authentication.RestAuthentication.java

public InputStream httpPost(String suffix, HashMap<String, String> values) {
    try {//  w  w  w.  j  a v a  2s . c  o m
        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:net.namecoin.NameCoinI2PResolver.HttpSession.java

public String executePost(String postdata) throws HttpSessionException {
    URL url;//  w w  w  .  java2  s. co  m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(this.uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
        connection.setRequestProperty("User-Agent", "java");

        if (!this.user.isEmpty() && !this.password.isEmpty()) {
            String authString = this.user + ":" + this.password;
            String authStringEnc = Base64.encodeBytes(authString.getBytes());
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }

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

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

        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }

        rd.close();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new HttpSessionException("Server returned: " + connection.getResponseMessage());
        }

        return response.toString();

    } catch (Exception e) {
        throw new HttpSessionException(e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:identify.SendMessage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w.  j  av a 2s.  c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException {
    String sender = request.getParameter("sender");
    String receiver = request.getParameter("receiver");
    String message = request.getParameter("body");
    int index = SaveToken.storage.findUsername(receiver);
    System.out.println(index);
    String tokenTo = SaveToken.storage.getData().get(index).getToken();
    JSONObject obj = new JSONObject();
    obj.put("sender", sender);
    obj.put("receiver", receiver);
    obj.put("body", message);
    JSONObject arrayObj = new JSONObject();
    arrayObj.put("to", tokenTo);
    arrayObj.put("data", obj);
    System.out.println(arrayObj.toString());
    String USER_AGENT = "Mozilla/5.0";
    String authKey = "key=AIzaSyBPldzkpB5YtLm3N8cYbdoweqtn5Dk3IfQ";
    String contentType = "application/json";
    String url = "https://fcm.googleapis.com/fcm/send";
    URL connection = new URL(url);
    HttpURLConnection con = (HttpURLConnection) connection.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Content-Type", contentType);
    con.setRequestProperty("Authorization", authKey);

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

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder resp = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        resp.append(inputLine);
    }
    in.close();
    String acrHeaders = request.getHeader("Access-Control-Request-Headers");
    String acrMethod = request.getHeader("Access-Control-Request-Method");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers", acrHeaders);
    response.setHeader("Access-Control-Allow-Methods", acrMethod);
    response.setContentType("application/json:charset=UTF-8");
    response.getWriter().write(resp.toString());
}

From source file:logout2_servlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w  ww .  j ava  2s . com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String access_token = "";
    Cookie cookie = null;
    Cookie[] cookies = request.getCookies();
    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie1 = cookies[i];
        if (cookies[i].getName().equals("access_token")) {
            access_token = cookie1.getValue();
            cookie = cookie1;
        }
    }
    System.out.println("TOKEN = " + access_token);

    String USER_AGENT = "Mozilla/5.0";
    String url = "http://localhost:8082/Identity_Service/logout_servlet";
    URL connection = new URL(url);
    HttpURLConnection con = (HttpURLConnection) connection.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 = "access_token=" + access_token;

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

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder resp = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        resp.append(inputLine);
    }
    in.close();

    JSONParser parser = new JSONParser();
    JSONObject obj = null;
    try {
        obj = (JSONObject) parser.parse(resp.toString());
    } catch (ParseException ex) {
        Logger.getLogger(logout2_servlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    String status = (String) obj.get("status");
    System.out.println(status);
    if (status.equals("ok")) {
        cookie.setMaxAge(0);
        response.sendRedirect("login.jsp");
    } else {

    }

}

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

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;/*from ww w.  ja v  a2 s .co  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);
    }
}

From source file:org.openxdata.server.servlet.WMDownloadServlet.java

private void downloadStudies(HttpServletResponse response) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    formDownloadService.downloadStudies(dos, "", "");
    baos.flush();/*from   www.  ja va  2  s  .c o  m*/
    dos.flush();
    byte[] data = baos.toByteArray();
    baos.close();
    dos.close();

    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    PrintWriter out = response.getWriter();
    out.println("<StudyList>");

    try {
        @SuppressWarnings("unused")
        byte size = dis.readByte(); //reads the size of the studies

        while (true) {
            String value = "<study id=\"" + dis.readInt() + "\" name=\"" + dis.readUTF() + "\"/>";
            out.println(value);
        }
    } catch (EOFException exe) {
        //exe.printStackTrace();
    }
    out.println("</StudyList>");
    out.flush();
    dis.close();
}

From source file:datafu.hourglass.test.TestBase.java

/**
 * Stores the configuration in the properties as "test.conf" so it can 
 * be used by the job.  This property is a special test hook to enable
 * testing./*from  w ww.ja  v  a 2  s .  c o  m*/
 * 
 * @param props
 * @throws IOException
 */
protected void storeTestConf(Properties props) throws IOException {
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
    DataOutputStream dataStream = new DataOutputStream(arrayOutputStream);
    createJobConf().write(dataStream);
    dataStream.flush();
    props.setProperty("test.conf", new String(Base64.encodeBase64(arrayOutputStream.toByteArray())));
}