Example usage for java.io StringWriter close

List of usage examples for java.io StringWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a StringWriter has no effect.

Usage

From source file:com.cloudbees.plugins.credentials.CredentialsStoreAction.java

/**
 * Creates a domain.// w w w.  ja v a2s.co  m
 *
 * @param req the request.
 * @return the response.
 * @throws ServletException if something goes wrong.
 * @throws IOException      if something goes wrong.
 */
@SuppressWarnings("unused") // stapler web method
@Restricted(NoExternalUse.class)
@RequirePOST
public HttpResponse doCreateDomain(StaplerRequest req) throws ServletException, IOException {
    getStore().checkPermission(MANAGE_DOMAINS);
    if (!getStore().isDomainsModifiable()) {
        return HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }
    String requestContentType = req.getContentType();
    if (requestContentType == null) {
        throw new Failure("No Content-Type header set");
    }

    if (requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml")) {
        final StringWriter out = new StringWriter();
        try {
            XMLUtils.safeTransform(new StreamSource(req.getReader()), new StreamResult(out));
            out.close();
        } catch (TransformerException e) {
            throw new IOException("Failed to parse credential", e);
        } catch (SAXException e) {
            throw new IOException("Failed to parse credential", e);
        }

        Domain domain = (Domain) Items.XSTREAM
                .unmarshal(new XppDriver().createReader(new StringReader(out.toString())));
        if (getStore().addDomain(domain)) {
            return HttpResponses.ok();
        } else {
            return HttpResponses.status(HttpServletResponse.SC_CONFLICT);
        }
    } else {
        JSONObject data = req.getSubmittedForm();
        Domain domain = req.bindJSON(Domain.class, data);
        String domainName = domain.getName();
        if (domainName != null && getStore().addDomain(domain)) {
            return HttpResponses.redirectTo("./domain/" + Util.rawEncode(domainName));

        }
        return HttpResponses.redirectToDot();
    }
}

From source file:com.omertron.themoviedbapi.tools.WebBrowser.java

public static String request(URL url, String jsonBody, boolean isDeleteRequest) throws MovieDbException {

    StringWriter content = null;

    try {//w  w  w .j  ava 2 s.co  m
        content = new StringWriter();

        BufferedReader in = null;
        HttpURLConnection cnx = null;
        OutputStreamWriter wr = null;
        try {
            cnx = (HttpURLConnection) openProxiedConnection(url);

            // If we get a null connection, then throw an exception
            if (cnx == null) {
                throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR,
                        "No HTTP connection could be made.", url);
            }

            if (isDeleteRequest) {
                cnx.setDoOutput(true);
                cnx.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                cnx.setRequestMethod("DELETE");
            }

            sendHeader(cnx);

            if (StringUtils.isNotBlank(jsonBody)) {
                cnx.setDoOutput(true);
                wr = new OutputStreamWriter(cnx.getOutputStream());
                wr.write(jsonBody);
            }

            readHeader(cnx);

            // http://stackoverflow.com/questions/4633048/httpurlconnection-reading-response-content-on-403-error
            if (cnx.getResponseCode() >= 400) {
                in = new BufferedReader(new InputStreamReader(cnx.getErrorStream(), getCharset(cnx)));
            } else {
                in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx)));
            }

            String line;
            while ((line = in.readLine()) != null) {
                content.write(line);
            }
        } finally {
            if (wr != null) {
                wr.flush();
                wr.close();
            }

            if (in != null) {
                in.close();
            }

            if (cnx instanceof HttpURLConnection) {
                ((HttpURLConnection) cnx).disconnect();
            }
        }
        return content.toString();
    } catch (IOException ex) {
        throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, null, url, ex);
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException ex) {
                LOG.debug("Failed to close connection: " + ex.getMessage());
            }
        }
    }
}

From source file:org.eclipse.virgo.ide.bundlor.internal.core.BundlorProjectBuilder.java

/**
 * Merges the manifests.//from  w  ww  .  ja  va 2s  .com
 */
