Example usage for java.io Writer append

List of usage examples for java.io Writer append

Introduction

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

Prototype

public Writer append(char c) throws IOException 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:org.alfresco.repo.domain.schema.SchemaBootstrap.java

/**
 * Builds the schema from scratch or applies the necessary patches to the schema.
 *///w  ww  .  ja v  a  2s  .c  om
private boolean updateSchema(Configuration cfg, Session session, Connection connection) throws Exception {
    boolean create = false;
    try {
        countAppliedPatches(cfg, connection);
    } catch (NoSchemaException e) {
        create = true;
    }
    // Get the dialect
    final Dialect dialect = Dialect.getDialect(cfg.getProperties());
    String dialectStr = dialect.getClass().getSimpleName();

    if (create) {
        long start = System.currentTimeMillis();

        // execute pre-create scripts (not patches)
        for (String scriptUrl : this.preCreateScriptUrls) {
            executeScriptUrl(cfg, connection, scriptUrl);
        }
        // Build and execute changes generated by Hibernate
        File tempFile = null;
        Writer writer = null;
        try {
            DatabaseMetadata metadata = new DatabaseMetadata(connection, dialect);
            String[] sqls = cfg.generateSchemaUpdateScript(dialect, metadata);
            if (sqls.length > 0) {
                tempFile = TempFileProvider.createTempFile("AlfrescoSchema-" + dialectStr + "-Update-", ".sql");
                writer = new BufferedWriter(new FileWriter(tempFile));
                for (String sql : sqls) {
                    writer.append(sql);
                    writer.append(";\n");
                }
                try {
                    writer.close();
                } catch (Throwable e) {
                }
                executeScriptFile(cfg, connection, tempFile, null);
            }
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Throwable e) {
                }
            }
        }
        // execute post-create scripts (not patches)
        for (String scriptUrl : this.postCreateScriptUrls) {
            executeScriptUrl(cfg, connection, scriptUrl);
        }

        if (logger.isInfoEnabled()) {
            logger.info("Create scripts executed in " + (System.currentTimeMillis() - start) + " ms");
        }
    } else {
        // Execute any pre-auto-update scripts
        checkSchemaPatchScripts(cfg, connection, preUpdateScriptPatches, true);

        // Build and execute changes generated by Hibernate
        File tempFile = null;
        Writer writer = null;
        try {
            DatabaseMetadata metadata = new DatabaseMetadata(connection, dialect);
            String[] sqls = cfg.generateSchemaUpdateScript(dialect, metadata);
            if (sqls.length > 0) {
                tempFile = TempFileProvider.createTempFile("AlfrescoSchema-" + dialectStr + "-Update-", ".sql");
                writer = new BufferedWriter(new FileWriter(tempFile));
                for (String sql : sqls) {
                    writer.append(sql);
                    writer.append(";\n");
                }
            }
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Throwable e) {
                }
            }
        }
        // execute if there were changes raised by Hibernate
        if (tempFile != null) {
            executeScriptFile(cfg, connection, tempFile, null);
        }

        // Execute any post-auto-update scripts
        checkSchemaPatchScripts(cfg, connection, postUpdateScriptPatches, true);
    }

    // Initialise Activiti DB, using an unclosable connection
    boolean activitiTablesExist = checkActivitiTablesExist(connection);
    if (!activitiTablesExist) {
        // Activiti DB updates are performed as patches in alfresco, only give
        // control to activiti when creating new one.
        initialiseActivitiDBSchema(new UnclosableConnection(connection));

        // ALF-18996: Upgrade from 3.4.12 to 4.2.0 fails: Activiti tables have not been bootstrapped
        // The Activiti bootstrap is effectively doing the work of all the other patches,
        // which should be considered complete.
        int installedSchemaNumber = getInstalledSchemaNumber(connection);
        for (Patch activitiScriptPatch : updateActivitiScriptPatches) {
            AppliedPatch appliedPatch = new AppliedPatch();
            appliedPatch.setId(activitiScriptPatch.getId());
            appliedPatch.setDescription(activitiScriptPatch.getDescription());
            appliedPatch.setFixesFromSchema(activitiScriptPatch.getFixesFromSchema());
            appliedPatch.setFixesToSchema(activitiScriptPatch.getFixesToSchema());
            appliedPatch.setTargetSchema(activitiScriptPatch.getTargetSchema());
            appliedPatch.setAppliedToSchema(installedSchemaNumber);
            appliedPatch.setAppliedToServer("UNKNOWN");
            appliedPatch.setAppliedOnDate(new Date()); // the date applied
            appliedPatch.setSucceeded(true);
            appliedPatch.setWasExecuted(false);
            appliedPatch.setReport("Placeholder for Activiti bootstrap at schema " + installedSchemaNumber);
            appliedPatchDAO.createAppliedPatch(appliedPatch);
        }
    } else {
        // Execute any auto-update scripts for Activiti tables
        checkSchemaPatchScripts(cfg, connection, updateActivitiScriptPatches, true);

        // verify that all Activiti patches have been applied correctly
        checkSchemaPatchScripts(cfg, connection, updateActivitiScriptPatches, false);
    }

    return create;
}

