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:org.apache.sling.maven.slingstart.run.LauncherCallable.java

public static void stop(final Log LOG, final ProcessDescription cfg) throws Exception {
    boolean isNew = false;

    if (cfg.getProcess() != null || isNew) {
        LOG.info("Stopping Launchpad " + cfg.getId());
        boolean destroy = true;
        final int twoMinutes = 2 * 60 * 1000;
        final File controlPortFile = getControlPortFile(cfg.getDirectory());
        LOG.debug("Control port file " + controlPortFile + " exists: " + controlPortFile.exists());
        if (controlPortFile.exists()) {
            // reading control port
            int controlPort = -1;
            String secretKey = null;
            LineNumberReader lnr = null;
            String serverName = null;
            try {
                lnr = new LineNumberReader(new FileReader(controlPortFile));
                final String portLine = lnr.readLine();
                final int pos = portLine.indexOf(':');
                controlPort = Integer.parseInt(portLine.substring(pos + 1));
                if (pos > 0) {
                    serverName = portLine.substring(0, pos);
                }/* ww w. j a v a  2 s. c  o  m*/
                secretKey = lnr.readLine();
            } catch (final NumberFormatException ignore) {
                // we ignore this
                LOG.debug("Error reading control port file " + controlPortFile, ignore);
            } catch (final IOException ignore) {
                // we ignore this
                LOG.debug("Error reading control port file " + controlPortFile, ignore);
            } finally {
                IOUtils.closeQuietly(lnr);
            }

            if (controlPort != -1) {
                final List<String> hosts = new ArrayList<String>();
                if (serverName != null) {
                    hosts.add(serverName);
                }
                hosts.add("localhost");
                hosts.add("127.0.0.1");
                LOG.debug("Found control port " + controlPort);
                int index = 0;
                while (destroy && index < hosts.size()) {
                    final String hostName = hosts.get(index);

                    Socket clientSocket = null;
                    DataOutputStream out = null;
                    BufferedReader in = null;
                    try {
                        LOG.debug("Trying to connect to " + hostName + ":" + controlPort);
                        clientSocket = new Socket();
                        // set a socket timeout
                        clientSocket.connect(new InetSocketAddress(hostName, controlPort), twoMinutes);
                        // without that, read() call on the InputStream associated with this Socket is infinite
                        clientSocket.setSoTimeout(twoMinutes);

                        LOG.debug(hostName + ":" + controlPort
                                + " connection estabilished, sending the 'stop' command...");

                        out = new DataOutputStream(clientSocket.getOutputStream());
                        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        if (secretKey != null) {
                            out.writeBytes(secretKey);
                            out.write(' ');
                        }
                        out.writeBytes("stop\n");
                        in.readLine();
                        destroy = false;
                        LOG.debug("'stop' command sent to " + hostName + ":" + controlPort);
                    } catch (final Throwable ignore) {
                        // catch Throwable because InetSocketAddress and Socket#connect throws unchecked exceptions
                        // we ignore this for now
                        LOG.debug("Error sending 'stop' command to " + hostName + ":" + controlPort
                                + " due to: " + ignore.getMessage());
                    } finally {
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                        IOUtils.closeQuietly(clientSocket);
                    }
                    index++;
                }
            }
        }
        if (cfg.getProcess() != null) {
            final Process process = cfg.getProcess();

            if (!destroy) {
                // as shutdown might block forever, we use a timeout
                final long now = System.currentTimeMillis();
                final long end = now + twoMinutes;

                LOG.debug("Waiting for process to stop...");

                while (isAlive(process) && (System.currentTimeMillis() < end)) {
                    try {
                        Thread.sleep(2500);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
                if (isAlive(process)) {
                    LOG.debug("Process timeout out after 2 minutes");
                    destroy = true;
                } else {
                    LOG.debug("Process stopped");
                }
            }

            if (destroy) {
                LOG.debug("Destroying process...");
                process.destroy();
                LOG.debug("Process destroyed");
            }

            cfg.setProcess(null);
        }
    } else {
        LOG.warn("Launchpad already stopped");
    }
}

From source file:org.shareok.data.htmlrequest.HttpRequestHandler.java

public StringBuffer sendPost(String url) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con;//from   ww  w.  j  av  a 2 s.  co  m

    try {
        con = (HttpURLConnection) obj.openConnection();
    } catch (Exception e) {
        con = (HttpsURLConnection) 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 = "";

    // 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("\n\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();

    return response;

}

From source file:gr.iit.demokritos.cru.cpserver.CPServer.java

public void httpHandler(BufferedReader input, DataOutputStream output) throws IOException, Exception {

    String request = input.readLine();
    request = request.toUpperCase();//from  ww w. ja va  2s . com
    if (request.startsWith("POST")) {

        output.writeBytes(create_response_header(200));
        output.writeBytes(create_response_body(request));
    } else if (request.startsWith("GET")) {
        //ERROR MSG
        //output.writeBytes("ERROR 404");
        output.writeBytes(create_response_header(200));
        output.writeBytes(create_response_body(request));
    } else {
        //ERROR MSG
        output.writeBytes("404");
    }

    output.close();
}

From source file:api.APICall.java

public String executePost(String targetURL, String urlParameters) {
    URL url;//from   w w  w  . j  a  va  2  s  . com
    HttpURLConnection connection = null;
    try {
        // Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

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

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

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        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();
        return response.toString();

    } catch (SocketException se) {
        se.printStackTrace();
        System.out.println("Server is down.");
        return null;
    } catch (Exception e) {

        e.printStackTrace();
        return null;

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:ict.servlet.UploadToServer.java

public static int upLoad2Server(String sourceFileUri) {
    String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp";
    // String [] string = sourceFileUri;
    String fileName = sourceFileUri;
    int serverResponseCode = 0;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {

        return 0;
    }/*from   w w  w. java2s .c  o  m*/
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\""
                + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        m_log.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": "
                + serverResponseCode);
        // close streams
        m_log.info("Upload file to server" + fileName + " File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        //         ex.printStackTrace();
        m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        //      e.printStackTrace();
    }
    //this block will give the response of upload link
    /* try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
      m_log.info("Huzza" + "RES Message: " + line);
      }
      rd.close();
      } catch (IOException ioex) {
      m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex);
      }*/
    return serverResponseCode; // like 200 (Ok)

}

From source file:org.apache.openmeetings.web.pages.auth.SignInPage.java

private AuthInfo getToken(String code, OAuthServer server) throws IOException {
    String requestTokenBaseUrl = server.getRequestTokenUrl();
    // build url params to request auth token
    String requestTokenParams = server.getRequestTokenAttributes();
    requestTokenParams = prepareUrlParams(requestTokenParams, server.getClientId(), server.getClientSecret(),
            null, getRedirectUri(server, this), code);
    // request auth token
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(requestTokenBaseUrl).openConnection();
    prepareConnection(urlConnection);//from  w  w  w. j a  v a2  s . c  om
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    urlConnection.setRequestProperty("charset", StandardCharsets.UTF_8.name());
    urlConnection.setRequestProperty("Content-Length", String.valueOf(requestTokenParams.length()));
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    DataOutputStream paramsOutputStream = new DataOutputStream(urlConnection.getOutputStream());
    paramsOutputStream.writeBytes(requestTokenParams);
    paramsOutputStream.flush();
    String sourceResponse = IOUtils.toString(urlConnection.getInputStream(), StandardCharsets.UTF_8);
    // parse json result
    AuthInfo result = new AuthInfo();
    try {
        JSONObject jsonResult = new JSONObject(sourceResponse.toString());
        if (jsonResult.has("access_token")) {
            result.accessToken = jsonResult.getString("access_token");
        }
        if (jsonResult.has("refresh_token")) {
            result.refreshToken = jsonResult.getString("refresh_token");
        }
        if (jsonResult.has("token_type")) {
            result.tokenType = jsonResult.getString("token_type");
        }
        if (jsonResult.has("expires_in")) {
            result.expiresIn = jsonResult.getLong("expires_in");
        }
    } catch (JSONException e) {
        // try to parse as canonical
        Map<String, String> parsedMap = parseCanonicalResponse(sourceResponse.toString());
        result.accessToken = parsedMap.get("access_token");
        result.refreshToken = parsedMap.get("refresh_token");
        result.tokenType = parsedMap.get("token_type");
        try {
            result.expiresIn = Long.valueOf(parsedMap.get("expires_in"));
        } catch (NumberFormatException nfe) {
        }
    }
    // access token must be specified
    if (result.accessToken == null) {
        log.error("Response doesn't contain access_token field:\n" + sourceResponse.toString());
        return null;
    }
    return result;
}

From source file:edu.pdx.cecs.orcycle.UserFeedbackUploader.java

boolean uploadUserInfoV4() {
    boolean result = false;
    final String postUrl = mCtx.getResources().getString(R.string.post_url);

    try {/* ww w  .  j a v a  2  s  .  com*/
        URL url = new URL(postUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Cycleatl-Protocol-Version", "4");

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        JSONObject jsonUser;
        if (null != (jsonUser = getUserJSON())) {
            try {
                String deviceId = userId;

                dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n");
                dos.writeBytes(
                        fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n");
                dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n");
                dos.writeBytes(fieldSep);
                dos.flush();
            } catch (Exception ex) {
                Log.e(MODULE_TAG, ex.getMessage());
                return false;
            } finally {
                dos.close();
            }
            int serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();
            // JSONObject responseData = new JSONObject(serverResponseMessage);
            Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
            if (serverResponseCode == 201 || serverResponseCode == 202) {
                // TODO: Record somehow that data was uploaded successfully
                result = true;
            }
        } else {
            result = false;
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }
    return result;
}

From source file:org.scigap.iucig.controller.ScienceDisciplineController.java

@ResponseBody
@RequestMapping(value = "/updateScienceDiscipline", method = RequestMethod.POST)
public void updateScienceDiscipline(@RequestBody ScienceDiscipline discipline, HttpServletRequest request)
        throws Exception {
    try {/*  w ww.  ja v a2s  . c  om*/
        String remoteUser;
        if (request != null) {
            remoteUser = request.getRemoteUser();
        } else {
            throw new Exception("Remote user is null");
        }
        int primarySubDisId = 0;
        int secondarySubDisId = 0;
        int tertiarySubDisId = 0;
        String urlParameters = "user=" + remoteUser;
        if (discipline != null) {
            Map<String, String> primarySubDisc = discipline.getPrimarySubDisc();
            if (primarySubDisc != null && !primarySubDisc.isEmpty()) {
                for (String key : primarySubDisc.keySet()) {
                    if (key.equals("id")) {
                        primarySubDisId = Integer.valueOf(primarySubDisc.get(key));
                        urlParameters += "&discipline1=" + primarySubDisId;
                    }
                }
            } else {
                Map<String, Object> primaryDiscipline = discipline.getPrimaryDisc();
                if (primaryDiscipline != null && !primaryDiscipline.isEmpty()) {
                    Object subdisciplines = primaryDiscipline.get("subdisciplines");
                    if (subdisciplines instanceof ArrayList) {
                        for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) {
                            Object disc = ((ArrayList) subdisciplines).get(i);
                            if (disc instanceof HashMap) {
                                if (((HashMap) disc).get("name").equals("Other / Unspecified")) {
                                    primarySubDisId = Integer.valueOf((((HashMap) disc).get("id")).toString());
                                }
                            }
                        }
                        urlParameters += "&discipline1=" + primarySubDisId;
                    }
                }
            }
            Map<String, String> secondarySubDisc = discipline.getSecondarySubDisc();
            if (secondarySubDisc != null && !secondarySubDisc.isEmpty()) {
                for (String key : secondarySubDisc.keySet()) {
                    if (key.equals("id")) {
                        secondarySubDisId = Integer.valueOf(secondarySubDisc.get(key));
                        urlParameters += "&discipline2=" + secondarySubDisId;
                    }
                }
            } else {
                Map<String, Object> secondaryDisc = discipline.getSecondaryDisc();
                if (secondaryDisc != null && !secondaryDisc.isEmpty()) {
                    Object subdisciplines = secondaryDisc.get("subdisciplines");
                    if (subdisciplines instanceof ArrayList) {
                        for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) {
                            Object disc = ((ArrayList) subdisciplines).get(i);
                            if (disc instanceof HashMap) {
                                if (((HashMap) disc).get("name").equals("Other / Unspecified")) {
                                    secondarySubDisId = Integer
                                            .valueOf((((HashMap) disc).get("id")).toString());
                                }
                            }
                        }
                        urlParameters += "&discipline2=" + secondarySubDisId;
                    }
                }
            }

            Map<String, String> tertiarySubDisc = discipline.getTertiarySubDisc();
            if (tertiarySubDisc != null && !tertiarySubDisc.isEmpty()) {
                for (String key : tertiarySubDisc.keySet()) {
                    if (key.equals("id")) {
                        tertiarySubDisId = Integer.valueOf(tertiarySubDisc.get(key));
                        urlParameters += "&discipline3=" + tertiarySubDisId;
                    }
                }
            } else {
                Map<String, Object> tertiaryDisc = discipline.getTertiaryDisc();
                if (tertiaryDisc != null && !tertiaryDisc.isEmpty()) {
                    Object subdisciplines = tertiaryDisc.get("subdisciplines");
                    if (subdisciplines instanceof ArrayList) {
                        for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) {
                            Object disc = ((ArrayList) subdisciplines).get(i);
                            if (disc instanceof HashMap) {
                                if (((HashMap) disc).get("name").equals("Other / Unspecified")) {
                                    tertiarySubDisId = Integer.valueOf((((HashMap) disc).get("id")).toString());
                                }
                            }
                        }
                        urlParameters += "&discipline3=" + tertiarySubDisId;
                    }
                }
            }
            URL obj = new URL(SCIENCE_DISCIPLINE_URL + "discipline/");
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            urlParameters += "&date=" + discipline.getDate() + "&source=cybergateway&commit=Update&cluster="
                    + discipline.getCluster();
            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 : " + SCIENCE_DISCIPLINE_URL);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.mendhak.gpslogger.senders.gdocs.GDocsHelper.java

private String CreateEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) {

    String fileId = null;//from w w  w . ja  v a  2s.c o m
    HttpURLConnection conn = null;

    String createFileUrl = "https://www.googleapis.com/drive/v2/files";

    String createFilePayload = "   {\n" + "             \"title\": \"" + fileName + "\",\n"
            + "             \"mimeType\": \"" + mimeType + "\",\n" + "             \"parents\": [\n"
            + "              {\n" + "               \"id\": \"" + parentFolderId + "\"\n" + "              }\n"
            + "             ]\n" + "            }";

    try {

        if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
            //Due to a pre-froyo bug
            //http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            System.setProperty("http.keepAlive", "false");
        }

        URL url = new URL(createFileUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/json");

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

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(createFilePayload);
        wr.flush();
        wr.close();

        fileId = null;

        String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream());

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        Utilities.LogDebug("File created with ID " + fileId);

    } catch (Exception e) {

        System.out.println(e.getMessage());
        System.out.println(e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }

    }

    return fileId;
}

From source file:org.testcontainers.couchbase.CouchbaseContainer.java

public void callCouchbaseRestAPI(String url, String payload) throws IOException {
    String fullUrl = urlBase + url;
    @Cleanup("disconnect")
    HttpURLConnection httpConnection = (HttpURLConnection) ((new URL(fullUrl).openConnection()));
    httpConnection.setDoOutput(true);//from  w w w .ja  va  2  s.  co m
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    String encoded = Base64.encode((clusterUsername + ":" + clusterPassword).getBytes("UTF-8"));
    httpConnection.setRequestProperty("Authorization", "Basic " + encoded);
    @Cleanup
    DataOutputStream out = new DataOutputStream(httpConnection.getOutputStream());
    out.writeBytes(payload);
    out.flush();
    httpConnection.getResponseCode();
}