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:pl.edu.agh.ServiceConnection.java

/**
 * 1. Sends data to service: console password | service password | service id
 *///from   www  . j  av  a 2s  .co m
public void connect(Service service) {
    try {
        LOGGER.info("Connecting to service: " + service);
        Socket socket = new Socket(service.getHost(), service.getPort());
        socket.setSoTimeout(300);
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        out.writeBytes(service.getPassword() + "|" + service.getId() + "\r\n");
        String response = in.readLine();

        in.close();
        out.close();
        socket.close();

        LOGGER.info("Service response: " + response);

    } catch (Exception e) {
        LOGGER.error("Error connecting with daemon: " + e.getMessage());
    }
}

From source file:br.org.indt.ndg.servlets.PostResultsOpenRosa.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    m_openRosaBD.setPortAndAddress(SystemProperties.getServerAddress());

    InputStreamReader inputStreamReader = new InputStreamReader(request.getInputStream(), "UTF-8");
    boolean success = m_openRosaBD.parseAndPersistResult(inputStreamReader, request.getContentType());

    DataOutputStream dataOutputStream = new DataOutputStream(response.getOutputStream());
    if (success) {
        dataOutputStream.writeInt(SUCCESS);
        log.info("Successfully processed result stream from " + request.getRemoteAddr());
    } else {//  w w w. j  a v  a 2s .c  om
        dataOutputStream.writeInt(FAILURE);
        log.error("Failed processing result stream from " + request.getRemoteAddr());
    }
    dataOutputStream.close();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.GenericCandidaciesDA.java

public ActionForward downloadRecomendationFile(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws IOException {
    final String confirmationCode = (String) getFromRequest(request, "confirmationCode");
    final GenericApplicationLetterOfRecomentation file = getDomainObject(request, "fileExternalId");
    if (file != null && file.getRecomentation() != null && file.getRecomentation().getConfirmationCode() != null
            && ((file.getRecomentation().getGenericApplication().getGenericApplicationPeriod()
                    .isCurrentUserAllowedToMange())
                    || file.getRecomentation().getConfirmationCode().equals(confirmationCode))) {
        response.setContentType(file.getContentType());
        response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\"");
        response.setContentLength(file.getSize().intValue());
        final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
        dos.write(file.getContent());//from   ww  w.  j av  a 2s .co m
        dos.close();
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();
    }
    return null;
}

From source file:iics.Connection.java

public String excutePost(String targetURL, String urlParameters) {

    URL url;//from  ww w.j  a  v a  2s. co  m
    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) {
            if (!line.equals("")) {
                response.append(line);
            }
            //response.append('\r');
        }
        rd.close();

        // System.out.println("gigig " + response.toString());
        if (response.toString().substring(0, 8).equals("Response")) {
            String[] dett = response.toString().split("~~~");
            det = dett[1];
            create_dir();
            openweb(f.toString());
        } else {
            //System.out.println("err "+ex.getMessage());
            JOptionPane.showMessageDialog(null,
                    "                 An error occured!! \n Try again later or contact your system admin for help.");
            close_loda();
        }
        return response.toString();

    } catch (Exception e) {

        JOptionPane.showMessageDialog(null,
                "                 An error occured!! \n Contact your system admin for help.", null,
                JOptionPane.WARNING_MESSAGE);
        close_loda();
        return null;

    } finally {

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

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.GenericCandidaciesDA.java

public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    final GenericApplication application = getDomainObject(request, "applicationExternalId");
    final String confirmationCode = (String) getFromRequest(request, "confirmationCode");
    final GenericApplicationFile file = getDomainObject(request, "fileExternalId");
    if (application != null && file != null && file.getGenericApplication() == application
            && ((confirmationCode != null && application.getConfirmationCode() != null
                    && application.getConfirmationCode().equals(confirmationCode))
                    || application.getGenericApplicationPeriod().isCurrentUserAllowedToMange())) {
        response.setContentType(file.getContentType());
        response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\"");
        response.setContentLength(file.getSize().intValue());
        final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
        dos.write(file.getContent());/*from w  w  w. ja v a 2s.c o m*/
        dos.close();
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();
    }
    return null;
}

