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:com.cloudera.sqoop.io.TestLobFile.java

public void testSeekToRecord() throws Exception {
    // Seek past the first two records and read the third.

    Path p = new Path(TEMP_BASE_DIR, "seek.lob");
    String[] records = { "this is the first record!", "here comes record number two. It is a bit longer.",
            "this is the third record. we can read it.", };

    // Write the file and memorize when the third record starts.
    LobFile.Writer writer = LobFile.create(p, conf, true);

    int recNum = 0;
    long rec3Start = 0;
    for (String r : records) {
        Writer w = writer.writeClobRecord(r.length());
        w.write(r);//from w  w w  .  j  a v a  2  s.  c o m
        w.close();
        writer.finishRecord();
        if (recNum == 1) {
            rec3Start = writer.tell();
            LOG.info("Record three start: " + rec3Start);
        }
        recNum++;
    }

    writer.close();

    // Now reopen the file for read, seek to the third record, and get it.
    LobFile.Reader reader = LobFile.open(p, conf);
    reader.seek(rec3Start);
    assertTrue(reader.next());
    assertTrue(reader.isRecordAvailable());
    assertEquals(rec3Start, reader.getRecordOffset());

    Reader r = reader.readClobRecord();
    CharBuffer buf = CharBuffer.allocate(records[2].length());
    r.read(buf);
    r.close();
    char[] chars = buf.array();
    String s = new String(chars);
    assertEquals(records[2], s);

    r.close();
    reader.close();
}

From source file:org.hoteia.qalingo.app.business.job.email.AbstractEmailItemProcessor.java

public Email process(CommonProcessIndicatorItemWrapper<Long, Email> wrapper) throws Exception {
    Email email = wrapper.getItem();/*from   w  w w . ja v a  2  s  . c  om*/
    Blob emailcontent = email.getEmailContent();

    InputStream is = emailcontent.getBinaryStream();
    ObjectInputStream oip = new ObjectInputStream(is);
    Object object = oip.readObject();

    MimeMessagePreparatorImpl mimeMessagePreparator = (MimeMessagePreparatorImpl) object;

    oip.close();
    is.close();

    try {
        // SANITY CHECK
        if (email.getStatus().equals(Email.EMAIl_STATUS_PENDING)) {

            if (mimeMessagePreparator.isMirroringActivated()) {
                String filePathToSave = mimeMessagePreparator.getMirroringFilePath();
                File file = new File(filePathToSave);

                // SANITY CHECK : create folders
                String absoluteFolderPath = file.getParent();
                File absolutePathFile = new File(absoluteFolderPath);
                if (!absolutePathFile.exists()) {
                    absolutePathFile.mkdirs();
                }

                if (!file.exists()) {
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,
                            Constants.UTF8);
                    Writer out = new BufferedWriter(outputStreamWriter);
                    if (StringUtils.isNotEmpty(mimeMessagePreparator.getHtmlContent())) {
                        out.write(mimeMessagePreparator.getHtmlContent());
                    } else {
                        out.write(mimeMessagePreparator.getPlainTextContent());
                    }

                    try {
                        if (out != null) {
                            out.close();
                        }
                    } catch (IOException e) {
                        logger.debug("Cannot close the file", e);
                    }
                } else {
                    logger.debug("File already exists : " + filePathToSave);
                }
            }

            mailSender.send(mimeMessagePreparator);
            email.setStatus(Email.EMAIl_STATUS_SENDED);
        } else {
            logger.warn("Batch try to send email was already sended!");
        }

    } catch (Exception e) {
        logger.error("Fail to send email! Exception is save in database, id:" + email.getId());
        email.setStatus(Email.EMAIl_STATUS_ERROR);
        emailService.handleEmailException(email, e);
    }

    return email;
}

From source file:jp.go.aist.six.util.core.xml.castor.CastorXmlMapper.java

