Example usage for java.io StringWriter append

List of usage examples for java.io StringWriter append

Introduction

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

Prototype

public StringWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:org.sakaiproject.sgs2.server.GroovyShellServiceImpl.java

public ScriptParseResult parse(String sourceCode, String secureToken)
        throws RpcSecurityException, Server500Exception {

    isSecure(secureToken);/*from  w w w  .j  a v  a 2 s.c  o  m*/

    StringWriter stackTrace = new StringWriter();

    GroovyShell groovyShell = new GroovyShell();

    try {

        groovyShell.parse(sourceCode);

    } catch (CompilationFailedException cfe) {

        stackTrace.append(cfe.getMessage());

    } catch (Exception e) {

        stackTrace.append(e.getMessage());
    }

    ScriptParseResult scriptParseResult = new ScriptParseResult();
    scriptParseResult.setStackTrace(stackTrace.toString());

    return scriptParseResult;
}

From source file:org.apache.camel.component.xquery.XQueryBuilder.java

public String evaluateAsString(Exchange exchange) throws Exception {
    initialize(exchange);/*from ww  w  .  jav  a  2 s .c o m*/

    StringWriter buffer = new StringWriter();
    SequenceIterator iter = getExpression().iterator(createDynamicContext(exchange));
    for (Item item = iter.next(); item != null; item = iter.next()) {
        buffer.append(item.getStringValueCS());
    }
    return buffer.toString();
}

From source file:io.hawt.osgi.jmx.RBACDecorator.java

/**
 * Prepares list of operation signatures to pass to {@link JMXSecurityMBean#canInvoke(Map)}
 * @param ops/*from   ww  w.j  a va 2 s .  com*/
 * @return
 */
@SuppressWarnings("unchecked")
private List<String> operations(Map<String, Object> ops) {
    List<String> result = new LinkedList<>();
    for (String operation : ops.keySet()) {
        Object operationOrListOfOperations = ops.get(operation);
        List<Map<String, Object>> toStringify;
        if (operationOrListOfOperations instanceof List) {
            toStringify = (List<Map<String, Object>>) operationOrListOfOperations;
        } else /*if (operationOrListOfOperations instanceof Map) */ {
            toStringify = Collections.singletonList((Map<String, Object>) operationOrListOfOperations);
        }
        for (Map<String, Object> op : toStringify) {
            List<Map<String, String>> args = (List<Map<String, String>>) op.get("args");
            if (args == null || args.size() == 0) {
                result.add(operation + "()");
            } else {
                StringWriter sw = null;
                for (Map<String, String> arg : args) {
                    if (sw == null) {
                        sw = new StringWriter();
                    } else {
                        sw.append(',');
                    }
                    sw.append(arg.get("type"));
                }
                result.add(operation + "(" + sw.toString() + ")");
            }
        }
    }

    return result;
}

From source file:eu.sisob.uma.restserver.services.internalcvfiles.InternalCVFilesTask.java

public static boolean launch(String user, String pass, String task_code, String code_task_folder, String email,
        StringWriter message) {
    if (message == null) {
        return false;
    }//from  w ww .  j  a va  2s.c  o  m

    message.getBuffer().setLength(0);
    File code_task_folder_dir = new File(code_task_folder);

    File documents_dir = code_task_folder_dir;

    File input_file = FileSystemManager.getFileIfExists(code_task_folder_dir,
            input_data_source_filename_prefix_csv, input_data_source_filename_ext_csv);
    boolean validate = input_file != null;

    if (!validate) {
        message.write("You have not uploaded any file like this '" + input_data_source_filename_prefix_csv + "*"
                + input_data_source_filename_ext_csv + "' file");
        return false;
    }

    try {
        validate = FileFormatConversor.checkResearchersCSV(input_file, true);
    } catch (Exception ex) {
        eu.sisob.uma.extractors.adhoc.email.ProjectLogger.LOGGER.error(message.toString(), ex);
        validate = false;
    }

    if (!validate) {
        message.write("The format of '" + input_file.getName() + "' does not seems be correct"); //FIXME
        return false;
    }

    String middle_data_folder = code_task_folder + File.separator + AuthorizationManager.middle_data_dirname;
    File middle_data_dir = null;
    try {
        middle_data_dir = FileSystemManager.createFileAndIfExistsDelete(middle_data_folder);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.toString(), ex);
        message.append("The file couldn't be created " + middle_data_dir.getName() + "\r\n");
        return false;
    }

    String results_data_folder = code_task_folder + File.separator + AuthorizationManager.results_dirname;
    File results_data_dir = null;
    try {
        results_data_dir = FileSystemManager.createFileAndIfExistsDelete(results_data_folder);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.toString(), ex);
        message.append("The file couldn't be created " + results_data_dir.getName() + "\r\n");
        return false;
    }

    File zip_file = new File(code_task_folder_dir, input_data_documents_in_zip);

    if (zip_file.exists()) {
        documents_dir = new File(code_task_folder_dir, AuthorizationManager.middle_data_dirname);
        if (!ZipUtil.unZipItToSameFolder(zip_file, documents_dir)) {
            message.write(input_data_documents_in_zip + " cannot bet unziped"); //FIXME
            return false;
        }
    }

    String output_filename = input_file.getName().replace(input_data_source_filename_prefix_csv,
            output_data_source_filename_prefix_csv);
    File output_file = new File(results_data_dir, output_filename);

    String out_filename_2 = input_file.getName().replace(input_data_source_filename_prefix_csv,
            output_data_with_files_source_filename_prefix_csv);
    File output_file_2 = new File(results_data_dir, out_filename_2);

    InternalCVFilesExtractorTaskInRest task = new InternalCVFilesExtractorTaskInRest(user, task_code,
            code_task_folder, email, input_file, documents_dir, output_file,
            new File(results_data_dir, results_dirname), new File(results_data_dir, zip_output_filename),
            output_file_2);

    try {
        EmailExtractorService.getInstance().addExecution((new CallbackableTaskExecution(task)));

        message.write(TheResourceBundle.getString("Jsp Task Executed Msg"));
    } catch (Exception ex) {
        message.write(TheResourceBundle.getString("Jsp Task Executed Error Msg"));
        ProjectLogger.LOGGER.error(message.toString(), ex);
        return false;
    }

    return true;
}