From source file:com.apteligent.ApteligentJavaClient.java

private HttpsURLConnection sendPostRequest(String endpoint, String params) throws IOException {
    // build conn object for POST request
    URL obj = new URL(endpoint);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);//from ww w .  j  av  a  2  s  . com
    conn.setDoInput(true);
    conn.setRequestProperty("Authorization", "Bearer " + this.token.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
    conn.setRequestMethod("POST");

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

From source file:com.dagobert_engine.core.service.MtGoxApiAdapter.java

/**
 * Queries the mtgox api with params/*from  ww w .j  a  va  2s .c o m*/
 * 
 * @param url
 * @return
 */
public String query(String path, HashMap<String, String> args) {

    final String publicKey = mtGoxConfig.getMtGoxPublicKey();
    final String privateKey = mtGoxConfig.getMtGoxPrivateKey();

    if (publicKey == null || privateKey == null || "".equals(publicKey) || "".equals(privateKey)) {
        throw new ApiKeysNotSetException(
                "Either public or private key of MtGox are not set. Please set them up in src/main/resources/META-INF/seam-beans.xml");
    }

    // Create nonce
    final String nonce = String.valueOf(System.currentTimeMillis()) + "000";

    HttpsURLConnection connection = null;
    String answer = null;
    try {
        // add nonce and build arg list
        args.put(ARG_KEY_NONCE, nonce);
        String post_data = buildQueryString(args);

        String hash_data = path + "\0" + post_data; // Should be correct

        // args signature with apache cryptografic tools
        String signature = signRequest(mtGoxConfig.getMtGoxPrivateKey(), hash_data);

        // build URL
        URL queryUrl = new URL(Constants.API_BASE_URL + path);
        // create and setup a HTTP connection
        connection = (HttpsURLConnection) queryUrl.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty(REQ_PROP_USER_AGENT, com.dagobert_engine.core.util.Constants.APP_NAME);
        connection.setRequestProperty(REQ_PROP_REST_KEY, mtGoxConfig.getMtGoxPublicKey());
        connection.setRequestProperty(REQ_PROP_REST_SIGN, signature.replaceAll("\n", ""));

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

        // Read the response

        DataOutputStream os = new DataOutputStream(connection.getOutputStream());
        os.writeBytes(post_data);
        os.close();

        BufferedReader br = null;

        // Any error?
        int code = connection.getResponseCode();
        if (code >= 400) {
            // get error stream
            br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));

            answer = toString(br);
            logger.severe("HTTP Error on queryin " + path + ": " + code + ", answer: " + answer);
            throw new MtGoxConnectionError(code, answer);

        } else {
            // get normal stream
            br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
            answer = toString(br);

        }
    } catch (UnknownHostException exc) {
        throw new MtGoxConnectionError("Could not connect to MtGox. Please check your internet connection. ("
                + exc.getClass().getName() + ")");
    } catch (IllegalStateException ex) {
        throw new MtGoxConnectionError(ex);
    } catch (IOException ex) {
        throw new MtGoxConnectionError(ex);
    } finally {

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

    return answer;
}

From source file:RetrieveAllMIDlet.java