From source file:org.exoplatform.portal.webui.workspace.UIPortalApplication.java

/**
 * The processrender() method handles the creation of the returned HTML either for a full page render or in the case of an
 * AJAX call The first request, Ajax is not enabled (means no ajaxRequest parameter in the request) and hence the
 * super.processRender() method is called. This will hence call the processrender() of the Lifecycle object as this method
 * is not overidden in UIPortalApplicationLifecycle. There we simply render the bounded template (groovy usually). Note that
 * bounded template are also defined in component annotations, so for the current class it is UIPortalApplication.gtmpl On
 * second calls, request have the "ajaxRequest" parameter set to true in the URL. In that case the algorithm is a bit more
 * complex: a) The list of components that should be updated is extracted using the context.getUIComponentToUpdateByAjax()
 * method. That list was setup during the process action phase b) Portlets and other UI components to update are split in 2
 * different lists c) Portlets full content are returned and set with the tag <div class="PortalResponse"> d) Block to
 * updates (which are UI components) are set within the <div class="PortalResponseData"> tag e) Then the scripts and the
 * skins to reload are set in the <div class="PortalResponseScript">
 *///from   www  .ja  va2 s .c o  m
public void processRender(WebuiRequestContext context) throws Exception {
    PortalRequestContext pcontext = (PortalRequestContext) context;

    JavascriptManager jsMan = context.getJavascriptManager();
    // Add JS resource of current portal
    String portalOwner = pcontext.getPortalOwner();
    jsMan.loadScriptResource(ResourceScope.PORTAL, portalOwner);

    //
    Writer w = context.getWriter();
    if (!context.useAjax()) {
        // Support for legacy resource declaration
        jsMan.loadScriptResource(ResourceScope.SHARED, JavascriptConfigParser.LEGACY_JAVA_SCRIPT);
        // Need to add bootstrap as immediate since it contains the loader
        jsMan.loadScriptResource(ResourceScope.SHARED, "bootstrap");

        super.processRender(context);
    } else {
        UIMaskWorkspace uiMaskWS = getChildById(UIPortalApplication.UI_MASK_WS_ID);
        if (uiMaskWS.isUpdated())
            pcontext.addUIComponentToUpdateByAjax(uiMaskWS);
        if (getUIPopupMessages().hasMessage()) {
            pcontext.addUIComponentToUpdateByAjax(getUIPopupMessages());
        }

        Set<UIComponent> list = context.getUIComponentToUpdateByAjax();
        List<UIPortlet> uiPortlets = new ArrayList<UIPortlet>(3);
        List<UIComponent> uiDataComponents = new ArrayList<UIComponent>(5);

        if (list != null) {
            for (UIComponent uicomponent : list) {
                if (uicomponent instanceof UIPortlet)
                    uiPortlets.add((UIPortlet) uicomponent);
                else
                    uiDataComponents.add(uicomponent);
            }
        }
        w.write("<div class=\"PortalResponse\">");
        w.write("<div class=\"PortalResponseData\">");
        for (UIComponent uicomponent : uiDataComponents) {
            if (log.isDebugEnabled())
                log.debug("AJAX call: Need to refresh the UI component " + uicomponent.getName());
            renderBlockToUpdate(uicomponent, context, w);
        }
        w.write("</div>");

        if (!context.getFullRender()) {
            for (UIPortlet uiPortlet : uiPortlets) {
                if (log.isDebugEnabled())
                    log.debug("AJAX call: Need to refresh the Portlet " + uiPortlet.getId());

                w.write("<div class=\"PortletResponse\" style=\"display: none\">");
                w.append("<div class=\"PortletResponsePortletId\">" + uiPortlet.getId() + "</div>");
                w.append("<div class=\"PortletResponseData\">");

                /*
                 * If the portlet is using our UI framework or supports it then it will return a set of block to updates. If
                 * there is not block to update the javascript client will see that as a full refresh of the content part
                 */
                uiPortlet.processRender(context);

                w.append("</div>");
                w.append("<div class=\"PortletResponseScript\"></div>");
                w.write("</div>");
            }
        }
        w.write("<div class=\"MarkupHeadElements\">");
        List<String> headElems = ((PortalRequestContext) context).getExtraMarkupHeadersAsStrings();
        for (String elem : headElems) {
            w.write(elem);
        }
        w.write("</div>");
        w.write("<div class=\"LoadingScripts\">");
        writeLoadingScripts(pcontext);
        w.write("</div>");
        w.write("<div class=\"PortalResponseScript\">");
        JavascriptManager jsManager = pcontext.getJavascriptManager();
        String skin = getAddSkinScript(pcontext.getControllerContext(), list);
        if (skin != null) {
            jsManager.require("SHARED/skin", "skin").addScripts(skin);
        }
        w.write(jsManager.getJavaScripts());
        w.write("</div>");
        w.write("</div>");
    }
}

