Example usage for java.io Writer close

List of usage examples for java.io Writer close

Introduction

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

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream, flushing it first.

Usage

From source file:net.sourceforge.vulcan.spring.SpringFileStore.java

private void writeBeanConfig(File file) throws StoreException {
    Writer writer = null;/*w  ww  . j a v a  2  s.  c  om*/

    try {
        writer = new FileWriter(file);
        beanEncoder.write(writer);
    } catch (IOException e) {
        throw new StoreException(e);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException ignore) {
        }
    }
}

From source file:org.kurento.test.sanity.KurentoJsBase.java

private void createHtmlPages() {
    try {//from   ww w  .j  a v  a  2  s .c  o m
        final String outputFolder = new ClassPathResource("static").getFile().getAbsolutePath()
                + File.separator;

        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        cfg.setClassForTemplateLoading(KurentoJsBase.class, "/templates/");
        Template template = cfg.getTemplate("kurento-client.html.ftl");

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("kurentoUrl", kurentoUrl);

        for (String lib : kurentoLibs) {
            Writer writer = new FileWriter(new File(outputFolder + lib + ".html"));
            data.put("kurentoLib", lib);

            if (lib.contains("utils")) {
                data.put("kurentoObject", "kurentoUtils");
            } else {
                data.put("kurentoObject", "kurentoClient");
            }

            template.process(data, writer);
            writer.flush();
            writer.close();
        }
    } catch (Exception e) {
        Assert.fail("Exception creating templates: " + e.getMessage());
    }

}

From source file:fr.vdl.android.holocolors.HoloColorsDialog.java

private void checkLicence() {
    try {/*from   w w  w .j  a v a2 s. co  m*/
        String userHome = System.getProperty("user.home");
        File holoColorsFolder = new File(userHome + File.separator + ".holocolors");
        File licenceFile = new File(holoColorsFolder, ".licence");
        File noDonationFile = new File(holoColorsFolder, ".nodonation");

        if (noDonationFile.exists()) {
            return;
        }

        int usage = 1;
        boolean showPopup = false;
        if (!holoColorsFolder.exists()) {
            holoColorsFolder.mkdir();
            showPopup = true;
            licenceFile.createNewFile();
        } else {
            Scanner in = new Scanner(new FileReader(licenceFile));
            if (in.hasNextInt()) {
                usage = in.nextInt() + 1;
            }
            in.close();
        }
        if (usage > 10) {
            usage = 1;
            showPopup = true;
        }
        Writer out = new BufferedWriter(new FileWriter(licenceFile));
        out.write(String.valueOf(usage));
        out.close();

        if (showPopup) {
            Object[] donationOption = { "Make a donation", "Maybe later", "No Never" };
            int option = JOptionPane.showOptionDialog(ahcPanel,
                    "Thanks for using Android Holo Colors!\n\nAndroid Holo Colors (website and plugin) is free to use.\nIf you save time and money with it, please make a donation.",
                    "Support Android Holo Colors", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
                    new ImageIcon(getClass().getResource("/icons/H64.png")), donationOption, donationOption[0]);
            if (option == 0) {
                openWebpage(
                        "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=XQSBX55A2Z46U");
            }
            if (option == 2) {
                noDonationFile.createNewFile();
            }
        }
    } catch (Exception e) {
        // no matter, nothing to do
        e.printStackTrace();
    }
}

From source file:it.jugpadova.controllers.EventController.java

@RequestMapping
public ModelAndView badge(HttpServletRequest req, HttpServletResponse res) throws Exception {
    try {/*  ww  w.j a  v  a  2  s.c o  m*/
        String locale = req.getParameter("lang");
        if (StringUtils.isBlank(locale)) {
            locale = (String) req.getAttribute("lang");
        }
        if (StringUtils.isBlank(locale)) {
            locale = "en";
        }
        java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.DEFAULT,
                new Locale(locale));
        String baseUrl = Utilities.getBaseUrl(req);
        EventSearch eventSearch = buildEventSearch(req);
        List<Event> events = eventBo.search(eventSearch);
        boolean showJUGName = Boolean.parseBoolean(req.getParameter("jeb_showJUGName"));
        boolean showCountry = Boolean.parseBoolean(req.getParameter("jeb_showCountry"));
        boolean showDescription = Boolean.parseBoolean(req.getParameter("jeb_showDescription"));
        boolean showParticipants = Boolean.parseBoolean(req.getParameter("jeb_showParticipants"));
        String badgeStyle = req.getParameter("jeb_style");
        String result = eventBo.getBadgeCode(eventBo.getBadgeHtmlCode(events, dateFormat, baseUrl, showJUGName,
                showCountry, showDescription, showParticipants, badgeStyle, locale));
        // flush it in the res
        res.setHeader("Cache-Control", "no-store");
        res.setHeader("Pragma", "no-cache");
        res.setDateHeader("Expires", 0);
        res.setContentType("text/javascript");
        ServletOutputStream resOutputStream = res.getOutputStream();
        Writer writer = new OutputStreamWriter(resOutputStream, "UTF-8");
        writer.write(result);
        writer.flush();
        writer.close();
    } catch (Exception exception) {
        logger.error("Error producing badge", exception);
        throw exception;
    }
    return null;
}

From source file:com.panet.imeta.trans.step.errorhandling.AbstractFileErrorHandler.java

