Example usage for java.io StringWriter flush

List of usage examples for java.io StringWriter flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flush the stream.

Usage

From source file:fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter.java

protected void processTempFile(final File df, final String fileEncoding, final String xmlVersion,
        final String header, final String footer, final TDocument persistenceConfig, final Pair collectivite,
        final Pair codeBudget, final File originalFile, final int docCount, final boolean shouldDelete,
        final int progress) {
    try {//w  w  w .ja  v a2s. c  o m
        long startFile = System.currentTimeMillis();
        String data = FileUtils.readTextFile(df, fileEncoding);
        StringBuilder fullText = new StringBuilder();
        fullText.append("<?xml version=\"").append(xmlVersion).append("\" encoding=\"").append(fileEncoding)
                .append("\"?>");
        fullText.append(header).append(data).append(footer);
        String sFullText = fullText.toString();
        byte[] bData = sFullText.getBytes(fileEncoding);

        Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(bData));

        // il faut retrouver de quel etat est ce document
        // on cherche si la balise root contient un
        // dm.getEtatxxx().getBalise()
        EtatModel currentEtat = null;
        for (EtatModel em : dm.getEtats()) {
            String balise = em.getBalise();
            NodeList nl = doc.getElementsByTagName(balise);
            if (nl.getLength() > 0) {
                currentEtat = em;
                break;
            } else {
                nl = doc.getElementsByTagNameNS(em.getBaliseNamespace(), balise);
                if (nl.getLength() > 0) {
                    currentEtat = em;
                    break;
                }
            }
        }
        // traitement d'erreur, on n'arrive pas  identifier l'etat
        if (currentEtat == null) {
            StringWriter sw = new StringWriter();
            sw.append("Impossible de dterminer l'tat de ce document :\n");
            TransformerFactory errorTransFactory = FactoryProvider.getTransformerFactory();
            Transformer errorTransformer = errorTransFactory.newTransformer();
            errorTransformer.transform(new DOMSource(doc), new StreamResult(sw));
            sw.flush();
            sw.close();
            logger.error(sw.getBuffer().toString());
            return;
        }
        // apply before-import xslt
        if (persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile() != null) {
            Transformer trans = importXsltCache
                    .get(persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile());
            if (trans == null) {
                TransformerFactory tf = FactoryProvider.getTransformerFactory();
                File directory = new File(currentEtat.getParent().getBaseDirectory());
                File xslFile = new File(directory,
                        persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile());
                trans = tf.newTransformer(new StreamSource(xslFile));
                importXsltCache.put(persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile(), trans);
            }
            // important, maintenant que c'est mis en cache !
            trans.reset();
            if (codeBudget != null) {
                trans.setParameter("CodeBudget", codeBudget.key);
                trans.setParameter("LibelleBudget", codeBudget.libelle);
            }
            if (collectivite != null) {
                trans.setParameter("CodeCollectivite", collectivite.key);
                trans.setParameter("LibelleCollectivite", collectivite.libelle);
            }
            if (getManifeste() != null) {
                trans.setParameter("manifeste", new DOMSource(getManifeste()));
            }
            // on passe en parametre le nom du fichier
            trans.setParameter("file.name", originalFile.getName());

            trans.setOutputProperty(OutputKeys.ENCODING, fileEncoding);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            trans.transform(new StreamSource(new ByteArrayInputStream(sFullText.getBytes(fileEncoding))),
                    new StreamResult(baos));
            bData = baos.toByteArray();
        }
        importTimingOS.append(originalFile.getName()).append(";").append(df.toURI().toURL().toExternalForm())
                .append(";XSL;").append(Long.toString(startFile)).append(";")
                .append(Long.toString(startFile = System.currentTimeMillis()));
        importTimingOS.println();

        String docName = StringUtilities.removeFileNameSuffix(originalFile.getName()) + "-" + docCount + "."
                + dm.getExtension();
        if (!isCancelled()) {
            try {
                if (!DataLayerManager.getImplementation().importElement(dm, currentEtat, codeBudget,
                        collectivite, originalFile.getName(), docName, bData, fileEncoding, getArchiveName(),
                        user)) {
                    logger.warn(DataLayerManager.getImplementation().getWarnings());
                    warningCount++;
                }
            } catch (DataAccessException daEx) {
                logger.error("importing element:", daEx);
                throw (Exception) daEx;
            } catch (DataConfigurationException dcEx) {
                logger.error("importing element:", dcEx);
                throw (Exception) dcEx.getCause();
            }
        }
        if (shouldDelete) {
            df.delete();
        }
        importTimingOS.append(originalFile.getName()).append(";").append(df.toURI().toURL().toExternalForm())
                .append(";IDX;").append(Long.toString(startFile)).append(";")
                .append(Long.toString(startFile = System.currentTimeMillis()));
        importTimingOS.println();
        this.getImpSvcProvider().pushCurrentProgress(progress);
    } catch (Exception ex) {
        //TODO
    }
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToLaTeXConverter.java