private void mergeManifests(final IJavaProject javaProject, BundleManifest manifest,
        BundleManifest testManifest) throws CoreException {

    // Check if there is a manifest
    if (manifest == null) {
        return;
    }

    BundleManifest cleanTestManifest = null;
    if (testManifest != null) {

        /*
         * As the test manifest should not contain imported packages, bundles and libraries those need to be
         * removed. Furthermore there shouldn't be any bundlor related headers in the manifest.
         */
        cleanTestManifest = BundleManifestFactory.createBundleManifest();
        cleanTestManifest.setBundleManifestVersion(2);
        if (testManifest.getImportBundle() != null
                && testManifest.getImportBundle().getImportedBundles() != null
                && testManifest.getImportBundle().getImportedBundles().size() > 0) {
            cleanTestManifest.getImportBundle().getImportedBundles()
                    .addAll(testManifest.getImportBundle().getImportedBundles());
        }
        if (testManifest.getImportLibrary() != null
                && testManifest.getImportLibrary().getImportedLibraries() != null
                && testManifest.getImportLibrary().getImportedLibraries().size() > 0) {
            cleanTestManifest.getImportLibrary().getImportedLibraries()
                    .addAll(testManifest.getImportLibrary().getImportedLibraries());
        }
        for (ImportedPackage packageImport : testManifest.getImportPackage().getImportedPackages()) {
            boolean notImported = true;
            for (ImportedPackage manifestPackageImport : manifest.getImportPackage().getImportedPackages()) {
                if (manifestPackageImport.getPackageName().equals(packageImport.getPackageName())) {
                    notImported = false;
                    break;
                }
            }

            if (notImported) {
                boolean skip = false;
                for (ExportedPackage packageExport : manifest.getExportPackage().getExportedPackages()) {
                    String packageImportName = packageImport.getPackageName();
                    if (packageExport.getPackageName().equals(packageImportName)) {
                        skip = true;
                    }
                }
                if (!skip) {
                    cleanTestManifest.getImportPackage().getImportedPackages().add(packageImport);
                }
            }
        }
    }

    /*
     * Never ever import packages that are exported already; we need this as the STS integrated support will
     * sometimes try to import certain packages that are usually exported already if the classpath is incomplete.
     */
    List<ImportedPackage> importedPackagesCopy = new ArrayList<ImportedPackage>(
            manifest.getImportPackage().getImportedPackages());
    for (ExportedPackage packageExport : manifest.getExportPackage().getExportedPackages()) {
        for (ImportedPackage packageImport : importedPackagesCopy) {
            if (packageExport.getPackageName().equals(packageImport.getPackageName())) {

                boolean remove = true;
                // It might still be that the user explicitly wants the
                // package import in the template.mf
                for (ImportedPackage templatePackageImport : this.templatePackageImports) {
                    if (packageExport.getPackageName().equals(templatePackageImport.getPackageName())) {
                        remove = false;
                        break;
                    }
                }
                if (remove) {
                    manifest.getImportPackage().getImportedPackages().remove(packageImport);
                    break;
                }
            }
        }
    }

    IResource manifestResource = BundleManifestUtils.locateManifest(javaProject, false);
    if (manifestResource == null) {
        manifestResource = BundleManifestUtils.getFirstPossibleManifestFile(getProject(), false);
    }
    IResource testManifestResource = BundleManifestUtils.locateManifest(javaProject, true);
    if (testManifestResource == null) {
        testManifestResource = BundleManifestUtils.getFirstPossibleManifestFile(getProject(), true);
    }

    boolean formatPref = getProjectPreferences(javaProject.getProject()).getBoolean(
            BundlorCorePlugin.FORMAT_GENERATED_MANIFESTS_KEY,
            BundlorCorePlugin.FORMAT_GENERATED_MANIFESTS_DEFAULT);
    if (manifestResource != null && manifestResource instanceof IFile) {
        try {
            StringWriter writer = new StringWriter();
            manifest.write(writer);
            InputStream manifestStream = new ByteArrayInputStream(writer.toString().getBytes());
            if (formatPref) {
                manifestStream = formatManifest((IFile) manifestResource, manifestStream);
            }
            IStatus valid = ResourcesPlugin.getWorkspace()
                    .validateEdit(new IFile[] { (IFile) manifestResource }, IWorkspace.VALIDATE_PROMPT);
            if (valid.isOK()) {
                ((IFile) manifestResource).setContents(manifestStream, IResource.FORCE | IResource.KEEP_HISTORY,
                        new NullProgressMonitor());
            }
            writer.close();
            manifestStream.close();
        } catch (IOException e) {
        }

    }
    if (testManifestResource != null && testManifestResource instanceof IFile) {
        try {
            StringWriter writer = new StringWriter();
            cleanTestManifest.write(writer);
            InputStream testManifestStream = new ByteArrayInputStream(writer.toString().getBytes());
            if (formatPref) {
                testManifestStream = formatManifest((IFile) testManifestResource, testManifestStream);
            }
            IStatus valid = ResourcesPlugin.getWorkspace()
                    .validateEdit(new IFile[] { (IFile) testManifestResource }, IWorkspace.VALIDATE_PROMPT);
            if (valid.isOK()) {
                ((IFile) testManifestResource).setContents(testManifestStream,
                        IResource.FORCE | IResource.KEEP_HISTORY, new NullProgressMonitor());
            }
            writer.close();
            testManifestStream.close();
        } catch (IOException e) {
        }
    }
}