From source file:annis.gui.exporter.GeneralTextExporter.java

@Override
public void convertText(String queryAnnisQL, int contextLeft, int contextRight, Set<String> corpora,
        String keysAsString, String argsAsString, WebResource annisResource, Writer out) {
    try {// w ww.j  a  va2 s. co  m
        // int count = service.getCount(corpusIdList, queryAnnisQL);
        SaltProject queryResult = null;

        LinkedList<String> keys = new LinkedList<String>();

        if (keysAsString == null) {
            // auto set
            keys.add("tok");
            List<AnnisAttribute> attributes = new LinkedList<AnnisAttribute>();

            for (String corpus : corpora) {
                attributes.addAll(annisResource.path("corpora").path(URLEncoder.encode(corpus, "UTF-8"))
                        .path("annotations").queryParam("fetchvalues", "false")
                        .queryParam("onlymostfrequentvalues", "false").get(new AnnisAttributeListType()));
            }

            for (AnnisAttribute a : attributes) {
                if (a.getName() != null) {
                    String[] namespaceAndName = a.getName().split(":", 2);
                    if (namespaceAndName.length > 1) {
                        keys.add(namespaceAndName[1]);
                    } else {
                        keys.add(namespaceAndName[0]);
                    }
                }
            }
        } else {
            // manually specified
            String[] keysSplitted = keysAsString.split("\\,");
            for (String k : keysSplitted) {
                keys.add(k.trim());
            }
        }

        Map<String, String> args = new HashMap<String, String>();
        for (String s : argsAsString.split("&")) {
            String[] splitted = s.split("=", 2);
            String key = splitted[0];
            String val = "";
            if (splitted.length > 1) {
                val = splitted[1];
            }
            args.put(key, val);
        }

        final int stepSize = 10;
        int offset = 0;
        while (offset == 0 || (queryResult != null && queryResult.getSCorpusGraphs().size() > 0)) {

            try {
                queryResult = annisResource.path("search").path("annotate").queryParam("q", queryAnnisQL)
                        .queryParam("limit", "" + stepSize).queryParam("offset", "" + offset)
                        .queryParam("left", "" + contextLeft).queryParam("right", "" + contextRight)
                        .queryParam("corpora", StringUtils.join(corpora, ",")).get(SaltProject.class);
            } catch (UniformInterfaceException ex) {
                log.error(ex.getResponse().getEntity(String.class), ex);
            }

            convertText(LegacyGraphConverter.convertToResultSet(queryResult), keys, args, out, offset);

            out.flush();
            offset += stepSize;

        }

        out.append("\n");
        out.append("\n");
        out.append("finished");

    } catch (AnnisQLSemanticsException ex) {
        log.error(null, ex);
    } catch (AnnisQLSyntaxException ex) {
        log.error(null, ex);
    } catch (AnnisCorpusAccessException ex) {
        log.error(null, ex);
    } catch (RemoteException ex) {
        log.error(null, ex);
    } catch (IOException ex) {
        log.error(null, ex);
    }
}