/**
 * This method renders inline items based on a macro included in the main
 * template. In the template file the macro must be marked like this: <code>
 * % %%ITP ${Description} ${IssueNo}/*w  w  w  .  j  av  a  2s.  c  o m*/
 * </code> The inline macro buffer passed here has the comment part removed.
 *
 * @param context
 * @param inlineMacroBuffer
 */
private static String createProcessedInlineItems(Map<String, Object> context, StringBuilder inlineMacroBuffer) {
    if (inlineMacroBuffer == null || "".equals(inlineMacroBuffer)) {
        return null;
    }

    Template freemarkerTemplate = null;

    StringWriter texWriter = new StringWriter();
    StringBuffer debugMessages = new StringBuffer();
    try {
        debugMessages.append("Creating Freemarker template..." + CRLF);
        Configuration freemarkerConfig = new Configuration();
        freemarkerConfig.setTemplateExceptionHandler(new LaTeXFreemarkerExceptionHandler());
        freemarkerTemplate = new Template("InlineItems", new StringReader(inlineMacroBuffer.toString()),
                freemarkerConfig);
        debugMessages.append("Processing the Freemarker LaTeX template..." + CRLF);
        freemarkerTemplate.process(context, texWriter);
        debugMessages.append("Freemarker LaTeX template processed." + CRLF);
    } catch (Exception e) {
        LOGGER.error("Problem processing template: " + CRLF + debugMessages.toString());
        String st = ExceptionUtils.getStackTrace(e);
        LOGGER.debug(st, e);
        texWriter = new StringWriter();
        texWriter.append(inlineMacroBuffer.toString());

    }

    texWriter.flush();

    return texWriter.toString();
}

From source file:org.dswarm.graph.resources.MaintainResource.java

/**
 * note utilise this endpoint with care, because it cleans your complete db!
 *
 * @param database the graph database/* ww w  .  j  a  v  a 2 s .c o m*/
 */
@DELETE
@Path("/delete")
@Produces("application/json")
public Response cleanGraph(@Context final GraphDatabaseService database) throws IOException, DMPGraphException {

    MaintainResource.LOG.debug("start cleaning up the db");

    final long deleted = deleteSomeStatements(database);

    MaintainResource.LOG.debug("finished delete-all-entities TXs");

    MaintainResource.LOG.debug("start legacy indices clean-up");

    // TODO: maybe separate index clean-up + observe index clean-up
    // => maybe we also need to do a label + relationship types clean-up ... => this is not supported right now ...

    deleteSomeLegacyIndices(database);

    MaintainResource.LOG.debug("finished legacy indices clean-up");

    MaintainResource.LOG.debug("start schema indices clean-up");

    deleteSomeSchemaIndices(database);

    MaintainResource.LOG.debug("finished schema indices clean-up");

    MaintainResource.LOG.debug("finished cleaning up the db");

    final StringWriter out = new StringWriter();
    final JsonGenerator generator = simpleObjectMapper.getFactory().createGenerator(out);

    generator.writeStartObject();
    generator.writeNumberField("deleted", deleted);
    generator.writeEndObject();
    generator.flush();
    generator.close();

    final String result = out.toString();

    out.flush();
    out.close();

    return Response.ok(result, MediaType.APPLICATION_JSON_TYPE).build();
}