From source file:edu.ucsd.library.dams.jhove.MyJhoveBase.java

/**
 * Note: This code could be initialized only once in the constructor
 * but based on the comments from Jhove code it is not advisable to do so
 * /*  w  w  w  . j  a v  a2 s.c  o m*/
 * The JHOVE engine, providing all base services necessary to build an
  * application.   More than one JhoveBase may be instantiated and process files in
  * concurrent threads.  Any one instance must not be multithreaded.
  * @return
 * @throws Exception 
 * @throws Exception 
 */
/*private synchronized void initJhoveEngine() throws Exception {
   if(jhoveconf == null)
 throw new Exception("Configuration file for the Jhove Engine has not set yet.");
   if(_jebase == null){
 String saxClass = MyJhoveBase.getSaxClassFromProperties();
 try {
    _jebase = new MyJhoveBase();
    _jebase.init(MyJhoveBase.jhoveconf, saxClass);
 } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    _jebase = null;
    throw e;
 }
   }
}*/

public JhoveInfo getJhoveMetaData(String srcFileName) throws Exception {
    File file = new File(srcFileName);
    JhoveInfo dataObj = new JhoveInfo();
    dataObj.setLocalFileName(file.getName());
    dataObj.setFilePath(file.getParent());
    /*if (_jebase == null) {
       initJhoveEngine();          
    }*/
    resetAbort();
    if (!file.canRead()) {
        String emsg = "Can't read file for Jhove analysis: " + dataObj.getFilePath() + File.separatorChar
                + dataObj.getLocalFileName();
        throw new Exception(emsg);
    }
    JhoveAnalysisProgress jprogress = new JhoveAnalysisProgress();
    jprogress.set_filesize(file.length());
    setCallback(jprogress);
    String[] paths = new String[1];
    paths[0] = file.getAbsolutePath();
    setShowRawFlag(true);
    setChecksumFlag(true);
    //      _jebase.setLogLevel("ALL");

    StringWriter swriter = new StringWriter();
    PrintWriter kwriter = new PrintWriter(swriter);
    App _jeapp = new App(MyJhoveBase.jhvname, MyJhoveBase.jvhrel, MyJhoveBase.jhvdate, null,
            MyJhoveBase.jvhrights); //Moved here to make it thread safe

    //Module selection
    Module defaultModule = null;
    int indx = srcFileName.lastIndexOf(".");
    if (indx >= 0) {
        String ext = srcFileName.substring(indx);
        String selectedModule = null;
        if (_moduleMap.containsKey(ext))
            selectedModule = (String) _moduleMap.get(ext);
        else if (ext.indexOf("out") >= 0 || Arrays.asList(BYTESTREAM_MODULE_EXTS).contains(ext.toLowerCase()))
            selectedModule = BYTESTREAM;

        if (StringUtils.isNotBlank(selectedModule))
            defaultModule = (Module) getModuleMap().get(selectedModule.toLowerCase());
    }

    try {
        dispatch(_jeapp, defaultModule, null, // AboutHandler
                new XmlHandler(), kwriter, // output
                paths);
        parseXml(dataObj, swriter);
        if (!dataObj.getValid()) {
            swriter.close();
            kwriter.close();
            swriter = new StringWriter();
            kwriter = new PrintWriter(swriter);
            Module bytestreamModule = (Module) getModuleMap().get("bytestream");

            // keep the original formatName and mimeType
            String mimeType = dataObj.getMIMEtype();
            String formatName = dataObj.getFormat();
            dispatch(_jeapp, bytestreamModule, null, // AboutHandler
                    new XmlHandler(), kwriter, // output
                    paths);
            parseXml(dataObj, swriter);
            if (defaultModule != null) {
                if (mimeType != null && mimeType.length() > 0)
                    dataObj.setMIMEtype(mimeType);
                if (formatName != null && formatName.length() > 0)
                    dataObj.setFormat(formatName);
            }
        }
    } catch (Exception e) {
        log.warn("Jhove analysis error", e);
        if (srcFileName.endsWith(".pdf") || srcFileName.endsWith(".PDF")) {
            //Accept PDF file.
            swriter.close();
            kwriter.close();
            swriter = new StringWriter();
            kwriter = new PrintWriter(swriter);
            Module bytestreamModule = (Module) getModuleMap().get("bytestream");

            dispatch(_jeapp, bytestreamModule, null, // AboutHandler
                    new XmlHandler(), kwriter, // output
                    paths);
            parseXml(dataObj, swriter);
        } else
            throw new Exception(e);
    } finally {
        swriter.close();
        kwriter.close();
    }
    if (!dataObj.getValid())
        throw new Exception("Unable to extract file: " + srcFileName);

    if (indx > 0) {
        String fileExt = srcFileName.substring(indx);
        if (MEDIA_FILES.indexOf(fileExt.toLowerCase()) >= 0) {
            Map<String, String> ffmpegInfo = FfmpegUtil.executeInquiry(srcFileName, ffmpegCommand);
            dataObj.setDuration(ffmpegInfo.get("duration"));

            String audioFormat = ffmpegInfo.get("audio");
            String videoFormat = ffmpegInfo.get("video");
            if (dataObj.getQuality() == null || dataObj.getQuality().equals("")) {
                if (audioFormat != null && videoFormat != null) {
                    dataObj.setQuality("video: " + videoFormat + "; audio: " + audioFormat);
                } else if (audioFormat != null) {
                    dataObj.setQuality(audioFormat);
                } else if (videoFormat != null && videoFormat.startsWith("png, ")) {
                    dataObj.setQuality(videoFormat.substring(5));
                } else if (videoFormat != null) {
                    dataObj.setQuality(videoFormat);
                }
            }
        }
    }
    return dataObj;
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
*
* @param xmlObj/*from w  ww . ja va  2  s  . com*/
* @return a string containing the xml representation of the entityDescriptor
*/
public static String serializeObject(XMLObject xmlObj) {
    StringWriter stringWriter = new StringWriter();
    String stringRepresentation = "";
    try {
        DocumentBuilder builder;
        DocumentBuilderFactory factory = DocumentBuilderFactoryUtil.getSecureDocumentBuilderFactory();

        builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Marshaller out = Configuration.getMarshallerFactory().getMarshaller(xmlObj);
        out.marshall(xmlObj, document);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult streamResult = new StreamResult(stringWriter);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, streamResult);
    } catch (ParserConfigurationException pce) {
        LOG.info("ERROR : parser error", pce.getMessage());
        LOG.debug("ERROR : parser error", pce);
    } catch (TransformerConfigurationException tce) {
        LOG.info("ERROR : transformer configuration error", tce.getMessage());
        LOG.debug("ERROR : transformer configuration error", tce);
    } catch (TransformerException te) {
        LOG.info("ERROR : transformer error", te.getMessage());
        LOG.debug("ERROR : transformer error", te);
    } catch (MarshallingException me) {
        LOG.info("ERROR : marshalling error", me.getMessage());
        LOG.debug("ERROR : marshalling error", me);
    } finally {
        try {
            stringWriter.close();
            stringRepresentation = stringWriter.toString();
        } catch (IOException ioe) {
            LOG.warn("ERROR when closing the marshalling stream {}", ioe);
        }
    }
    return stringRepresentation;
}