From source file:com.redhat.rhn.frontend.taglibs.ListDisplayTag.java

private void renderAlphabar(Writer out) throws IOException {
    StringBuilder target = new StringBuilder();

    target.append("<div class=\"spacewalk-alphabar\">");

    target.append("<ul class=\"pagination pagination-sm\">");
    StringBuilder enabled = new StringBuilder("<li><a href=\"");
    enabled.append("?lower={1}");

    /**//ww w  . j av a 2s .c o  m
     * Add any query args we got to alphabar links.
     * We do it this way to ensure that any variables set on the page
     * carry from form submission (by pressing the pagination buttons)
     * to the alphabar links and vice-versa.
     */
    ServletRequest rq = pageContext.getRequest();
    String formvars = rq.getParameter("formvars");
    if (formvars != null) { //get vars from form submission
        String[] keys = formvars.split(",\\s?");
        for (int j = 0; j < keys.length; j++) {
            if (keys[j].equals("submitted")) {
                continue;
            }
            if (!PAGINATION_WASH_SET.contains(keys[j])) {
                String encodedParam = StringUtil.urlEncode(rq.getParameter(keys[j]));
                enabled.append("&amp;" + keys[j] + "=" + encodedParam);
            }
        }
    } else { //get vars from url
        Map qvars = rq.getParameterMap();
        qvars.remove("lower"); //don't repeat lower
        Iterator iter = qvars.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            if (key.equals("submitted")) {
                continue;
            }
            if (!PAGINATION_WASH_SET.contains(key)) {
                String encodedParam = StringUtil.urlEncode(rq.getParameter(key));
                enabled.append("&amp;" + key + "=" + encodedParam);
            }
        }
    }

    enabled.append("\">{0}</a><li>");
    AlphaBar ab = new AlphaBar(enabled.toString(), "<li class=\"disabled\"><span>{0}</span></li>");
    target.append(ab.getAlphaList(getPageList().getIndex()));
    target.append("</ul>");
    target.append("</div>");
    out.append(target.toString());
}

From source file:org.jboss.windup.reporting.html.freemarker.ArchiveReportSummarySerializer.java