From source file:org.ikasan.filetransfer.xml.transform.DefaultXSLTransformer.java

/**
 * Performs the transformation to the output result as String.
 *
 * @param in - the XML document./*w  w  w.  jav a2 s. com*/
 * @return String
 * @throws TransformerException 
 * @throws IOException 
 */
public String transformToString(Source in) throws TransformerException, IOException {
    // Create a Writer instance to hold transformation result
    StringWriter writer = new StringWriter();
    StreamResult out = new StreamResult(writer);

    // Transformation
    this.transform(in, out);

    // Flush and close the stream
    writer.flush();
    writer.close();

    // Here is the newly transformed string
    return new String(writer.getBuffer().toString());
}

From source file:org.multicore_association.measure.mem.generate.MemCodeGen.java

/**
 * Output of a C language source based on read setting data.
 * @return Flag for success judgements/*from w  w w  .  j  a v  a2 s .c  om*/
 */
private boolean dumpCSource() {
    try {

        Properties p = new Properties();
        p.setProperty("resource.loader", "class");
        p.setProperty("class.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        p.setProperty("input.encoding", "UTF-8");

        Velocity.init(p);
        Velocity.setProperty("file.resource.loader.path", "/");
        VelocityContext context = new VelocityContext();
        context.put("confData", confData);
        context.put("measureCountMax", measureCountMax);
        context.put("addressSpaceList", addressSpaceList);
        context.put("subSpaceList", subSpaceList);
        context.put("slaveComponentList", slaveComponentList);
        context.put("cpuList", cpuList);
        context.put("accessTypeList", accessTypeList);
        context.put("accessByteSizeList", accessByteSizeList);

        StringWriter writer = new StringWriter();

        String tempFile = "template.vm";
        Template template = Velocity.getTemplate(tempFile);

        template.merge(context, writer);
        System.out.println(writer.toString());
        writer.flush();
    } catch (ResourceNotFoundException e) {
        e.printStackTrace();
        System.err.println("Error: template file is not found");
        return false;
    } catch (MethodInvocationException e) {
        e.printStackTrace();
        System.err.println("Error: syntax error occurs in the template file");
        return false;
    } catch (ParseErrorException e) {
        e.printStackTrace();
        System.err.println("Error: syntax error occurs in the template file");
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Error: other error");
        return false;
    }

    return true;
}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java

static String getStackTrace(Throwable t) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw, true);
    t.printStackTrace(pw);//  ww  w  .j  a v  a  2s . co m
    pw.flush();
    sw.flush();
    return sw.toString();
}

From source file:org.oryxeditor.server.BPELImporter.java

private String preprocessSource(HttpServletResponse res, String oldString) {

    StringWriter stringOut = new StringWriter();
    try {/*w  w  w  . ja va  2s .  co  m*/
        // transform string to document
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream oldResultInputStream = new ByteArrayInputStream(oldString.getBytes());
        Document oldDocument = builder.parse(oldResultInputStream);

        // rearrange document
        Document newDocument = preprocessor.preprocessDocument(oldDocument);

        // transform document to string
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        DOMSource source = new DOMSource(newDocument);
        StreamResult result = new StreamResult(stringOut);
        transformer.transform(source, result);
        stringOut.flush();

    } catch (Exception e) {
        handleException(res, e);
    }

    return stringOut.toString();

}

From source file:com.aimluck.eip.project.util.ProjectUtils.java

/**
 * ?????/*from ww w.j  a  v  a2  s.c o  m*/
 * 
 * @return
 */
