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:org.alfresco.webservice.util.ContentUtils.java

/**
 * Streams content into the repository.  Once done a content details string is returned and this can be used to update 
 * a content property in a CML statement.
 * /*from  ww w. ja va 2s . com*/
 * @param file  the file to stream into the repository
 * @param host  the host name of the destination repository
 * @param port  the port name of the destination repository
 * @param webAppName        the name of the target web application (default 'alfresco')
 * @param mimetype the mimetype of the file, ignored if null
 * @param encoding the encoding of the file, ignored if null
 * @return      the content data that can be used to set the content property in a CML statement  
 */
@SuppressWarnings("deprecation")
public static String putContent(File file, String host, int port, String webAppName, String mimetype,
        String encoding) {
    String result = null;

    try {
        String url = "/" + webAppName + "/upload/" + URLEncoder.encode(file.getName(), "UTF-8") + "?ticket="
                + AuthenticationUtils.getTicket();
        if (mimetype != null) {
            url = url + "&mimetype=" + mimetype;
        }
        if (encoding != null) {
            url += "&encoding=" + encoding;
        }

        String request = "PUT " + url + " HTTP/1.1\n" + "Cookie: JSESSIONID="
                + AuthenticationUtils.getAuthenticationDetails().getSessionId() + ";\n" + "Content-Length: "
                + file.length() + "\n" + "Host: " + host + ":" + port + "\n" + "Connection: Keep-Alive\n"
                + "\n";

        // Open sockets and streams
        Socket socket = new Socket(host, port);
        DataOutputStream os = new DataOutputStream(socket.getOutputStream());
        DataInputStream is = new DataInputStream(socket.getInputStream());

        try {
            if (socket != null && os != null && is != null) {
                // Write the request header
                os.writeBytes(request);

                // Stream the content onto the server
                InputStream fileInputStream = new FileInputStream(file);
                int byteCount = 0;
                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead = -1;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                    byteCount += bytesRead;
                }
                os.flush();
                fileInputStream.close();

                // Read the response and deal with any errors that might occur
                boolean firstLine = true;
                String responseLine;
                while ((responseLine = is.readLine()) != null) {
                    if (firstLine == true) {
                        if (responseLine.contains("200") == true) {
                            firstLine = false;
                        } else if (responseLine.contains("401") == true) {
                            throw new RuntimeException(
                                    "Content could not be uploaded because invalid credentials have been supplied.");
                        } else if (responseLine.contains("403") == true) {
                            throw new RuntimeException(
                                    "Content could not be uploaded because user does not have sufficient privileges.");
                        } else {
                            throw new RuntimeException(
                                    "Error returned from upload servlet (" + responseLine + ")");
                        }
                    } else if (responseLine.contains("contentUrl") == true) {
                        result = responseLine;
                        break;
                    }
                }
            }
        } finally {
            try {
                // Close the streams and socket
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("Error closing sockets and streams", e);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error writing content to repository server", e);
    }

    return result;
}

From source file:net.portalblockz.portalbot.urlshorteners.GooGl.java

@Override
public String shorten(String url) {
    StringBuilder response = new StringBuilder();
    try {/*from ww w.  j  av  a 2 s .c o  m*/
        URL req = new URL("https://www.googleapis.com/urlshortener/v1/url");

        HttpsURLConnection con = (HttpsURLConnection) req.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes("{\"longUrl\": \"" + url + "\"}");
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        JSONObject res = new JSONObject(response.toString());
        if (res.optString("id") != null)
            return res.getString("id");

    } catch (Exception ignored) {
        ignored.printStackTrace();
        System.out.print(response.toString());
    }
    return null;
}

From source file:net.terryyiu.emailservice.providers.AbstractEmailServiceProvider.java

@Override
public boolean send(Email email) throws IOException {
    HttpURLConnection connection = createConnection();

    // Create a Map from an email object, which can be translated to JSON which
    // the specific email service provider understands.
    Map<String, Object> map = getRequestPostData(email);

    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(map);

    DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
    dos.writeBytes(json);// ww w. j a  v a2  s. c o  m
    dos.flush();
    dos.close();

    int responseCode = connection.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + getServiceUrl());
    System.out.println("JSON: " + json);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    connection.disconnect();
    return false;
}