From source file:net.longfalcon.newsj.nntp.client.CustomNNTPClient.java

/***
 * List the command help from the server.
 * <p>//from   w w w.  ja  v  a2  s  .  co m
 * @return The sever help information.
 * @exception NNTPConnectionClosedException
 *      If the NNTP server prematurely closes the connection as a result
 *      of the client being idle or some other reason causing the server
 *      to send NNTP reply code 400.  This exception may be caught either
 *      as an IOException or independently as itself.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 ***/
@Override
public String listHelp() throws IOException {
    if (!NNTPReply.isInformational(help())) {
        return null;
    }

    StringWriter help = new StringWriter();
    BufferedReader reader = new DotTerminatedMessageReader(_reader_);
    Util.copyReader(reader, help);
    reader.close();
    help.close();
    return help.toString();
}

From source file:disko.PDFDocument.java

protected synchronized String load() {
    final StringWriter stringOutput = new StringWriter();
    PDDocument document = null;/*from w ww  .jav a  2  s  . c  om*/
    try {
        document = PDDocument.load(ContentDownloader.getInstance().getInputStream(getUrlString()));
        title = document.getDocumentInformation().getTitle();
        PDFTextStripper stripper = new PDFTextStripper() {
            int startPage = 0;

            private int getIndex() {
                return stringOutput.getBuffer().length();
            }

            @Override
            protected void startPage(PDPage page) throws IOException {
                startPage = getIndex();
                log.debug("START PAGE " + getCurrentPageNo() + " AT " + startPage);
            }

            @Override
            protected void endPage(PDPage page) throws IOException {
                int endPage = getIndex();
                DocumentAnn ann = new DocumentAnn(startPage, endPage, PAGE_ANN);
                annotations.add(ann);
                log.debug("END PAGE " + getCurrentPageNo() + " AT " + endPage);
            }

        };
        //            stripper.setSortByPosition(false);
        //            String maxPageSetting = System.getProperty("disco.pdf.max.pages", 
        //                                             Integer.toString(Integer.MAX_VALUE));
        //            stripper.setEndPage(Integer.parseInt(maxPageSetting));
        stripper.writeText(document, stringOutput);
    } catch (Throwable t) {
        throw new RuntimeException("Unable to read resource at URL '" + url + "'", t);
    } finally {
        if (stringOutput != null) {
            try {
                stringOutput.close();
            } catch (IOException e) {
            }
        }
        if (document != null) {
            try {
                document.close();
            } catch (IOException e) {
            }
        }
    }

    String s = DU.replaceUnicodePunctuation(stringOutput.toString());
    ParagraphDetector.detectParagraphs(s, this.annotations);

    return (fullText = new WeakReference<String>(s)).get();
}

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