public byte[] changeToByteArray() {
    byte[] data = null;

    try {/*from   w ww  .  ja  v a2s . co  m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeUTF(name);
        dos.writeInt(chineseScore);
        dos.writeInt(englishScore);
        dos.writeInt(mathScore);
        data = baos.toByteArray();

        baos.close();
        dos.close();
    } catch (Exception e) {
    }
    return data;
}

From source file:ml.shifu.shifu.core.correlation.CorrelationReducer.java

public byte[] objectToBytes(Writable result) {
    ByteArrayOutputStream out = null;
    DataOutputStream dataOut = null;
    try {//from w ww .j  av a  2s.c o m
        out = new ByteArrayOutputStream();
        dataOut = new DataOutputStream(out);
        result.write(dataOut);
    } catch (IOException e) {
        throw new GuaguaRuntimeException(e);
    } finally {
        if (dataOut != null) {
            try {
                dataOut.close();
            } catch (IOException e) {
                throw new GuaguaRuntimeException(e);
            }
        }
    }
    return out.toByteArray();
}

From source file:org.belio.service.gateway.AirtelCharging.java

private String sendXmlOverPost(String url, String xml) {
    StringBuffer result = new StringBuffer();
    try {// w w w .j  a  v  a2  s  . c om
        Launcher.LOG.info("======================xml==============");

        Launcher.LOG.info(xml.toString());

        //            String userPassword = "roamtech_KE:roamtech _KE!ibm123";
        //            URL url2 = new URL("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");

        String userPassword = "" + networkproperties.getProperty("air_info_u") + ":"
                + networkproperties.getProperty("air_info_p");
        URL url2 = new URL(url);

        // URLConnection urlc =  url.openConnection();
        URLConnection urlc = url2.openConnection();
        HttpsURLConnection conn = (HttpsURLConnection) urlc;
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("SOAPAction", "run");

        //            urlc.setDoOutput(true);
        //            urlc.setUseCaches(false);
        //            urlc.setAllowUserInteraction(false);
        conn.setRequestProperty("Authorization", "Basic " + new Base64().encode(userPassword.getBytes()));
        conn.setRequestProperty("Content-Type", "text/xml");

        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        // Write post data
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(xml);
        out.flush();
        out.close();
        BufferedReader aiResult = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuffer responseMessage = new StringBuffer();
        while ((line = aiResult.readLine()) != null) {
            responseMessage.append(line);
        }
        System.out.println(responseMessage);

        //urlc.s("POST");  
        //  urlc.setRequestProperty("SOAPAction", SOAP_ACTION);

        urlc.connect();

    }

    catch (MalformedURLException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }

    catch (IOException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }
    return result.toString();

    //        try {
    //            // String url = "https://selfsolve.apple.com/wcResults.do";
    //            HttpClient client = new DefaultHttpClient();
    //            HttpPost post = new HttpPost("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");
    //            // add header
    //            post.setHeader("User-Agent", USER_AGENT);
    //            post.setHeader("Content-type:", " text/xml");
    //            post.setHeader("charset", "utf-8");
    //            post.setHeader("Accept:", ",text/xml");
    //            post.setHeader("Cache-Control:", " no-cache");
    //            post.setHeader("Pragma:", " no-cache");
    //            post.setHeader("SOAPAction:", "run");
    //            post.setHeader("Content-length:", "xml");
    //            
    ////            String encoding = new Base64().encode((networkproperties.getProperty("air_charge_n") + ":"
    ////                    + networkproperties.getProperty("air_charge_p")).getBytes());
    //            String encoding = new Base64().encode( ("roamtech_KE:roamtech _KE!ibm123").getBytes());
    //            
    //            post.setHeader("Authorization", "Basic " + encoding);
    //
    //            // post.setHeader("Authorization: Basic ", "base64_encode(credentials)");
    //            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    //            
    //            urlParameters.add(new BasicNameValuePair("xml", xml));
    //            
    //            System.out.println("\n============================ : " + url);
    //
    ////            urlParameters.add(new BasicNameValuePair("srcCode", ""));
    ////            urlParameters.add(new BasicNameValuePair("phone", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentId", ""));
    ////            urlParameters.add(new BasicNameValuePair("itemName", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentDescription", ""));
    ////            urlParameters.add(new BasicNameValuePair("actualPrice", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentMediaType", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentUrl", ""));
    //            post.setEntity(new UrlEncodedFormEntity(urlParameters));
    //            
    //            HttpResponse response = client.execute(post);
    //            Launcher.LOG.info("\nSending 'POST' request to URL : " + url);
    //            Launcher.LOG.info("Post parameters : " + post.getEntity());
    //            Launcher.LOG.info("Response Code : "
    //                    + response.getStatusLine().getStatusCode());
    //            
    //            BufferedReader rd = new BufferedReader(
    //                    new InputStreamReader(response.getEntity().getContent()));
    //            
    //            String line = "";
    //            while ((line = rd.readLine()) != null) {
    //                result.append(line);
    //            }
    //            
    //            System.out.println(result.toString());
    //        } catch (UnsupportedEncodingException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        } catch (IOException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        }
}