Search in sources :

Example 86 with VelocityContext

use of org.apache.velocity.VelocityContext in project celements-blog by celements.

the class NewsletterReceivers method getHtmlContent.

private String getHtmlContent(XWikiDocument doc, String baseURL) throws XWikiException {
    String header = "";
    if ((baseURL != null) && !"".equals(baseURL.trim())) {
        header = "<base href='" + baseURL + "' />\n";
    }
    String renderLang = getContext().getLanguage();
    VelocityContext vcontext = (VelocityContext) getContext().get("vcontext");
    XWikiMessageTool msgTool = getWebUtilsService().getMessageTool(renderLang);
    DocumentReference headerRef = getWebUtilsService().resolveDocumentReference("LocalMacros.NewsletterHTMLheader");
    if (getContext().getWiki().exists(headerRef, getContext())) {
        LOGGER.debug("Additional header found.");
        LOGGER.debug("doc=" + doc + ", context.language=" + getContext().getLanguage(), doc, getContext());
        LOGGER.debug("context=" + getContext());
        vcontext.put("msg", msgTool);
        vcontext.put("adminMsg", msgTool);
        header += renderCommand.renderDocument(headerRef, renderLang);
        LOGGER.debug("Additional header rendered.");
    } else {
        LOGGER.debug("No additional header. Doc does not exist: " + headerRef);
    }
    LOGGER.debug("rendering content in " + renderLang);
    getContext().setLanguage(renderLang);
    renderCommand.setDefaultPageType("RichText");
    vcontext.put("msg", msgTool);
    vcontext.put("adminMsg", msgTool);
    String content = renderCommand.renderCelementsDocument(doc.getDocumentReference(), renderLang, "view");
    content = Utils.replacePlaceholders(content, getContext());
    if (getContext().getWiki().getXWikiPreferenceAsInt("newsletter_embed_all_images", "celements.newsletter.embedAllImages", 0, getContext()) == 1) {
        content = getNewsletterAttachmentService().embedImagesInContent(content);
    }
    String footer = "";
    DocumentReference footerRef = getWebUtilsService().resolveDocumentReference("LocalMacros.NewsletterHTMLfooter");
    if (getContext().getWiki().exists(footerRef, getContext())) {
        getContext().setLanguage(renderLang);
        LOGGER.debug("Additional footer found.");
        LOGGER.debug("doc={} , context.language={}", doc, getContext().getLanguage());
        LOGGER.debug("context={}", getContext());
        vcontext.put("msg", msgTool);
        vcontext.put("adminMsg", msgTool);
        footer += renderCommand.renderDocument(footerRef, renderLang) + "\n";
        LOGGER.debug("Additional footer rendered.");
    } else {
        LOGGER.debug("No additional footer. Doc does not exist: {} ", footerRef);
    }
    XWikiMessageTool messageTool = getWebUtilsService().getMessageTool(renderLang);
    footer += messageTool.get("cel_newsletter_html_footer_message", Arrays.asList(doc.getExternalURL("view", getContext())));
    LOGGER.debug("Header: [" + header + "]");
    LOGGER.debug("Footer: [" + footer + "]");
    return header + content + footer;
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) XWikiMessageTool(com.xpn.xwiki.web.XWikiMessageTool) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 87 with VelocityContext

use of org.apache.velocity.VelocityContext in project celements-blog by celements.

the class NewsletterAttachmentServiceTest method testGetEmbedAttList_validList.

@Test
public void testGetEmbedAttList_validList() {
    VelocityContext vcontext = (VelocityContext) getContext().get("vcontext");
    List<Attachment> list = new ArrayList<>();
    Attachment att = new Attachment(null, new XWikiAttachment(), getContext());
    list.add(att);
    vcontext.put("nlEmbedAttList", list);
    List<Attachment> resList = service.getAttachmentList(true);
    assertNotNull(resList);
    assertSame(att, resList.get(0));
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) ArrayList(java.util.ArrayList) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Attachment(com.xpn.xwiki.api.Attachment) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Test(org.junit.Test)

Example 88 with VelocityContext

use of org.apache.velocity.VelocityContext in project bioformats by openmicroscopy.

the class FormatPageAutogen method writeFormatTable.