public XmlElement getXmlElement(final StartElement start, final XMLEventReader reader) throws Exception {

    final XmlElement res = new XmlElement();
    res.setStart(start);/*w w  w  .j a v  a2  s  .co  m*/

    StringWriter content = new StringWriter();

    int depth = 1;

    while (reader.hasNext() && depth > 0) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
            depth++;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
            depth--;
        }

        if (depth == 0) {
            res.setEnd(event.asEndElement());
        } else {
            event.writeAsEncodedUnicode(content);
        }
    }

    content.flush();
    content.close();

    res.setContent(new ByteArrayInputStream(content.toString().getBytes()));

    return res;
}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.StatisticJspBean.java

/**
 * Exports all the statistics visitors filtered.
 *
 * @param request The Http request/*  w  ww  . ja va 2 s .c  o  m*/
 * @param response The Http response
 * @return The Url after the export
 */
public String doExportStatistics(HttpServletRequest request, HttpServletResponse response) {
    String strFistResponseDateFilter = request.getParameter(PARAMETER_FIRST_RESPONSE_DATE_FILTER);
    String strLastResponseDateFilter = request.getParameter(PARAMETER_LAST_RESPONSE_DATE_FILTER);
    String strTimesUnit = request.getParameter(PARAMETER_TIMES_UNIT);
    String strTypeData = request.getParameter(PARAMETER_TYPE_DATA);
    List<ResultStatistic> listeResultStatistic = null;
    String strExportFileName;

    if (strTypeData.equals(CONSTANT_PRODUCT_TYPE)) {
        listeResultStatistic = _serviceStatistic.getProductStatistic(strTimesUnit, strFistResponseDateFilter,
                strLastResponseDateFilter);
        strExportFileName = PROPERTY_PRODUCT_STAT_EXPORT_FILE_NAME;
    } else {
        listeResultStatistic = _serviceStatistic.getPurchaseStatistic(strTimesUnit, strFistResponseDateFilter,
                strLastResponseDateFilter);
        strExportFileName = PROPERTY_PURCHASE_STAT_EXPORT_FILE_NAME;
    }

    List<String[]> listToCSVWriter = StatisticService.buildListToCSVWriter(listeResultStatistic, strTimesUnit,
            getLocale());

    //        if ( listToCSVWriter == null )
    //        {
    //            if ( strTypeData.equals( CONSTANT_PRODUCT_TYPE ) )
    //            {
    //                return getManageProducts( request );
    //            }
    //            else
    //            {
    //                return getManagePurchases( request );
    //            }
    //        }
    String strCsvSeparator = AppPropertiesService.getProperty(TicketsConstants.PROPERTY_CSV_SEPARATOR);
    StringWriter strWriter = new StringWriter();
    CSVWriter csvWriter = new CSVWriter(strWriter, strCsvSeparator.toCharArray()[0]);

    csvWriter.writeAll(listToCSVWriter);

    String strEncoding = AppPropertiesService.getProperty(PROPERTY_ENCODING);
    byte[] byteFileOutPut;

    try {
        byteFileOutPut = strWriter.toString().getBytes(strEncoding);
    } catch (UnsupportedEncodingException e) {
        byteFileOutPut = strWriter.toString().getBytes();
    }

    try {
        String strFormatExtension = AppPropertiesService.getProperty(TicketsConstants.PROPERTY_CSV_EXTENSION);
        String strFileName = AppPropertiesService.getProperty(strExportFileName) + "." + strFormatExtension;
        TicketsExportUtils.addHeaderResponse(request, response, strFileName, strFormatExtension);
        response.setContentLength(byteFileOutPut.length);

        OutputStream os = response.getOutputStream();
        os.write(byteFileOutPut);
        os.flush();
        os.close();

        // We do not close the output stream to allow HTTP keep alive
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    } finally {
        try {
            csvWriter.close();
        } catch (IOException e) {
            AppLogService.error(e.getMessage(), e);
        }

        try {
            strWriter.close();
        } catch (IOException e) {
            AppLogService.error(e.getMessage(), e);
        }
    }

    UrlItem url = new UrlItem(getManageProducts(request));

    return url.getUrl();
}