@Override
public void execute(Environment env, Map map, TemplateModel[] templateModel,
        TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
    StringModel stringModel = (StringModel) map.get("archive");
    ArchiveReport archive = (ArchiveReport) stringModel.getWrappedObject();

    Writer bw = env.getOut();

    String jvmVersion = null;//from w  ww. ja va2s  . c  o  m
    String vendor = null;
    Version version = null;
    String summary = null;

    // eliminate links to same place..
    Set<Link> links = new TreeSet<Link>(new Comparator<Link>() {
        @Override
        public int compare(Link o1, Link o2) {
            String link1 = StringUtils.removeEnd(o1.getLink(), "/");
            String link2 = StringUtils.removeEnd(o2.getLink(), "/");

            if (StringUtils.equals(link1, link2)) {
                return 0;
            }
            if (o1 == null || o2 == null) {
                return 1;
            }

            return o1.getLink().compareTo(o2.getLink());
        }
    });

    if (archive.getDecorations() != null) {
        for (AbstractDecoration dr : archive.getDecorations()) {
            if (dr == null) {
                LOG.info("Skipping null decorator.");
                continue;
            }
            if (dr instanceof VendorResult) {
                vendor = ((VendorResult) dr).toString();
            }
            if (dr instanceof Version) {
                if ((version != null && version instanceof PomVersion)) {
                    // do nothing.
                } else if (version == null) {
                    version = ((Version) dr);
                } else {
                    version = ((Version) dr);
                }
            }
            if (dr instanceof Summary) {
                summary = ((Summary) dr).getDescription();
            }
            if (dr instanceof Link) {
                links.add((Link) dr);
            }
            if (dr instanceof JVMBuildVersionResult) {
                jvmVersion = ((JVMBuildVersionResult) dr).getJdkBuildVersion();
            }
        }
    }

    StringBuilder builder = new StringBuilder();
    if (StringUtils.isNotBlank(vendor)) {
        builder.append("<div class='archiveSummaryPart'><h3>Vendor</h3><p>").append(vendor)
                .append("</p></div>");
    }
    if (version != null) {
        builder.append("<div class='archiveSummaryPart'><h3>Version</h3><p>").append(version.toString())
                .append("</p></div>");
    }

    if (links.size() > 0) {
        for (Link link : links) {
            builder.append("<div class='archiveSummaryPart'><h3>Link</h3><p><a href='" + link.getLink() + "'>"
                    + link.getDescription() + "</p></a></div>");
        }
    }
    if (jvmVersion != null && builder.toString().length() > 0) {
        builder.append("<div class='archiveSummaryPart'><h3>JVM</h3><p>" + "<span class='jreVersion'>"
                + jvmVersion + "</span></div>");
    }
    if (StringUtils.isNotBlank(summary)) {
        builder.append("<div class='archiveSummaryPart'><h3>Description</h3><p>" + summary + "</p></div>");
    }

    String body = builder.toString();
    if (body.length() > 0) {
        bw.append("<div class='archiveSummary'>");
        bw.append(body);
        bw.append("</div>");
    }

}

From source file:se.liu.imt.mi.eee.validation.json.AOMtoJSONandYAMLSerializer.java

/**
 * Output given archetype to writer//from www .  j a v  a  2 s.c  om
 * 
 * @param archetype
 * @param out
 * @param flowstyle TODO
 * @throws IOException
 */
public void output(Archetype archetype, Writer out, boolean cADLforDefinition, FlowStyle flowstyle)
        throws IOException {

    Map<String, Object> archetypeAsMap = new LinkedHashMap<String, Object>(); //Linked to preserve ordering

    archetypeAsMap.put("adl_version", archetype.getAdlVersion());
    archetypeAsMap.put("archetype_id", archetype.getArchetypeId().getValue());
    if (archetype.getUid() != null)
        archetypeAsMap.put("uid", archetype.getUid().getValue());
    archetypeAsMap.put("concept", archetype.getConcept());
    archetypeAsMap.put("original_language", archetype.getOriginalLanguage());
    archetypeAsMap.put("translations", archetype.getTranslations());
    if (archetype.getParentArchetypeId() != null) {
        archetypeAsMap.put("parent_archetype_id", archetype.getParentArchetypeId());
    }
    archetypeAsMap.put("description", archetype.getDescription());

    if (cADLforDefinition) {
        StringWriter sw = new StringWriter();
        //lineSeparator = "\n";
        printCComplexObject(archetype.getDefinition(), 1, sw);
        String swStr = sw.toString(); //.replace("\n", ""+'\n');
        //               System.out.println("AOMtoYAMLSerializer.output()---------------");
        //               System.out.println(swStr);
        //               System.out.println("AOMtoYAMLSerializer.output()---------------");
        archetypeAsMap.put("definition", swStr);
    } else {
        archetypeAsMap.put("definition", archetype.getDefinition());
    }

    archetypeAsMap.put("ontology", archetype.getOntology());
    archetypeAsMap.put("invariants", archetype.getInvariants());
    archetypeAsMap.put("is_controlled", archetype.isControlled());

    String archetypeAsJsonString = gson.toJson(archetypeAsMap).replace("node_i_d:", "node_id:");

    boolean doYaml = true;
    if (doYaml) {
        // Without YAML typing:
        Object niceObjectTree = yaml.load(archetypeAsJsonString);
        //yaml.dump(niceObjectTree, out);   
        // With experimental YAML typing:               
        Tag rootTag = new Tag("http://www.openehr.org/releases/1.0.2/class/openehr.am.archetype.ARCHETYPE"); //TODO: Define real tag
        out.append(yaml.dumpAs(niceObjectTree, rootTag, flowstyle));
        //                     yaml.dump(archetypeAsMap, out);   
    } else {
        out.append(archetypeAsJsonString);
    }
    out.flush();
    out.close();
}