public void writeFormatTable() throws Exception {
    File doc = new File("../../docs/sphinx/");
    if (!doc.exists()) {
        boolean success = doc.mkdir();
        if (!success) {
            throw new IOException("Could not create " + doc.getAbsolutePath());
        }
    }
    VelocityEngine engine = VelocityTools.createEngine();
    VelocityContext context = VelocityTools.createContext();
    IniTable[] sortedTable = new IniTable[data.size()];
    for (int i = 0; i < data.size(); i++) {
        IniTable table = data.get(i);
        table.put("pagename", getPageName(table.get(IniTable.HEADER_KEY), table.get("pagename")));
        sortedTable[i] = table;
    }
    Arrays.sort(sortedTable, new Comparator<IniTable>() {

        @Override
        public int compare(IniTable t1, IniTable t2) {
            String page1 = t1.get("pagename");
            String page2 = t2.get("pagename");
            return page1.compareTo(page2);
        }
    });
    context.put("formats", sortedTable);
    context.put("count", sortedTable.length);
    VelocityTools.processTemplate(engine, context, TABLE_TEMPLATE, "../../docs/sphinx/supported-formats.rst");
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) VelocityContext(org.apache.velocity.VelocityContext) IniTable(loci.common.IniTable) IOException(java.io.IOException) File(java.io.File)

Example 89 with VelocityContext

use of org.apache.velocity.VelocityContext in project sw360portal by sw360.

the class OutputGenerator method getConfiguredVelocityContext.

public VelocityContext getConfiguredVelocityContext() {
    Properties p = new Properties();
    p.setProperty(RuntimeConstants.RESOURCE_LOADER, "file, class");
    p.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CommonUtils.SYSTEM_CONFIGURATION_PATH);
    p.setProperty("file.resource.loader.class", FileResourceLoader.class.getName());
    p.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
    Velocity.init(p);
    ToolManager velocityToolManager = new ToolManager();
    velocityToolManager.configure(VELOCITY_TOOLS_FILE);
    return new VelocityContext(velocityToolManager.createContext());
}
Also used : FileResourceLoader(org.apache.velocity.runtime.resource.loader.FileResourceLoader) VelocityContext(org.apache.velocity.VelocityContext) ClasspathResourceLoader(org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader) ToolManager(org.apache.velocity.tools.ToolManager)

Example 90 with VelocityContext

use of org.apache.velocity.VelocityContext in project sw360portal by sw360.

the class OutputGenerator method renderTemplateWithDefaultValues.

/**
 * Creates a velocity context and fills it with the default, commonly used
 * values:
 * <ul>
 * <li>allLicenseNamesWithTexts: list of {@link LicenseNameWithText} objects,
 * sorted by license name</li>
 * <li>licenseNameWithTextToReferenceId: map from the license name to a unique
 * id inside the file. May be used to reference a license.</li>
 * <li>licenseInfoResults: map of {@link LicenseInfoParsingResult} objects,
 * where the key is the name of the release. The licenses within the objects are
 * sorted by name. Contains only the results with status {@link LicenseInfoRequestStatus#SUCCESS}</li>
 * <li>licenseInfoErrorResults: map {@link List}of {@link LicenseInfoParsingResult} objects,
 * where the key is the name of the release. Contains only the results with status other than
 * {@link LicenseInfoRequestStatus#SUCCESS}. These results are not merged, that's why the map values are lists.</li>
 * <li>acknowledgments: map of acknowledgments for a release where the key is
 * the release and the value is a set of strings (acknowledgments)</li>
 * </ul>
 * The given file will be used as velocity template and will be rendered with
 * the described data.
 *
 * @param projectLicenseInfoResults
 *            parsing results to be rendered
 * @param file
 *            name of template file
 * @return rendered template
 */