public static String createProjectMemberMsg(RunData rundata, String addr, EipTProject project) {
    VelocityContext context = new VelocityContext();
    boolean enableAsp = JetspeedResources.getBoolean("aipo.asp", false);
    String CR = ALMailUtils.CR;

    context.put("user_email", addr);

    // ??????????
    StringBuffer message = new StringBuffer("");
    message.append(CR);
    message.append(getl10nFormat("PROJECT_MAIL_TEXT2", project.getProjectName())).append(CR);
    context.put("message", message);

    // 
    context.put("serviceAlias", ALOrgUtilsService.getAlias());
    // Aipo??
    context.put("enableAsp", enableAsp);
    context.put("globalurl", ALMailUtils.getGlobalurl());
    context.put("localurl", ALMailUtils.getLocalurl());
    CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil
            .getServiceByName(LocalizationService.SERVICE_NAME);
    String lang = locService.getLocale(rundata).getLanguage();
    StringWriter writer = new StringWriter();
    try {
        if (lang != null && lang.equals("ja")) {
            Template template = Velocity.getTemplate("portlets/mail/" + lang + "/project-notification-mail.vm",
                    "utf-8");
            template.merge(context, writer);
        } else {
            Template template = Velocity.getTemplate("portlets/mail/project-notification-mail.vm", "utf-8");
            template.merge(context, writer);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    writer.flush();
    String ret = writer.getBuffer().toString();
    return ret;

}

From source file:com.aimluck.eip.project.util.ProjectUtils.java

/**
 * ?????//  ww  w .  ja va  2 s .  c o  m
 * 
 * @return
 */
public static String createTaskMemberMsg(RunData rundata, String addr, EipTProjectTask task,
        EipTProject project) {
    VelocityContext context = new VelocityContext();
    boolean enableAsp = JetspeedResources.getBoolean("aipo.asp", false);
    String CR = ALMailUtils.CR;

    context.put("user_email", addr);

    // ??????????
    StringBuffer message = new StringBuffer("");
    message.append(CR);
    message.append(getl10nFormat("PROJECT_MAIL_TEXT", project.getProjectName(), task.getTaskName())).append(CR);
    context.put("message", message);

    // 
    context.put("serviceAlias", ALOrgUtilsService.getAlias());
    // Aipo??
    context.put("enableAsp", enableAsp);
    context.put("globalurl", ALMailUtils.getGlobalurl());
    context.put("localurl", ALMailUtils.getLocalurl());
    CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil
            .getServiceByName(LocalizationService.SERVICE_NAME);
    String lang = locService.getLocale(rundata).getLanguage();
    StringWriter writer = new StringWriter();
    try {
        if (lang != null && lang.equals("ja")) {
            Template template = Velocity.getTemplate("portlets/mail/" + lang + "/project-notification-mail.vm",
                    "utf-8");
            template.merge(context, writer);
        } else {
            Template template = Velocity.getTemplate("portlets/mail/project-notification-mail.vm", "utf-8");
            template.merge(context, writer);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    writer.flush();
    String ret = writer.getBuffer().toString();
    return ret;

}

From source file:de.tu_dortmund.ub.data.dswarm.Init.java

public String call() {

    final String serviceName = config.getProperty(TPUStatics.SERVICE_NAME_IDENTIFIER);
    final String engineDswarmAPI = config.getProperty(TPUStatics.ENGINE_DSWARM_API_IDENTIFIER);
    final Optional<Boolean> optionalEnhanceInputDataResource = TPUUtil
            .getBooleanConfigValue(TPUStatics.ENHANCE_INPUT_DATA_RESOURCE, config);

    LOG.info(String.format("[%s][%d] Starting 'Init (Task)' ...", serviceName, cnt));

    try {//from  w w  w.  jav a  2s  .c  o m

        final boolean doIngest;

        final String doIngestString = config.getProperty(TPUStatics.DO_INITIAL_DATA_MODEL_INGEST_IDENTIFIER);

        if (doIngestString != null && !doIngestString.trim().isEmpty()) {

            doIngest = Boolean.valueOf(doIngestString);
        } else {

            // default = true
            doIngest = true;
        }

        if (doIngest) {

            LOG.debug("[{}][{}] do data model creation with data ingest", serviceName, cnt);

            TPUUtil.initSchemaIndices(serviceName, config);
        }

        final String configurationFileName = config.getProperty(TPUStatics.CONFIGURATION_NAME_IDENTIFIER);
        final String configurationJSONString = readFile(configurationFileName, Charsets.UTF_8);
        final JsonObject configurationJSON = TPUUtil.getJsonObject(configurationJSONString);

        final String finalInputResourceFile;

        if (optionalEnhanceInputDataResource.isPresent()
                && Boolean.TRUE.equals(optionalEnhanceInputDataResource.get())) {

            final Optional<String> optionalUpdatedInputResourceFile = enhanceInputDataResource(initResourceFile,
                    configurationJSON);

            if (optionalUpdatedInputResourceFile.isPresent()) {

                finalInputResourceFile = optionalUpdatedInputResourceFile.get();
            } else {

                finalInputResourceFile = initResourceFile;
            }
        } else {

            finalInputResourceFile = initResourceFile;
        }

        final String name = String.format("resource for project '%s'", initResourceFile);
        final String description = String.format("'resource does not belong to a project' - case %d", cnt);
        final String inputResourceJson = uploadFileAndCreateResource(finalInputResourceFile, name, description,
                serviceName, engineDswarmAPI);

        if (inputResourceJson == null) {

            final String message = "something went wrong at resource creation";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        final JsonObject inputResourceJSON = TPUUtil.getJsonObject(inputResourceJson);
        final String inputResourceID = inputResourceJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER);
        LOG.info(String.format("[%s][%d] input resource id = %s", serviceName, cnt, inputResourceID));

        if (inputResourceID == null) {

            final String message = "something went wrong at resource creation, no resource uuid available";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        // TODO: refactor this, so that a configuration only needs to be create once per TPU task
        // create configuration
        final String finalConfigurationJSONString = createConfiguration(configurationJSONString, serviceName,
                engineDswarmAPI);

        if (finalConfigurationJSONString == null) {

            final String message = "something went wrong at configuration creation";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        final JsonObject finalConfigurationJSON = TPUUtil.getJsonObject(finalConfigurationJSONString);
        final String configurationID = finalConfigurationJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER);
        LOG.info(String.format("[%s][%d] configuration id = %s", serviceName, cnt, configurationID));

        if (configurationID == null) {

            final String message = "something went wrong at configuration creation, no configuration uuid available";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        // check for existing input schema
        final Optional<JsonObject> optionalInputSchema = getInputSchema(serviceName, engineDswarmAPI);

        // create the datamodel (will use it's resource)
        final String dataModelName = String.format("data model %d", cnt);
        final String dataModelDescription = String.format("data model description %d", cnt);
        final String dataModelJSONString = createDataModel(inputResourceJSON, finalConfigurationJSON,
                optionalInputSchema, dataModelName, dataModelDescription, serviceName, engineDswarmAPI,
                doIngest);

        if (dataModelJSONString == null) {

            final String message = "something went wrong at data model creation";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        final JsonObject dataModelJSON = TPUUtil.getJsonObject(dataModelJSONString);
        final String dataModelID = dataModelJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER);
        LOG.info(String.format("[%s][%d] data model id = %s", serviceName, cnt, dataModelID));

        if (dataModelID == null) {

            final String message = "something went wrong at data model creation, no data model uuid available";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        // we don't need to transform after each ingest of a slice of records,
        // so transform and export will be done separately
        LOG.info(String.format("[%s][%d] (Note: Only ingest, but no transformation or export done.)",
                serviceName, cnt));

        final StringWriter stringWriter = new StringWriter();
        final JsonGenerator jp = Json.createGenerator(stringWriter);

        jp.writeStartObject();
        jp.write(DATA_MODEL_ID, dataModelID);
        jp.write(RESOURCE_ID, inputResourceID);
        jp.write(CONFIGURATION_ID, configurationID);
        jp.writeEnd();

        jp.flush();
        jp.close();

        final String result = stringWriter.toString();

        stringWriter.flush();
        stringWriter.close();

        return result;
    } catch (final Exception e) {

        final String message = String.format("[%s][%d] Processing resource '%s' failed with a %s", serviceName,
                cnt, initResourceFile, e.getClass().getSimpleName());

        LOG.error(message, e);

        throw new RuntimeException(message, e);
    }
}