From source file:se.liu.imt.mi.eee.validation.json.JacksonBasedAOMtoJSONandYAML.java

/**
 * Output given archetype to writer/*from  w  w  w  .j  a  va2  s  .c  o m*/
 * 
 * @param archetype
 * @param out
 * @param flowstyle TODO
 * @throws IOException
 */
public void output(Archetype archetype, Writer out, boolean cADLforDefinition, FlowStyle flowstyle)
        throws IOException {

    Map<String, Object> archetypeAsMap = new LinkedHashMap<String, Object>(); //Linked to preserve ordering

    archetypeAsMap.put("adl_version", archetype.getAdlVersion());
    archetypeAsMap.put("archetype_id", archetype.getArchetypeId().getValue());
    if (archetype.getUid() != null)
        archetypeAsMap.put("uid", archetype.getUid().getValue());
    archetypeAsMap.put("concept", archetype.getConcept());
    archetypeAsMap.put("original_language", archetype.getOriginalLanguage());
    archetypeAsMap.put("translations", archetype.getTranslations());
    if (archetype.getParentArchetypeId() != null) {
        archetypeAsMap.put("parent_archetype_id", archetype.getParentArchetypeId());
    }
    /*
     archetypeAsMap.put("description", archetype.getDescription());               
    */
    if (cADLforDefinition) {
        StringWriter sw = new StringWriter();
        //lineSeparator = "\n";
        printCComplexObject(archetype.getDefinition(), 1, sw);
        String swStr = sw.toString(); //.replace("\n", ""+'\n');
        //               System.out.println("AOMtoYAMLSerializer.output()---------------");
        //               System.out.println(swStr);
        //               System.out.println("AOMtoYAMLSerializer.output()---------------");
        archetypeAsMap.put("definition", swStr);
    } else {
        archetypeAsMap.put("definition", archetype.getDefinition());
    }

    archetypeAsMap.put("ontology", archetype.getOntology());
    archetypeAsMap.put("invariants", archetype.getInvariants());
    archetypeAsMap.put("is_controlled", archetype.isControlled());

    /// GSON
    //String archetypeAsJsonString = gson.toJson(archetypeAsMap).replace("node_i_d:", "node_id:");

    /// Jackson
    //String archetypeAsJsonString = mapper.writeValueAsString(archetype);
    //String archetypeAsJsonString = mapper.writeValueAsString(archetype.getDefinition());
    String archetypeAsJsonString = mapper.writeValueAsString(archetypeAsMap);

    System.out.println("*** JacksonBasedAOMtoJSONandYAML.output() - using Jackson! ***");

    if (doYaml) {
        // Without YAML typing:
        Object niceObjectTree = yaml.load(archetypeAsJsonString);
        //yaml.dump(niceObjectTree, out);   
        // With experimental YAML typing:               
        Tag rootTag = new Tag("http://www.openehr.org/releases/1.0.2/class/openehr.am.archetype.ARCHETYPE"); //TODO: Define real tag
        out.append(yaml.dumpAs(niceObjectTree, rootTag, flowstyle));
        //                     yaml.dump(archetypeAsMap, out);   
    } else {
        out.append(archetypeAsJsonString);
    }
    out.flush();
    out.close();
}

From source file:annis.visualizers.iframe.dependency.VakyarthaDependencyTree.java