public void marshal(final Object obj, final Writer writer) {
    Writer w = ((writer instanceof BufferedWriter) ? writer : (new BufferedWriter(writer)));
    try {/*  w  w  w. j av a  2 s  .c  o  m*/
        _marshaller.marshal(obj, new StreamResult(w));
        //@throws IOException
        //@throws XmlMappingException
    } catch (Exception ex) {
        throw new XmlException(ex);
    } finally {
        try {
            writer.close();
        } catch (IOException ex) {
            //ignorable
        }
    }
}

From source file:com.github.mavogel.ilias.printer.VelocityOutputPrinter.java

/**
 * Prints the header, content and output to the given print stream with the default template from the classpath.
 *
 * @param outputType the desired output type. @see {@link OutputType}
 * @param contextMap the context for velocity
 * @throws Exception in case of a error, so the caller can handle it
 *///  w ww.  j a  va 2s. c  o m
private static void printWithDefaultTemplate(final OutputType outputType, final Map<String, Object> contextMap)
        throws Exception {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();

    Writer writer = null;
    final String templateName = outputType.getDefaultTemplateLocation();
    try {
        VelocityContext context = new VelocityContext();
        contextMap.forEach((k, v) -> context.put(k, v));
        Template template = ve.getTemplate(templateName, "UTF-8");
        writer = new BufferedWriter(createFileWriter(outputType, templateName));

        template.merge(context, writer);
        writer.flush();
    } catch (ResourceNotFoundException rnfe) {
        LOG.error("Couldn't find the template with name '" + templateName + "'");
        throw new Exception(rnfe.getMessage());
    } catch (ParseErrorException pee) {
        LOG.error("Syntax error: problem parsing the template ' " + templateName + "': " + pee.getMessage());
        throw new Exception(pee.getMessage());
    } catch (MethodInvocationException mie) {
        LOG.error(
                "An invoked method on the template '" + templateName + "' threw an error: " + mie.getMessage());
        throw new Exception(mie.getMessage());
    } catch (Exception e) {
        LOG.error("Error: " + e.getMessage());
        LOG.error("Cause: " + e.getCause());
        Arrays.stream(e.getStackTrace()).forEach(LOG::error);
        throw e;
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:com.adrguides.model.Guide.java

private void saveTextToFile(File f, String text) throws IOException {

    Writer filewriter = null;
    try {/* w  w  w  . ja va 2 s.  c  o m*/
        filewriter = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
        filewriter.append(text);
    } finally {
        if (filewriter != null) {
            try {
                filewriter.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.ssn.listener.SSNHiveAlbumSelectionListner.java

private void getAlbumMedia(String accessToken, int pageCount, SSNAlbum album) {
    try {//  w  ww. ja va 2 s  .c o m
        String urlString = SSNConstants.SSN_WEB_HOST + "api/albums/view/%s/page:%s.json";
        URL url = new URL(String.format(urlString, album.getId(), pageCount));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String input = "access_token=%s";
        input = String.format(input, URLEncoder.encode(accessToken, "UTF-8"));

        OutputStream os = conn.getOutputStream();
        Writer writer = new OutputStreamWriter(os, "UTF-8");
        writer.write(input);
        writer.close();
        os.close();

        int status = conn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

            String output;
            StringBuilder response = new StringBuilder();

            while ((output = br.readLine()) != null) {
                response.append(output);
            }
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> outputJSON = mapper.readValue(response.toString(), Map.class);

            boolean success = (Boolean) outputJSON.get("success");
            if (success) {
                List<Map<String, Object>> mediaFileListJSON = (List<Map<String, Object>>) outputJSON
                        .get("MediaFile");
                ssnHiveAlbumAllMedia = new HashMap<String, SSNAlbumMedia>();
                if (mediaFileListJSON.size() > 0) {
                    for (Map<String, Object> mediaFileJSON : mediaFileListJSON) {
                        SSNAlbumMedia ssnAlbumMedia = mapper.readValue(mapper.writeValueAsString(mediaFileJSON),
                                SSNAlbumMedia.class);
                        String name = "";
                        String[] videoSupported = SSNConstants.SSN_VIDEO_FORMAT_SUPPORTED;

                        final List<String> videoSupportedList = Arrays.asList(videoSupported);
                        String fileType = ssnAlbumMedia.getFile_type()
                                .substring(ssnAlbumMedia.getFile_type().lastIndexOf("/") + 1,
                                        ssnAlbumMedia.getFile_type().length())
                                .toUpperCase();

                        if (videoSupportedList.contains(fileType)) {
                            name = ssnAlbumMedia.getFile_name();
                        } else {
                            name = ssnAlbumMedia.getThumbnail().substring(
                                    ssnAlbumMedia.getThumbnail().lastIndexOf("/") + 1,
                                    ssnAlbumMedia.getThumbnail().length());
                        }

                        File mediaFile = new File(
                                SSNHelper.getSsnTempDirPath() + album.getName() + File.separator + name);
                        ssnHiveAlbumAllMedia.put(name, ssnAlbumMedia);

                        int lastModificationComparision = -1;
                        if (mediaFile.exists()) {
                            String mediaFileModifiedDate = SSNDao.getSSNMetaData(mediaFile.getAbsolutePath())
                                    .getModiFied();
                            String ssnMediaModifiedDate = ssnAlbumMedia.getModified();
                            lastModificationComparision = compareDates(mediaFileModifiedDate,
                                    ssnMediaModifiedDate);
                        }

                        if ((!mediaFile.exists() && !ssnAlbumMedia.isIs_deleted())
                                || (lastModificationComparision < 0)) {
                            if (ssnAlbumMedia.getFile_url() != null && !ssnAlbumMedia.getFile_url().isEmpty()
                                    && !ssnAlbumMedia.getFile_url().equalsIgnoreCase("false")) {
                                try {
                                    URL imageUrl = null;
                                    if (videoSupportedList.contains(fileType)) {
                                        imageUrl = new URL(ssnAlbumMedia.getFile_url().replaceAll(" ", "%20"));
                                    } else {
                                        imageUrl = new URL(ssnAlbumMedia.getThumbnail().replaceAll(" ", "%20"));
                                    }
                                    FileUtils.copyURLToFile(imageUrl, mediaFile);
                                } catch (IOException e) {
                                    logger.error(e);
                                }
                            }
                        }
                    }
                }

                Map<String, Object> pagingJSON = (Map<String, Object>) outputJSON.get("paging");
                if (pagingJSON != null) {
                    boolean hasNextPage = Boolean.parseBoolean(pagingJSON.get("nextPage") + "");
                    if (hasNextPage) {
                        getAlbumMedia(accessToken, ++pageCount, album);
                    }
                }
            }
        }

    } catch (EOFException e) {
        logger.error(e);
        SSNMessageDialogBox dialogBox = new SSNMessageDialogBox();
        dialogBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                "No Response from server.");
    } catch (Exception ee) {
        logger.error(ee);
    }
}

From source file:com.sun.syndication.propono.atom.server.AtomServlet.java

/**
 * Handles an Atom GET by calling handler and writing results to response.
 *///  w ww.j av  a 2 s.  co m
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.debug("Entering");
    AtomHandler handler = createAtomRequestHandler(req, res);
    String userName = handler.getAuthenticatedUsername();
    if (userName != null) {
        AtomRequest areq = new AtomRequestImpl(req);
        try {
            if (handler.isAtomServiceURI(areq)) {
                // return an Atom Service document
                AtomService service = handler.getAtomService(areq);
                Document doc = service.serviceToDocument();
                res.setContentType("application/atomsvc+xml; charset=utf-8");
                Writer writer = res.getWriter();
                XMLOutputter outputter = new XMLOutputter();
                outputter.setFormat(Format.getPrettyFormat());
                outputter.output(doc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isCategoriesURI(areq)) {
                Categories cats = handler.getCategories(areq);
                res.setContentType("application/xml");
                Writer writer = res.getWriter();
                Document catsDoc = new Document();
                catsDoc.setRootElement(cats.categoriesToElement());
                XMLOutputter outputter = new XMLOutputter();
                outputter.output(catsDoc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isCollectionURI(areq)) {
                // return a collection
                Feed col = handler.getCollection(areq);
                col.setFeedType(FEED_TYPE);
                WireFeedOutput wireFeedOutput = new WireFeedOutput();
                Document feedDoc = wireFeedOutput.outputJDom(col);
                res.setContentType("application/atom+xml; charset=utf-8");
                Writer writer = res.getWriter();
                XMLOutputter outputter = new XMLOutputter();
                outputter.setFormat(Format.getPrettyFormat());
                outputter.output(feedDoc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isEntryURI(areq)) {
                // return an entry
                Entry entry = handler.getEntry(areq);
                if (entry != null) {
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");
                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(entry, writer);
                    writer.close();
                } else {
                    res.setStatus(HttpServletResponse.SC_NOT_FOUND);
                }
            } else if (handler.isMediaEditURI(areq)) {
                AtomMediaResource entry = handler.getMediaResource(areq);
                res.setContentType(entry.getContentType());
                res.setContentLength((int) entry.getContentLength());
                Utilities.copyInputToOutput(entry.getInputStream(), res.getOutputStream());
                res.getOutputStream().flush();
                res.getOutputStream().close();
            } else {
                res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (AtomException ae) {
            res.sendError(ae.getStatus(), ae.getMessage());
            log.debug("ERROR processing GET", ae);
        } catch (Exception e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            log.debug("ERROR processing GET", e);
        }
    } else {
        res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    log.debug("Exiting");
}

From source file:appeng.services.export.MinecraftItemCSVExporter.java

@Override
public void export() {
    final Iterable<Item> items = this.itemRegistry.typeSafeIterable();
    final List<Item> itemList = Lists.newArrayList(items);

    final List<String> lines = Lists.transform(itemList,
            new ItemRowExtractFunction(this.itemRegistry, this.mode));

    final Joiner newLineJoiner = Joiner.on('\n');
    final Joiner newLineJoinerIgnoringNull = newLineJoiner.skipNulls();
    final String joined = newLineJoinerIgnoringNull.join(lines);

    final File file = new File(this.exportDirectory, ITEM_CSV_FILE_NAME);

    try {// w w w  .j  a v  a2  s .  co  m
        FileUtils.forceMkdir(this.exportDirectory);

        final Writer writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8")));

        final String header = this.mode == ExportMode.MINIMAL ? MINIMAL_HEADER : VERBOSE_HEADER;
        writer.write(header);
        writer.write("\n");
        writer.write(joined);
        writer.flush();
        writer.close();

        AELog.info(EXPORT_SUCCESSFUL_MESSAGE, lines.size(), ITEM_CSV_FILE_NAME);
    } catch (final IOException e) {
        AELog.warn(EXPORT_UNSUCCESSFUL_MESSAGE);
        AELog.debug(e);
    }
}

From source file:ded.model.Diagram.java

/** Write this diagram to the specified file. */
public void saveToFile(String fname) throws Exception {
    JSONObject serialized = this.toJSON();
    FileOutputStream fos = new FileOutputStream(fname);
    try {//from w ww.  j a v a 2  s .  c  om
        Writer w = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
        try {
            serialized.write(w, 2, 0);
            w.append('\n');
        } finally {
            w.close();
            fos = null;
        }
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}

From source file:Repackage.java

void writeFile(File f, StringBuffer chars) throws IOException {
    f.getParentFile().mkdirs();/*  w w w .  ja v a  2  s.  co  m*/

    OutputStream out = new FileOutputStream(f);
    Writer w = new OutputStreamWriter(out);
    Reader r = new StringReader(chars.toString());

    copy(r, w);

    r.close();
    w.close();
    out.close();
}