From source file:org.zaproxy.zap.extension.ascan.ScriptsActiveScanner.java

@Override
public void scan(HttpMessage msg, String param, String value) {
    if (this.getExtension() == null) {
        return;/*ww w. ja va2s.  com*/
    }
    List<ScriptWrapper> scripts = this.getExtension().getScripts(ExtensionActiveScan.SCRIPT_TYPE_ACTIVE);

    for (Iterator<ScriptWrapper> it = scripts.iterator(); it.hasNext() && !isStop();) {
        ScriptWrapper script = it.next();
        StringWriter writer = new StringWriter();
        try {
            if (script.isEnabled()) {
                ActiveScript s = extension.getInterface(script, ActiveScript.class);

                if (s != null) {
                    logger.debug("Calling script " + script.getName() + " scan for "
                            + msg.getRequestHeader().getURI() + "param=" + param + " value=" + value);
                    s.scan(this, msg, param, value);

                } else {
                    writer.append(Constant.messages.getString("scripts.interface.active.error"));
                    extension.setError(script, writer.toString());
                    extension.setEnabled(script, false);
                }
            }

        } catch (Exception e) {
            writer.append(e.toString());
            extension.setError(script, e);
            extension.setEnabled(script, false);
        }
    }
}

From source file:ro.nextreports.engine.util.QueryUtil.java

public List<NameType> getColumns(String sql, Map<String, QueryParameter> params, List<NameType> cachedColumns)
        throws Exception {
    if (cachedColumns != null) {
        return cachedColumns;
    }/*from  w  ww.  j  a va  2 s  .c  o  m*/

    // create the query object
    Query query = new Query(sql);

    // get parameter names
    String[] paramNames = query.getParameterNames();

    // execute query if no parameters
    if (paramNames.length == 0) {
        return executeQueryForColumnNames(sql);
    }

    // init the sql without parameters
    StringWriter sqlWithoutParameters = new StringWriter(100);

    // subtitute paramters with default value
    QueryChunk[] chunks = query.getChunks();
    for (QueryChunk chunk : chunks) {
        int chunckType = chunk.getType();
        if (QueryChunk.TEXT_TYPE == chunckType) {
            sqlWithoutParameters.append(chunk.getText());
        } else if (QueryChunk.PARAMETER_TYPE == chunckType) {
            String paramName = chunk.getText();
            QueryParameter param = params.get(paramName);
            if (param == null) {
                // do not internationalize strings in engine package!!!
                throw new Exception("Parameter '" + paramName + "' not defined.");
            }
            boolean afterIn = sqlWithoutParameters.getBuffer().toString().trim().toLowerCase()
                    .endsWith(QueryExecutor.IN.toLowerCase());
            if (afterIn) {
                sqlWithoutParameters.append("(");
            }
            sqlWithoutParameters.append(getDummyValueForParameter(param));
            if (afterIn) {
                sqlWithoutParameters.append(")");
            }
        }
    }
    return executeQueryForColumnNames(sqlWithoutParameters.toString());
}

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  a  2s  . 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:ubic.gemma.core.analysis.service.ArrayDesignAnnotationServiceImpl.java