public void printHTMLOutput(VisualizerInput input, Writer writer) {
    SDocumentGraph sDocumentGraph = input.getSResult().getSDocumentGraph();

    for (SNode n : sDocumentGraph.getSNodes()) {
        if (selectNode(n)) {
            SFeature sFeature = n.getSFeature(ANNIS_NS, FEAT_TOKENINDEX);
            int tokenIdx = sFeature != null ? (int) (long) sFeature.getSValueSNUMERIC() : -1;
            selectedNodes.put(n, tokenIdx);
        }//  w  ww.ja  v a 2s.  c  o  m
    }

    Map<SNode, Integer> node2Int = new HashMap<SNode, Integer>();
    int count = 0;
    for (SNode tok : selectedNodes.keySet()) {
        node2Int.put(tok, count++);
    }

    try {
        println("<html>", writer);
        println("<head>", writer);

        LinkedList<String> fontsText = new LinkedList<String>();
        LinkedList<String> fontsDep = new LinkedList<String>();
        if (input.getFont() != null) {
            fontsText.add(input.getFont().getName());
            fontsDep.add(input.getFont().getName());
            println("<link href=\"" + input.getFont().getUrl() + "\" rel=\"stylesheet\" type=\"text/css\" >",
                    writer);
        }
        fontsText.add("sans-serif");
        fontsDep.add("serif");

        println("<script type=\"text/javascript\" src=\""
                + input.getResourcePath("vakyartha/jquery-1.9.0.min.js") + "\"></script>", writer);
        println("<script type=\"text/javascript\" src=\"" + input.getResourcePath("vakyartha/raphael-min.js")
                + "\"></script>", writer);
        println("<script type=\"text/javascript\" src=\""
                + input.getResourcePath("vakyartha/vakyarthaDependency.js") + "\"></script>", writer);

        // output the data for the javascript
        println("<script type=\"text/javascript\">", writer);
        println("fcolors={};", writer);
        println("shownfeatures=[\"t\"];", writer);
        println("tokens=new Object();", writer);

        count = 0;
        for (SNode node : selectedNodes.keySet()) {
            JSONObject vakyarthaObject = new JSONObject();

            String completeAnnotation = getAnnotation(node);
            String annotationValue = completeAnnotation.replaceFirst(".*=", "");
            String text = getText(node, input);

            // decide, if the visualization is token based.
            if (mappings.containsKey(MAPPING_NODE_KEY)) {
                vakyarthaObject.put("t", annotationValue);
            } else {
                vakyarthaObject.put("t", text);
            }
            vakyarthaObject.put("annotation", annotationValue);
            vakyarthaObject.put("text", text);
            vakyarthaObject.put("tooltip", completeAnnotation);

            JSONObject govs = new JSONObject();
            EList<Edge> sEdges = node.getSGraph().getInEdges(node.getSId());

            for (Edge e : sEdges) {
                if (!(e instanceof SPointingRelation)) {
                    continue;
                }

                SPointingRelation sRelation = (SPointingRelation) e;
                SNode source = (SNode) sRelation.getSource();

                String label = "";
                for (SAnnotation anno : sRelation.getSAnnotations()) {
                    label = anno.getSValueSTEXT();
                    break;
                }

                if (sRelation.getSource() != null && node2Int.containsKey(source)) {
                    govs.put(String.valueOf(node2Int.get(source)), label);
                }
            }

            vakyarthaObject.put("govs", govs);
            JSONObject attris = new JSONObject();

            JSONObject tAttris = new JSONObject();
            String tokenColor = "black";
            if (input.getMarkedAndCovered().containsKey(node)) {
                int colorNumber = ((int) (long) input.getMarkedAndCovered().get(node)) - 1;
                tokenColor = MatchedNodeColors.values()[colorNumber].getHTMLColor();
            }
            tAttris.put("fill", tokenColor);
            tAttris.put("font", "11px " + StringUtils.join(fontsText, ","));

            attris.put("t", tAttris);

            JSONObject depAttris = new JSONObject();
            depAttris.put("fill", "#999");
            depAttris.put("font-style", "italic");
            depAttris.put("font", "12px " + StringUtils.join(fontsDep, ","));
            attris.put("deptext", depAttris);
            vakyarthaObject.put("attris", attris);

            writer.append("tokens[").append("" + count++).append("]=");
            writer.append(vakyarthaObject.toString().replaceAll("\n", " "));
            writer.append(";\n");
        }

        println("</script>", writer);

        println("</head>", writer);
        println("<body>", writer);

        // the div to render the javascript to
        println("<div id=\"holder\" style=\"background:white; position:relative;\"> </div>", writer);

        println("</body>", writer);
        println("</html>", writer);
    } catch (JSONException ex) {
        log.error(null, ex);
    } catch (IOException ex) {
        log.error(null, ex);
    }
}