From source file:MainFrame.CheckConnection.java

private boolean isOnline() throws MalformedURLException, IOException, Exception {
    String url = "http://www.itstepdeskview.hol.es";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "apideskviewer.checkStatus={}";

    // Send post request
    con.setDoOutput(true);//from  ww w.  j av  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()));

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

    JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

    String s = (String) jsonParsedResponse.get("response");
    if (s.equals("online")) {
        return true;
    } else {
        return false;
    }
}

From source file:net.indialend.web.component.GCMComponent.java

public void setMessage(User user, String deactivate) {

    try {// w  ww .jav a 2 s.co  m
        URL obj = new URL(serviceUrl);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "key=" + API_KEY);

        String urlParameters = "{" + "   \"data\": {" + "     \"deactivate\": \"" + deactivate + "\"," + "   },"
                + "   \"to\": \"" + user.getGcmToken() + "\"" + " }";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(urlParameters.getBytes("UTF-8"));
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + serviceUrl);
        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
        System.out.println(response.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.bikfalvi.java.web.WebState.java

/**
 * Creates a GET web request for the current URL.
 * @throws IOException /* ww  w . j  a va2 s . c o m*/
 */
public void execute() throws IOException {
    // If the data is not null.
    if (null != this.data) {
        // Write the data.
        this.connection.setDoOutput(true);
        DataOutputStream stream = new DataOutputStream(this.connection.getOutputStream());
        stream.write(this.data);
        stream.flush();
        stream.close();
    }

    // Execute the request and set the response code.
    int code = this.connection.getResponseCode();

    // Set the response data.
    this.setResponse(code, this.connection.getInputStream(), this.connection.getContentEncoding());

    // Complete the request.
    this.complete();
}

From source file:net.bashtech.geobot.BotManager.java

public static String postRemoteDataStrawpoll(String urlString) {

    String line = "";
    try {/*  w w w .jav a2 s.  c  o m*/
        HttpURLConnection c = (HttpURLConnection) (new URL("http://strawpoll.me/api/v2/polls")
                .openConnection());

        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/json");
        c.setRequestProperty("User-Agent", "CB2");

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

        String queryString = urlString;

        c.setRequestProperty("Content-Length", Integer.toString(queryString.length()));

        DataOutputStream wr = new DataOutputStream(c.getOutputStream());
        wr.writeBytes(queryString);

        wr.flush();
        wr.close();

        Scanner inStream = new Scanner(c.getInputStream());

        while (inStream.hasNextLine())
            line += (inStream.nextLine());

        inStream.close();
        System.out.println(line);
        try {
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(line);
            JSONObject jsonObject = (JSONObject) obj;
            line = (Long) jsonObject.get("id") + "";

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

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return line;
}

From source file:com.gagein.crawler.FileDownLoader.java

/**
 * ? filePath ???/*from   w  ww .ja v a 2  s.c  o  m*/
 */
private void saveToLocal(byte[] data, String filePath) {
    try {
        System.out.println("========SaveToLocal========filePath===" + filePath);
        DataOutputStream out = new DataOutputStream(new FileOutputStream(new File(filePath)));
        for (int i = 0; i < data.length; i++)
            out.write(data[i]);
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.dirtyunicorns.hfm.mainFragment.java

public void RunAsRoot(String string) throws IOException {
    Process P = Runtime.getRuntime().exec("su");
    DataOutputStream os = new DataOutputStream(P.getOutputStream());
    os.writeBytes(string + "\n");
    os.writeBytes("exit\n");
    os.flush();
}

From source file:db.dao.ArticleDao.java

public void deletebyId(String deleteId) {
    try {//  ww w. java 2 s.c  om
        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);
    }
}