private Writer initOutputFile(ArrayDesign arrayDesign, String fileBaseName, boolean overWrite)
        throws IOException {

    Writer writer;// w  w  w.  j  a v  a  2  s .  c  o  m
    if (StringUtils.isBlank(fileBaseName)) {
        ArrayDesignAnnotationServiceImpl.log.info("Output to stdout");
        writer = new PrintWriter(System.out);
    } else {

        File f = ArrayDesignAnnotationServiceImpl.getFileName(fileBaseName);

        if (f.exists()) {
            if (overWrite) {
                ArrayDesignAnnotationServiceImpl.log.warn("Will overwrite existing file " + f);
                EntityUtils.deleteFile(f);
            } else {
                return null;
            }
        } else {
            ArrayDesignAnnotationServiceImpl.log.info("Creating new annotation file " + f + " \n");
        }

        EntityUtils.mkdirs(f.getParentFile());
        writer = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(f)));
    }
    StringWriter buf = new StringWriter();
    buf.append("# Annotation file generated by Gemma\n");
    buf.append("# Generated ").append(DateUtil.convertDateToString(new Date())).append("\n");
    buf.append(ExpressionDataFileService.DISCLAIMER);
    buf.append("# Gemma link for this platform: ").append(Settings.getBaseUrl())
            .append(" arrays/showArrayDesign.html?id=").append(arrayDesign.getId().toString()).append("\n");
    buf.append("# ").append(arrayDesign.getShortName()).append("  ").append(arrayDesign.getName()).append("\n");
    buf.append("# ").append(arrayDesign.getPrimaryTaxon().getScientificName()).append("\n");

    writer.write(buf.toString());
    writer.write("ProbeName\tGeneSymbols\tGeneNames\tGOTerms\tGemmaIDs\tNCBIids\n");

    return writer;
}

From source file:org.nuxeo.theme.elements.ElementRenderer.java

public static RenderingInfo render(RenderingInfo info, final boolean cache) {
    InfoPool.register(info);//from w w  w . j av a  2 s .co m

    final StringWriter rendered = new StringWriter();
    final URL themeUrl = info.getThemeUrl();
    if (themeUrl == null) {
        log.warn("Theme URL not set for the element: " + info.getElement());
    }

    final EngineType engine = info.getEngine();
    final Element element = info.getElement();

    String markup = "";
    if (element.isLeaf()) {
        if (!(element instanceof Fragment)) {
            log.error(String.format("Leaf nodes must be fragments, ignoring element: %s",
                    element.getElementType().getTypeName()));
            return info;
        }
        final Fragment fragment = (Fragment) element;
        try {
            info.setModel(fragment.getModel());
        } catch (ModelException e) {
            if (info.isDirty()) {
                final String fragmentName = fragment.getFragmentType().getTypeName();
                log.error("Rendering of fragment '" + fragmentName + "' failed.", e);
                return info;
            }
        }
        if (fragment.isDynamic()) {
            info.setDirty(true);
        }
    } else {
        for (Node child : element.getChildrenInContext(themeUrl)) {
            final RenderingInfo childInfo = new RenderingInfo((Element) child, themeUrl);
            final RenderingInfo renderedChild = render(childInfo);
            if (renderedChild == null) {
                continue;
            }
            rendered.append(renderedChild.getMarkup());
        }
        markup = rendered.toString();
    }

    info.setMarkup(markup);

    final RendererType renderer = engine.getRenderers().get(element.getElementType().getTypeName());

    if (renderer == null) {
        return info;
    }

    final String templateEngineName = info.getTemplateEngine().getName();
    final String engineName = info.getEngine().getName();
    final String viewMode = info.getViewMode();
    for (final String filterName : renderer.getFilters()) {

        // Look for a filter for the current engine
        FilterType filterType = getFilterFor(engineName, filterName, templateEngineName, viewMode);

        // Fall back to no specific engine
        if (filterType == null) {
            filterType = getFilterFor("*", filterName, templateEngineName, viewMode);
        }

        if (filterType == null) {
            log.warn("Filter type '" + filterName + "' not found.");
            continue;
        }

        final Filter filter = filterType.getFilter();
        if (filter == null) {
            log.warn("Filter instantiation failed: " + filterName);
            continue;
        }

        final FilterTypeFamily filterTypeFamily = filterType.getFilterTypeFamily();

        if (filterTypeFamily == FilterTypeFamily.FORMAT) {
            final FormatType formatType = ((FormatFilter) filter).getFormatType();
            final Format format = ElementFormatter.getFormatByType(element, formatType);
            if (format == null) {
                log.debug("Could not find '" + formatType.getTypeName() + "' format for: "
                        + element.getElementType().getTypeName());
                continue;
            }
            info.setFormat(format);
        } else if (filterTypeFamily == FilterTypeFamily.STANDALONE) {
            // Do nothing
        } else {
            log.warn("Unsupported filter type: " + filterName);
        }

        info = filter.process(info, cache);

        // Abort the rendering if the filter returns null
        if (info == null) {
            break;
        }
    }
    return info;
}