private void close(Writer outputStreamWriter) throws KettleException {
    if (outputStreamWriter != null) {
        try {//from   w ww. j a va  2s .  c om
            outputStreamWriter.flush();
        } catch (IOException exception) {
            log.logError(Messages.getString("AbstractFileErrorHandler.Log.CouldNotFlushContentToFile"), //$NON-NLS-1$
                    exception.getLocalizedMessage());
        }
        try {
            outputStreamWriter.close();
        } catch (IOException exception) {
            throw new KettleException(
                    Messages.getString("AbstractFileErrorHandler.Exception.CouldNotCloseFile"), exception); //$NON-NLS-1$
        } finally {
            outputStreamWriter = null;
        }
    }
}

From source file:net.chaosserver.timelord.data.XmlDataReaderWriter.java

/**
 * Converts and old XML file from the "TimeTracker" application into
 * the new version with "Timelord" data.
 *
 * @param oldfile the old file from TimeTracker
 * @param datafile the new file for Timelord
 * @throws IOException indicates and error processing the file
 *//*from   w w w . j av a2 s  .  c om*/
protected void convertTrackerToLord(File oldfile, File datafile) throws IOException {

    BufferedReader reader = new BufferedReader(new FileReader(oldfile));
    Writer writer = new BufferedWriter(new FileWriter(datafile));

    String line = reader.readLine();
    while (line != null) {
        line = line.replace("timetracker", "timelord");
        line = line.replace("TimeTracker", "Timelord");
        writer.write(line);
        line = reader.readLine();
    }

    reader.close();
    writer.close();
}

From source file:eu.prestoprime.p4gui.connection.SearchConnection.java

public static String solrSuggest(P4Service service, final String term) {
    Writer writer = new StringWriter();

    String results = "";
    try {//from  ww  w  . j av a  2s . c o  m
        StringBuilder sb = new StringBuilder();
        sb.append(service.getURL());
        sb.append(SUGGEST_URI);
        sb.append("?term=");
        sb.append(term);
        String path = sb.toString();

        logger.debug("Query to P4WS:\n" + path);

        P4HttpClient client = new P4HttpClient(service.getUserID());

        client.getParams().setParameter("http.protocol.content-charset", "UTF-8");

        HttpRequestBase request = new HttpGet(path);
        HttpResponse response = client.executeRequest(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream is = entity.getContent();
            if (is != null) {
                char[] buffer = new char[1024];

                Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
                is.close();
            }
        }
        results = writer.toString();
        EntityUtils.consume(entity);
        writer.close();
    } catch (Exception e) {
        logger.error(e.getMessage());
        logger.error("Either the query was invalid or P4WS could not be accessed.");
        results = null;
    }
    return results;
}

From source file:com.adito.notification.smtp.SMTPMessageSink.java

private void send(Message message, Recipient recipient) throws Exception {
    UserDatabase userDatabase = UserDatabaseManager.getInstance().getUserDatabase(recipient.getRealmName());
    User user = userDatabase.getAccount(recipient.getRecipientAlias());

    String sender = Property.getProperty(new SystemConfigKey("smtp.senderAddress"));
    client.setSender(sender);/*ww w .ja v a 2s  .c o  m*/
    client.addRecipient(user.getEmail());
    Writer writer = client.sendMessageData();
    if (writer == null) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Failed to send message data to " + user.getEmail());
        }
        return;
    }

    SimpleSMTPHeader header = new SimpleSMTPHeader(sender, user.getEmail(), message.getSubject());
    writer.write(header.toString());
    writer.write(message.getContent());
    writer.close();
    if (!client.completePendingCommand()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Failed to send message data to " + user.getEmail());
        }
    }
}

From source file:org.lieuofs.extraction.commune.mutation.ExtracteurMutation.java

public void extraireMutation(Date depuis, Date jusqua, Writer writer) throws IOException {
    MutationCommuneCritere critere = new MutationCommuneCritere();
    if (null != depuis) {
        critere.setDateDebut(depuis);//from   w ww. j a v  a 2  s . c  om
    }
    if (null != jusqua) {
        critere.setDateFin(jusqua);
    }
    List<IMutationCommune> mutations = gestionnaire.rechercherMutation(critere);
    for (IMutationCommune mut : mutations) {
        String mutStr = mutWriter.ecrireMutation(mut);
        if (null != mutStr) {
            writer.append(mutStr);
        }
    }
    writer.close();
}

From source file:hudson.model.LargeText.java

/**
 * Implements the progressive text handling.
 * This method is used as a "web method" with progressiveText.jelly.
 *//*ww w .  j  a v  a  2 s.c o m*/
public void doProgressText(StaplerRequest req, StaplerResponse rsp) throws IOException {
    rsp.setContentType("text/plain");
    rsp.setCharacterEncoding("UTF-8");
    rsp.setStatus(HttpServletResponse.SC_OK);

    if (!source.exists()) {
        // file doesn't exist yet
        rsp.addHeader("X-Text-Size", "0");
        rsp.addHeader("X-More-Data", "true");
        return;
    }

    long start = 0;
    String s = req.getParameter("start");
    if (s != null)
        start = Long.parseLong(s);

    if (source.length() < start)
        start = 0; // text rolled over

    CharSpool spool = new CharSpool();
    long r = writeLogTo(start, spool);

    rsp.addHeader("X-Text-Size", String.valueOf(r));
    if (!completed)
        rsp.addHeader("X-More-Data", "true");

    // when sending big text, try compression. don't bother if it's small
    Writer w;
    if (r - start > 4096)
        w = rsp.getCompressedWriter(req);
    else
        w = rsp.getWriter();
    spool.writeTo(new LineEndNormalizingWriter(w));
    w.close();

}