Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

In this page you can find the example usage for java.io OutputStreamWriter close.

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:biblivre3.cataloging.bibliographic.BiblioBO.java

private File createIsoFile(Database database) {
    try {//from ww  w . j a  va  2s.  co  m
        File file = File.createTempFile("bib3_", null);
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
        BiblioDAO biblioDao = new BiblioDAO();
        int limit = 100;
        int recordCount = biblioDao.countAll(database);

        for (int offset = 0; offset < recordCount; offset += limit) {
            ArrayList<RecordDTO> records = biblioDao.list(database, MaterialType.ALL, offset, limit, false);
            for (RecordDTO dto : records) {
                writer.write(dto.getIso2709());
                writer.write(ApplicationConstants.LINE_BREAK);
            }
        }
        writer.flush();
        writer.close();
        return file;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return null;
}

From source file:net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent.DataTypeBigDecimal.java

/**
 * Construct an appropriate external representation of the object
 * and write it to a file.//from w  w  w.ja va2  s.  c o m
 * Errors are returned by throwing an IOException containing the
 * cause of the problem as its message.
 * <P>
 * DataType is responsible for validating that the given text
 * text from a Popup JTextArea can be converted to an object.
 * This text-to-object conversion is the same as validateAndConvertInPopup,
 * which may be used internally by the object to do the validation.
 * <P>
 * The DataType object must flush and close the output stream before returning.
 * Typically it will create another object (e.g. an OutputWriter), and
 * that is the object that must be flushed and closed.
 * 
 * <P>
 * File is assumed to be and ASCII string of digits
 * representing a value of this data type.
 */
public void exportObject(FileOutputStream outStream, String text) throws IOException {

    OutputStreamWriter outWriter = new OutputStreamWriter(outStream);

    // check that the text is a valid representation
    StringBuffer messageBuffer = new StringBuffer();
    validateAndConvertInPopup(text, null, messageBuffer);
    if (messageBuffer.length() > 0) {
        // there was an error in the conversion
        throw new IOException(new String(messageBuffer));
    }

    // just send the text to the output file
    outWriter.write(text);
    outWriter.flush();
    outWriter.close();
}

From source file:com.androidaq.AndroiDAQMain.java

public void writeToFile(String data) {

    File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/log.txt");

    try {/*from   w  w  w.  ja  v a 2 s.c  o m*/
        if (!myFile.exists()) {
            myFile.createNewFile();
            Toast.makeText(getBaseContext(), "Created new 'log.txt'", Toast.LENGTH_SHORT).show();
        }
    } catch (IOException e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    try {

        FileOutputStream fOut = new FileOutputStream(myFile, true);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(data);
        myOutWriter.close();
        fOut.close();
        Toast.makeText(getBaseContext(), "Done writing to SD 'log.txt'", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }

}

From source file:me.kaidul.uhunt.MainActivity.java

private void writeToFile(String data, String fileName) {
    try {//from  www.  j a v a2 s  .  c  om
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                openFileOutput(fileName, Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    } catch (IOException e) {
        if (CommonUtils.isDebuggable) {
            Log.e("Exception", "File write failed: " + e.toString());
        }
    }
}

From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean running_state = CMS.isInRunningState();

    if (!running_state)
        throw new IOException("CMS server is not ready to serve.");

    HttpServletRequest req = request;/*from   w w w  .  ja  v a2  s .co m*/
    HttpServletResponse resp = response;

    CMSRequest cmsRequest = newCMSRequest();

    // set argblock
    cmsRequest.setHttpParams(CMS.createArgBlock(toHashtable(request)));

    // set http request
    cmsRequest.setHttpReq(request);

    // set http response
    cmsRequest.setHttpResp(response);

    // set servlet config.
    cmsRequest.setServletConfig(mConfig);

    // set servlet context.
    cmsRequest.setServletContext(mConfig.getServletContext());

    char[] content = null;
    String encodedreq = null;
    String method = null;
    int len = -1;
    IPKIMessage msg = null;
    IPKIMessage replymsg = null;

    // NOTE must read all bufer before redoing handshake for
    // ssl client auth for client auth to work.

    // get request method
    method = req.getMethod();

    // get content length
    len = request.getContentLength();

    // get content, a base 64 encoded serialized request.
    if (len > 0) {
        InputStream in = request.getInputStream();
        InputStreamReader inreader = new InputStreamReader(in, "UTF8");
        BufferedReader reader = new BufferedReader(inreader, len);

        content = new char[len];
        int done = reader.read(content, 0, len);
        int total = done;

        while (done >= 0 && total < len) {
            done = reader.read(content, total, len - total);
            total += done;
        }
        reader.close();
        encodedreq = new String(content);
    }

    // force client auth handshake, validate RA and get RA's Id.
    // NOTE must do this after all contents are read for ssl
    // redohandshake to work

    X509Certificate peerCert;

    try {
        peerCert = getPeerCert(req);
    } catch (EBaseException e) {
        mAuthority.log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT"));
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    if (peerCert == null) {
        // XXX log something here.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // authenticate RA

    String RA_Id = null;
    String raUserId = null;
    IAuthToken token = null;

    try {
        token = authenticate(request);
        raUserId = token.getInString("userid");
        RA_Id = peerCert.getSubjectDN().toString();
    } catch (EInvalidCredentials e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } catch (EBaseException e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    mAuthority.log(ILogger.LL_INFO, "Remote Authority authenticated: " + peerCert.getSubjectDN());

    // authorize
    AuthzToken authzToken = null;

    try {
        authzToken = authorize(mAclMethod, token, mAuthzResourceName, "submit");
    } catch (Exception e) {
        // do nothing for now
    }

    if (authzToken == null) {
        cmsRequest.setStatus(ICMSRequest.UNAUTHORIZED);
        return;
    }

    // after cert validated, check http request.
    if (!method.equalsIgnoreCase("POST")) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    if (len <= 0) {
        resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED);
        return;
    }

    // now process request.

    CMS.debug("ConnectorServlet: process request RA_Id=" + RA_Id);
    try {
        // decode request.
        msg = (IPKIMessage) mReqEncoder.decode(encodedreq);
        // process request
        replymsg = processRequest(RA_Id, raUserId, msg, token);
    } catch (IOException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } catch (EBaseException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
    }

    CMS.debug("ConnectorServlet: done processRequest");

    // encode reply
    try {
        String encodedrep = mReqEncoder.encode(replymsg);

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("text/html");
        resp.setContentLength(encodedrep.length());

        // send reply
        OutputStream out = response.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8");

        writer.write(encodedrep);
        writer.flush();
        writer.close();
        out.flush();
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: error writing e=" + e.toString());
    }
    CMS.debug("ConnectorServlet: send response RA_Id=" + RA_Id);
}

From source file:net.subclient.subsonic.SubsonicConnection.java

/**
 * Performs a connection to the server executing specified method and passing provided parameters.
 * @param method One of the supported methods
 * @param parameters Parametters to be passed to server
 * @param isJson Defines if JSON is expected. It won't be JSON on any method returning binary contents
 * @return The performed HTTP connection InputStream
 * @throws IOException// w  ww. ja v a  2 s. c om
 * @throws InvalidResponseException If the Subsonic servers returns a non parseable response 
 * @throws HTTPException If the server response code is other than 200
 * @throws CompatibilityException 
 */
private InputStream connect(ApiMethod method, List<HttpParameter> parameters, boolean isJson)
        throws IOException, InvalidResponseException, HTTPException, CompatibilityException {
    // Generate URL object
    URL url = new URL(this.serverURL.toString() + method.toString());
    // Append version param to parameters array
    parameters.add(new HttpParameter("v", this.getVersionCompatible(method.getVersion()).toString(true)));

    // Open HTTP/HTTPS Connection
    HttpURLConnection conn = (this.isSSL) ? (HttpsURLConnection) url.openConnection()
            : (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);

    // Add parameters to be sent
    OutputStreamWriter connOut = new OutputStreamWriter(conn.getOutputStream());
    StringBuilder auxParams = new StringBuilder(this.parametersString);
    for (HttpParameter parameter : parameters)
        auxParams.append(String.format("&%s", parameter.toString()));
    //Send parameters to outer connection
    connOut.write(auxParams.toString());
    connOut.flush();
    connOut.close();

    // Check the response code is 200
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
        throw new HTTPException(conn.getResponseCode());
    // Check the content type is application/json
    if (isJson && conn.getContentType().indexOf(JSON_CONTENT_TYPE) == -1)
        throw new InvalidResponseException(conn.getContentType());

    // Return the connection InputStream
    return conn.getInputStream();
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/*from   w  w  w .j  ava  2 s.c  om*/
 *
 * @param multipart DOCUMENT ME!
 * @param vcard DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, vCard vcard, String charset) throws MessagingException {
    String xpath = "/tmp";
    String xcontent = vcard.toString();

    try {
        // write the vCard to a temporary file in UTF-8 format
        File xfile = new File(xpath);
        FileOutputStream xfos = new FileOutputStream(xfile);
        OutputStreamWriter xosw = new OutputStreamWriter(xfos, Charset.defaultCharset().displayName());

        xosw.write(xcontent, 0, xcontent.length());
        xosw.flush();
        xosw.close();
        xfos.close();

        // attach the temporary file to the message
        attach(multipart, xfile, Charset.defaultCharset().displayName());
    } catch (Exception xex) {
        System.out.println("vCard attachment failed: " + xex.toString());
    }
}

From source file:com.truebanana.http.HTTPRequest.java

/**
 * Executes this {@link HTTPRequest} asynchronously. To hook to events or listen to the server response, you must provide an {@link HTTPResponseListener} using {@link HTTPRequest#setHTTPResponseListener(HTTPResponseListener)}.
 *
 * @return This {@link HTTPRequest}/*from ww  w . j  a v  a2 s  . c o m*/
 */
public HTTPRequest executeAsync() {
    Async.executeAsync(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection urlConnection = buildURLConnection();

            // Get request body now if there's a provider
            if (bodyProvider != null) {
                body = bodyProvider.getRequestBody();
            }

            // Update socket factory as needed
            if (urlConnection instanceof HttpsURLConnection) {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection;

                try {
                    httpsURLConnection.setSSLSocketFactory(new FlexibleSSLSocketFactory(trustStore,
                            trustStorePassword, keyStore, keyStorePassword, !verifySSL));
                } catch (GeneralSecurityException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.SECURITY_EXCEPTION);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.KEYSTORE_INVALID);
                    onRequestTerminated();
                    return; // Terminate now
                }

                if (!verifySSL) {
                    httpsURLConnection.setHostnameVerifier(new NoVerifyHostnameVerifier());
                    log("SSL Verification Disabled", "**********");
                }
            }

            log("Endpoint", urlConnection.getURL().toString());
            Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> pair = (Map.Entry) iterator.next();
                urlConnection.addRequestProperty(pair.getKey(), pair.getValue());
                log("Request Header", pair.getKey() + ": " + pair.getValue());
            }
            if (multiPartContent != null) {
                log("Multipart Request Boundary", multiPartContent.getBoundary());
                int counter = 1;
                for (MultiPartContent.Part part : multiPartContent.getParts()) {
                    log("Request Body Part " + counter,
                            "Name: " + part.getName() + "; File Name: " + part.getFileName());

                    Iterator<Map.Entry<String, String>> it = part.getHeaders().entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> pair = (Map.Entry) it.next();
                        log("Request Body Part " + counter + " Header", pair.getKey() + ": " + pair.getValue());
                    }
                }
            } else {
                log("Request Body", body);
            }

            if (mockResponse == null) {
                // Trigger pre-execute since preparations are complete
                onPreExecute();

                // Write our request body
                try {
                    if (multiPartContent != null) {
                        multiPartContent.write(urlConnection.getOutputStream());
                    } else if (body != null) {
                        OutputStream os = urlConnection.getOutputStream();
                        OutputStreamWriter writer = new OutputStreamWriter(os);
                        writer.write(body);
                        writer.flush();
                        writer.close();
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Get the response
                InputStream content;
                try {
                    content = urlConnection.getInputStream();
                    onPostExecute();
                } catch (SocketTimeoutException e) { // Timeout
                    e.printStackTrace();
                    onPostExecute();
                    onRequestError(HTTPRequestError.TIMEOUT);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) { // All other exceptions
                    e.printStackTrace();
                    content = urlConnection.getErrorStream();
                    onPostExecute();
                }

                // Pre-process the response
                final HTTPResponse response = HTTPResponse.from(HTTPRequest.this, urlConnection, content);

                if (response.isConnectionError()) {
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Log response
                log("Response Message", response.getResponseMessage());
                log("Response Content", response.getStringContent());

                // Trigger request completed and return the response
                onRequestCompleted(response);

                // Terminate the connection
                urlConnection.disconnect();

                onRequestTerminated();
            } else {
                onPreExecute();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                onPostExecute();
                log("Response Message", mockResponse.getResponseMessage());
                log("Response Content", mockResponse.getStringContent());
                onRequestCompleted(mockResponse);
                urlConnection.disconnect();
                onRequestTerminated();
            }
        }
    });
    return this;
}

From source file:com.cyberway.issue.crawler.writer.MirrorWriterProcessor.java

public static void createFile(String output, String content) throws Exception {
    // System.out.println(content);
    OutputStreamWriter fw = null;
    PrintWriter out = null;//from  w  ww .  j  a  v  a  2 s .  c  o m
    try {
        fw = new OutputStreamWriter(new FileOutputStream(output), "utf-8");
        out = new PrintWriter(fw);
        out.print(content);
    } catch (Exception ex) {
        throw new Exception(ex);
    } finally {
        if (out != null)
            out.close();
        if (fw != null)
            fw.close();
    }

}

From source file:de.akquinet.engineering.vaadinator.timesheet.service.AbstractCouchDbService.java

protected JSONObject putCouch(String urlPart, JSONObject content)
        throws IOException, MalformedURLException, JSONException {
    HttpURLConnection couchConn = null;
    BufferedReader couchRead = null;
    OutputStreamWriter couchWrite = null;
    try {//  w ww  .  ja  va 2 s  .  c o m
        couchConn = (HttpURLConnection) (new URL(couchUrl + (couchUrl.endsWith("/") ? "" : "/") + urlPart))
                .openConnection();
        couchConn.setRequestMethod("PUT");
        couchConn.setDoInput(true);
        couchConn.setDoOutput(true);
        couchWrite = new OutputStreamWriter(couchConn.getOutputStream());
        couchWrite.write(content.toString());
        couchWrite.flush();
        couchRead = new BufferedReader(new InputStreamReader(couchConn.getInputStream()));
        StringBuffer jsonBuf = new StringBuffer();
        String line = couchRead.readLine();
        while (line != null) {
            jsonBuf.append(line);
            line = couchRead.readLine();
        }
        JSONObject couchObj = new JSONObject(jsonBuf.toString());
        return couchObj;
    } finally {
        if (couchRead != null) {
            couchRead.close();
        }
        if (couchWrite != null) {
            couchWrite.close();
        }
        if (couchConn != null) {
            couchConn.disconnect();
        }
    }
}