From source file:ru.apertum.qsystem.client.forms.FAdmin.java

private void buttonExportToCSVActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExportToCSVActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.setDialogTitle(getLocaleMessage("save.statictic"));
        fc.setFileFilter(new FileFilter() {

            @Override//from   ww  w  .  ja  va 2s .co  m
            public boolean accept(File f) {
                return !f.isFile() || f.getAbsolutePath().toLowerCase().endsWith(".csv");
            }

            @Override
            public String getDescription() {
                return getLocaleMessage("files.type.csv");
            }
        });
        //fc.setCurrentDirectory(new File("config"));
        //fc.setSelectedFile(new File(configuration.getSystemName()));
        fc.setDialogType(JFileChooser.SAVE_DIALOG);
        if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            final File file;
            //This is where a real application would open the file.
            if (!fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".csv")) {
                file = new File(fc.getSelectedFile().getAbsoluteFile() + ".csv");
            } else {
                file = fc.getSelectedFile();
            }

            Spring.getInstance().getHt().getSessionFactory().openSession().doWork((Connection connection) -> {
                final GregorianCalendar gc = new GregorianCalendar();
                gc.setTime(dateChooserStartCsv.getDate());
                gc.set(GregorianCalendar.HOUR_OF_DAY, 0);
                gc.set(GregorianCalendar.MINUTE, 0);
                gc.set(GregorianCalendar.SECOND, 0);
                gc.set(GregorianCalendar.MILLISECOND, 0);
                final String std = Uses.format_for_rep.format(gc.getTime());
                gc.setTime(dateChooserFinishCsv.getDate());
                gc.set(GregorianCalendar.HOUR_OF_DAY, 0);
                gc.set(GregorianCalendar.MINUTE, 0);
                gc.set(GregorianCalendar.SECOND, 0);
                gc.set(GregorianCalendar.MILLISECOND, 0);
                gc.add(GregorianCalendar.HOUR, 24);
                final String find = Uses.format_for_rep.format(gc.getTime());
                final String sql = " SELECT " + "    s.client_id as id, "
                        + "    concat(c.service_prefix , c.number) as num, " + "    c.input_data as inp,  "
                        + "    DATE_FORMAT(s.client_stand_time, '%d.%m.%y %H:%i') as stnd, "
                        + "    sv.name as srv, " + "    DATE_FORMAT(s.user_start_time, '%d.%m.%y %H:%i') as strt, "
                        + "    DATE_FORMAT(s.user_finish_time, '%d.%m.%y %H:%i') as fin, " + "    u.name as usr, "
                        + "    s.client_wait_period as wt, " + "    s.user_work_period as wrk, "
                        + "    IFNULL(r.name, '') as res "
                        + " FROM statistic s left join results r on s.results_id=r.id, clients c, users u, services sv "
                        + " WHERE s.client_id=c.id and s.user_id=u.id and s.service_id=sv.id "
                        + "    and s.client_stand_time>='" + std + "' and s.client_stand_time<='" + find + "'";
                try (ResultSet set = connection.createStatement().executeQuery(sql)) {
                    final Writer writer;
                    try {
                        writer = new OutputStreamWriter(new FileOutputStream(file), "cp1251").append("");
                        writer.append("");
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.number"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.data"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.stand_time"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.service_name"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.start_time"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.finish_time"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.user"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.wait"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.work"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.result"));
                        writer.append('\n');

                        while (set.next()) {
                            writer.append(set.getString("id"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("num"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("inp"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("stnd"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(
                                    set.getString("srv").replace(cbSeparateCSV.getSelectedItem().toString(), " "));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("strt"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("fin"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("usr"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("wt"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("wrk"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("res"));
                            writer.append('\n');
                        }
                        //generate whatever data you want

                        writer.flush();
                        writer.close();
                    } catch (IOException ex) {
                        throw new ClientException(ex);
                    }
                }
                JOptionPane.showMessageDialog(fc, getLocaleMessage("stat.saved"), getLocaleMessage("stat.saving"),
                        JOptionPane.INFORMATION_MESSAGE);
            });

        }
    }