From source file:org.kie.workbench.common.forms.adf.processors.FormDefinitionsProcessor.java

protected StringBuffer writeTemplate(String templateName, Map<String, Object> context)
        throws GenerationException {
    //Generate code
    final StringWriter sw = new StringWriter();
    final BufferedWriter bw = new BufferedWriter(sw);

    // The code used to contain 'new InputStreamReader(this.getClass().getResourceAsStream(templateName))' which for
    // some reason was causing issues during concurrent invocation of this method (e.g. in parallel Maven build).
    // The stream returned by 'getResourceAsStream(templateName)' was sometimes already closed (!) and as the
    // Template class tried to read from the stream it resulted in IOException. Changing the code to
    // 'getResource(templateName).openStream()' seems to be a sensible workaround
    try (InputStream templateIs = this.getClass().getResource(templateName).openStream()) {
        Configuration config = new Configuration();

        Template template = new Template("", new InputStreamReader(templateIs), config);

        template.process(context, bw);//from w w  w .j a  va  2 s.  c  o  m
    } catch (IOException ioe) {
        throw new GenerationException(ioe);
    } catch (TemplateException te) {
        throw new GenerationException(te);
    } finally {
        try {
            bw.close();
            sw.close();
        } catch (IOException ioe) {
            throw new GenerationException(ioe);
        }
    }
    return sw.getBuffer();
}