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:net.namecoin.NameCoinI2PResolver.HttpSession.java

public String executePost(String postdata) throws HttpSessionException {
    URL url;/*from   w ww .  j  a  v a2 s . c om*/
    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:com.googlecode.fascinator.portal.quartz.ExternalJob.java

/**
 * The real work happens here/*from w  w  w  .  j  a  v a  2s .  co 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:identify.SendMessage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w w  .  j  av  a2 s . c  o  m
 *
 * @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:ImageTransfer.java

public void javaToNative(Object object, TransferData transferData) {
    if (!checkImage(object) || !isSupportedType(transferData)) {
        DND.error(DND.ERROR_INVALID_DATA);
    }/*from   w  ww. j  a v  a  2s .c  o  m*/
    ImageData imdata = (ImageData) object;
    try {
        // write data to a byte array and then ask super to convert to
        // pMedium
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DataOutputStream writeOut = new DataOutputStream(out);
        ImageLoader loader = new ImageLoader();
        loader.data = new ImageData[] { imdata };
        loader.save(writeOut, SWT.IMAGE_BMP);
        writeOut.close();
        byte[] buffer = out.toByteArray();
        super.javaToNative(buffer, transferData);
        out.close();
    } catch (IOException e) {
    }
}

From source file:com.csipsimple.backup.SipSharedPreferencesHelper.java

@Override
public void writeNewStateDescription(ParcelFileDescriptor newState) {
    long fileModified = 0;
    if (prefsFiles != null) {
        prefsFiles.lastModified();//from  w ww  .  j  a v  a 2  s .  c o  m
    }
    try {
        FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor());
        DataOutputStream out = new DataOutputStream(outstream);
        out.writeLong(fileModified);
        out.close();
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage final local backup state", e);
    }
}

From source file:logout2_servlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w w w.  jav  a2  s.  c om*/
 * @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.csipsimple.backup.SipProfilesHelper.java

@Override
public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) {
    boolean forceBackup = (oldState == null);

    long fileModified = databaseFile.lastModified();
    try {//from w  w w  . ja v  a  2 s .co m
        if (!forceBackup) {
            FileInputStream instream = new FileInputStream(oldState.getFileDescriptor());
            DataInputStream in = new DataInputStream(instream);
            long lastModified = in.readLong();
            in.close();

            if (lastModified < fileModified) {
                forceBackup = true;
            }
        }
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage previous local backup state", e);
        forceBackup = true;
    }

    Log.d(THIS_FILE, "Will backup profiles ? " + forceBackup);
    if (forceBackup) {
        JSONArray accountsSaved = SipProfileJson.serializeSipProfiles(mContext);
        try {
            writeData(data, accountsSaved.toString());
        } catch (IOException e) {
            Log.e(THIS_FILE, "Cannot manage remote backup", e);
        }
    }

    try {
        FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor());
        DataOutputStream out = new DataOutputStream(outstream);
        out.writeLong(fileModified);
        out.close();
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage final local backup state", e);
    }
}

From source file:com.wakatime.eclipse.plugin.Dependencies.java

public boolean downloadFile(String url, String saveAs) {
    File outFile = new File(saveAs);

    // create output directory if does not exist
    File outDir = outFile.getParentFile();
    if (!outDir.exists())
        outDir.mkdirs();//from  w  w  w  .  ja va2s .com

    WakaTime.log("Downloading " + url + " to " + outFile.toString());

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    try {

        // download file
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        // save file contents
        DataOutputStream os = new DataOutputStream(new FileOutputStream(outFile));
        entity.writeTo(os);
        os.close();

        return true;

    } catch (ClientProtocolException e) {
        WakaTime.error("Error", e);
    } catch (FileNotFoundException e) {
        WakaTime.error("Error", e);
    } catch (IOException e) {
        WakaTime.error("Error", e);
    }

    return false;
}

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

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;/*from www .  j a  v  a  2 s .  c o 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:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java

protected void setRequestParams(HttpURLConnection connection, Request<?> request)
        throws ProtocolException, IOException {
    Request.HttpMethod method = request.getmHttpMethod();
    connection.setRequestMethod(method.toString());
    // add params
    byte[] body = request.getBody();
    if (body != null) {
        // enable output
        connection.setDoOutput(true);/*ww w .ja  v a 2  s  .  co  m*/
        // set content type
        connection.addRequestProperty(Request.HEADER_CONTENT_TYPE, request.getBodyContentType());
        // write params data to connection
        DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
        dataOutputStream.write(body);
        dataOutputStream.close();
    }
}