From source file:eu.sisob.uma.restserver.services.email.EmailTask.java

public static boolean launch(String user, String pass, String task_code, String code_task_folder, String email,
        List<String> filters, StringWriter message) {
    if (message == null) {
        return false;
    }/*from   w w  w  .ja v a  2  s.co  m*/

    message.getBuffer().setLength(0);
    File code_task_folder_dir = new File(code_task_folder);

    File documents_dir = code_task_folder_dir;

    File csv_data_source_file = FileSystemManager.getFileIfExists(code_task_folder_dir,
            input_data_source_filename_prefix_csv, input_data_source_filename_ext_csv);
    boolean validate = csv_data_source_file != null;

    if (!validate) {
        message.write("You have not uploaded any file like this '" + input_data_source_filename_prefix_csv + "*"
                + input_data_source_filename_ext_csv + "' file");
        return false;
    }

    try {
        validate = FileFormatConversor.checkResearchersCSV(csv_data_source_file, true);
    } catch (Exception ex) {
        eu.sisob.uma.extractors.adhoc.email.ProjectLogger.LOGGER.error(message.toString(), ex);
        validate = false;
    }

    if (!validate) {
        message.write("The format of '" + csv_data_source_file.getName() + "' does not seems be correct"); //FIXME
        return false;
    }

    String middle_data_folder = code_task_folder + File.separator + AuthorizationManager.middle_data_dirname;
    File middle_data_dir = null;
    try {
        middle_data_dir = FileSystemManager.createFileAndIfExistsDelete(middle_data_folder);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.toString(), ex);
        message.append("The file couldn't be created " + middle_data_dir.getName() + "\r\n");
        return false;
    }

    String results_data_folder = code_task_folder + File.separator + AuthorizationManager.results_dirname;
    File results_data_dir = null;
    try {
        results_data_dir = FileSystemManager.createFileAndIfExistsDelete(results_data_folder);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.toString(), ex);
        message.append("The file couldn't be created " + results_data_dir.getName() + "\r\n");
        return false;
    }

    File zip_file = new File(code_task_folder_dir, input_data_documents_in_zip);

    if (zip_file.exists()) {
        documents_dir = new File(code_task_folder_dir, AuthorizationManager.middle_data_dirname);
        if (!ZipUtil.unZipItToSameFolder(zip_file, documents_dir)) {
            message.write(input_data_documents_in_zip + " cannot bet unziped"); //FIXME
            return false;
        }
    }

    String out_filename = csv_data_source_file.getName().replace(input_data_source_filename_prefix_csv,
            output_data_source_filename_prefix_csv);
    File csv_data_output_file = new File(results_data_dir, out_filename);

    String out_filename_unfounded = csv_data_source_file.getName()
            .replace(input_data_source_filename_prefix_csv, output_data_source_nofound_filename_prefix_csv);
    File csv_data_output_file_unfounded = new File(results_data_dir, out_filename_unfounded);

    String out_filename_wor = csv_data_source_file.getName().replace(input_data_source_filename_prefix_csv,
            output_data_source_norepeat_filename_prefix_csv);
    File csv_data_output_file_wor = new File(results_data_dir, out_filename_wor);

    String out_filename_wor_notfound = csv_data_source_file.getName().replace(
            input_data_source_filename_prefix_csv, output_data_source_nofound_norepeat_filename_prefix_csv);
    File csv_data_output_file_notfound_wor = new File(results_data_dir, out_filename_wor_notfound);

    EmailExtractorTaskInRest task = new EmailExtractorTaskInRest(user, task_code, code_task_folder, email,
            csv_data_source_file, documents_dir, csv_data_output_file, csv_data_output_file_wor,
            csv_data_output_file_unfounded, csv_data_output_file_notfound_wor, filters);

    try {
        EmailExtractorService.getInstance().addExecution((new CallbackableTaskExecution(task)));

        message.write(TheResourceBundle.getString("Jsp Task Executed Msg"));
    } catch (Exception ex) {
        message.write(TheResourceBundle.getString("Jsp Task Executed Error Msg"));
        ProjectLogger.LOGGER.error(message.toString(), ex);
        return false;
    }

    return true;
}