protected String renderTemplateWithDefaultValues(Collection<LicenseInfoParsingResult> projectLicenseInfoResults, String file, String projectTitle, String licenseInfoHeaderText) {
    VelocityContext vc = getConfiguredVelocityContext();
    // set header
    vc.put(LICENSE_INFO_PROJECT_TITLE, projectTitle);
    vc.put(LICENSE_INFO_HEADER_TEXT, licenseInfoHeaderText);
    // sorted lists of all license to be displayed at the end of the file at once
    List<LicenseNameWithText> licenseNamesWithTexts = getSortedLicenseNameWithTexts(projectLicenseInfoResults);
    vc.put(ALL_LICENSE_NAMES_WITH_TEXTS, licenseNamesWithTexts);
    // assign a reference id to each license in order to only display references for
    // each release. The references will point to
    // the list with all details at the and of the file (see above)
    int referenceId = 1;
    Map<LicenseNameWithText, Integer> licenseToReferenceId = Maps.newHashMap();
    for (LicenseNameWithText licenseNamesWithText : licenseNamesWithTexts) {
        licenseToReferenceId.put(licenseNamesWithText, referenceId++);
    }
    vc.put(LICENSE_REFERENCE_ID_MAP_CONTEXT_PROPERTY, licenseToReferenceId);
    Map<Boolean, List<LicenseInfoParsingResult>> partitionedResults = projectLicenseInfoResults.stream().collect(Collectors.partitioningBy(r -> r.getStatus() == LicenseInfoRequestStatus.SUCCESS));
    List<LicenseInfoParsingResult> goodResults = partitionedResults.get(true);
    Map<String, List<LicenseInfoParsingResult>> badResultsPerRelease = partitionedResults.get(false).stream().collect(Collectors.groupingBy(this::getComponentLongName));
    vc.put(LICENSE_INFO_ERROR_RESULTS_CONTEXT_PROPERTY, badResultsPerRelease);
    // be sure that the licenses inside a release are sorted by id. This looks nicer
    SortedMap<String, LicenseInfoParsingResult> sortedLicenseInfos = getSortedLicenseInfos(goodResults);
    // this will effectively change the objects in the collection and therefore the
    // objects in the sorted map above
    sortLicenseNamesWithinEachLicenseInfoById(sortedLicenseInfos.values(), licenseToReferenceId);
    vc.put(LICENSE_INFO_RESULTS_CONTEXT_PROPERTY, sortedLicenseInfos);
    // also display acknowledgments
    SortedMap<String, Set<String>> acknowledgements = getSortedAcknowledgements(sortedLicenseInfos);
    vc.put(ACKNOWLEDGEMENTS_CONTEXT_PROPERTY, acknowledgements);
    StringWriter sw = new StringWriter();
    Velocity.mergeTemplate(file, "utf-8", vc, sw);
    IOUtils.closeQuietly(sw);
    return sw.toString();
}
Also used : SW360Utils(org.eclipse.sw360.datahandler.common.SW360Utils) java.util(java.util) StringWriter(java.io.StringWriter) RuntimeConstants(org.apache.velocity.runtime.RuntimeConstants) ClasspathResourceLoader(org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader) LicenseNameWithTextUtils(org.eclipse.sw360.licenseinfo.util.LicenseNameWithTextUtils) SW360Exception(org.eclipse.sw360.datahandler.thrift.SW360Exception) Maps(com.google.common.collect.Maps) VelocityContext(org.apache.velocity.VelocityContext) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) ToolManager(org.apache.velocity.tools.ToolManager) IOUtils(org.apache.commons.io.IOUtils) CommonUtils(org.eclipse.sw360.datahandler.common.CommonUtils) org.eclipse.sw360.datahandler.thrift.licenseinfo(org.eclipse.sw360.datahandler.thrift.licenseinfo) Velocity(org.apache.velocity.app.Velocity) NotNull(org.jetbrains.annotations.NotNull) FileResourceLoader(org.apache.velocity.runtime.resource.loader.FileResourceLoader) VelocityContext(org.apache.velocity.VelocityContext) StringWriter(java.io.StringWriter)

Aggregations

VelocityContext (org.apache.velocity.VelocityContext)492 StringWriter (java.io.StringWriter)156 Template (org.apache.velocity.Template)120 Test (org.junit.Test)72 IOException (java.io.IOException)60 VelocityEngine (org.apache.velocity.app.VelocityEngine)53 File (java.io.File)47 ArrayList (java.util.ArrayList)39 HashMap (java.util.HashMap)36 Map (java.util.Map)36 Identity (org.olat.core.id.Identity)36 Context (org.apache.velocity.context.Context)32 MailTemplate (org.olat.core.util.mail.MailTemplate)28 Writer (java.io.Writer)22 Properties (java.util.Properties)20 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)19 ParseErrorException (org.apache.velocity.exception.ParseErrorException)16 ClasspathResourceLoader (org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader)16 FileWriter (java.io.FileWriter)15 OutputStreamWriter (java.io.OutputStreamWriter)14