Search in sources :

Example 1 with Evaluated

use of com.opensymphony.xwork2.util.Evaluated in project struts by apache.

the class OgnlValueStackTest method reloadTestContainerConfiguration.

private void reloadTestContainerConfiguration(Boolean allowStaticMethod, Boolean allowStaticField) throws Exception {
    loadConfigurationProviders(new StubConfigurationProvider() {

        @Override
        public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException {
            // undefined values then should be evaluated to false
            if (props.containsKey(StrutsConstants.STRUTS_ALLOW_STATIC_METHOD_ACCESS)) {
                props.remove(StrutsConstants.STRUTS_ALLOW_STATIC_METHOD_ACCESS);
            }
            if (props.containsKey(StrutsConstants.STRUTS_ALLOW_STATIC_FIELD_ACCESS)) {
                props.remove(StrutsConstants.STRUTS_ALLOW_STATIC_FIELD_ACCESS);
            }
            if (allowStaticMethod != null) {
                props.setProperty(StrutsConstants.STRUTS_ALLOW_STATIC_METHOD_ACCESS, "" + allowStaticMethod);
            }
            if (allowStaticField != null) {
                props.setProperty(StrutsConstants.STRUTS_ALLOW_STATIC_FIELD_ACCESS, "" + allowStaticField);
            }
        }
    });
    ognlUtil = container.getInstance(OgnlUtil.class);
}
Also used : ContainerBuilder(com.opensymphony.xwork2.inject.ContainerBuilder) StubConfigurationProvider(com.opensymphony.xwork2.test.StubConfigurationProvider) LocatableProperties(com.opensymphony.xwork2.util.location.LocatableProperties) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException)

Example 2 with Evaluated

use of com.opensymphony.xwork2.util.Evaluated in project entando-core by entando.

the class TestContentAction method testValidate_4.

/*
	 * We test, among other things the CheckBox attribute
	 */
public void testValidate_4() throws Throwable {
    String contentTypeCode = "RAH";
    String contentOnSessionMarker = this.extractSessionMarker(contentTypeCode, ApsAdminSystemConstants.ADD);
    String insertedDescr = "XXX Prova Validazione XXX";
    try {
        String result = this.executeCreateNewVoid(contentTypeCode, "descr", Content.STATUS_DRAFT, Group.FREE_GROUP_NAME, "admin");
        assertEquals(Action.SUCCESS, result);
        Content contentOnSession = this.getContentOnEdit(contentOnSessionMarker);
        assertNotNull(contentOnSession);
        this.initContentAction("/do/jacms/Content", "save", contentOnSessionMarker);
        this.setUserOnSession("admin");
        this.addParameter("descr", insertedDescr);
        this.addParameter("Monotext:email", "wrongEmailAddress");
        this.addParameter("Number:Numero", "wrongNumber");
        this.addParameter("CheckBox:Checkbox", "true");
        result = this.executeAction();
        assertEquals(Action.INPUT, result);
        ActionSupport action = this.getAction();
        Map<String, List<String>> fieldErros = action.getFieldErrors();
        assertEquals(2, fieldErros.size());
        List<String> emailFieldErrors = fieldErros.get("Monotext:email");
        assertEquals(1, emailFieldErrors.size());
        List<String> numberFieldErrors = fieldErros.get("Number:Numero");
        assertEquals(1, numberFieldErrors.size());
        Content content = this.getContentOnEdit(contentOnSessionMarker);
        assertNotNull(content);
        assertTrue(content.getAttributeMap().containsKey("Checkbox"));
        BooleanAttribute attribute = (BooleanAttribute) content.getAttribute("Checkbox");
        assertNotNull(attribute);
        assertEquals("CheckBox", attribute.getType());
        assertEquals(Boolean.TRUE, attribute.getValue());
        this.initContentAction("/do/jacms/Content", "save", contentOnSessionMarker);
        this.setUserOnSession("admin");
        this.addParameter("mainGroup", Group.FREE_GROUP_NAME);
        this.addParameter("descr", insertedDescr);
        this.addParameter("Monotext:email", "wrongEmailAddress");
        this.addParameter("Number:Numero", "wrongNumber");
        // LEAVING the Checkbox parameter will result in the checkbox attribute being later evaluated as 'false'
        result = this.executeAction();
        assertEquals(Action.INPUT, result);
        content = this.getContentOnEdit(contentOnSessionMarker);
        assertNotNull(content);
        assertTrue(content.getAttributeMap().containsKey("Checkbox"));
        attribute = (BooleanAttribute) content.getAttribute("Checkbox");
        assertNotNull(attribute);
        assertEquals("CheckBox", attribute.getType());
        assertEquals(Boolean.FALSE, attribute.getValue());
    } catch (Throwable t) {
        throw t;
    } finally {
        this.removeTestContent(insertedDescr);
    }
}
Also used : BooleanAttribute(com.agiletec.aps.system.common.entity.model.attribute.BooleanAttribute) Content(com.agiletec.plugins.jacms.aps.system.services.content.model.Content) ActionSupport(com.opensymphony.xwork2.ActionSupport) List(java.util.List)

Example 3 with Evaluated

use of com.opensymphony.xwork2.util.Evaluated in project struts by apache.

the class Date method end.

@Override
public boolean end(Writer writer, String body) {
    TextProvider textProvider = findProviderInStack();
    ZonedDateTime date = null;
    final ZoneId tz = getTimeZone();
    // find the name on the valueStack
    Object dateObject = findValue(name);
    if (dateObject instanceof java.util.Date) {
        date = ((java.util.Date) dateObject).toInstant().atZone(tz);
    } else if (dateObject instanceof Calendar) {
        date = ((Calendar) dateObject).toInstant().atZone(tz);
    } else if (dateObject instanceof Long) {
        date = Instant.ofEpochMilli((long) dateObject).atZone(tz);
    } else if (dateObject instanceof LocalDateTime) {
        date = ((LocalDateTime) dateObject).atZone(tz);
    } else if (dateObject instanceof LocalDate) {
        date = ((LocalDate) dateObject).atStartOfDay(tz);
    } else if (dateObject instanceof Instant) {
        date = ((Instant) dateObject).atZone(tz);
    } else {
        if (devMode) {
            String developerNotification = "";
            if (textProvider != null) {
                developerNotification = textProvider.getText("devmode.notification", "Developer Notification:\n{0}", new String[] { "Expression [" + name + "] passed to <s:date/> tag which was evaluated to [" + dateObject + "](" + (dateObject != null ? dateObject.getClass() : "null") + ") isn't supported!" });
            }
            LOG.warn(developerNotification);
        } else {
            LOG.debug("Expression [{}] passed to <s:date/> tag which was evaluated to [{}]({}) isn't supported!", name, dateObject, (dateObject != null ? dateObject.getClass() : "null"));
        }
    }
    // try to find the format on the stack
    if (format != null) {
        format = findString(format);
    }
    String msg;
    if (date != null) {
        if (textProvider != null) {
            if (nice) {
                msg = formatTime(textProvider, date);
            } else {
                msg = formatDate(textProvider, date);
            }
            if (msg != null) {
                try {
                    if (getVar() == null) {
                        writer.write(msg);
                    } else {
                        putInContext(msg);
                    }
                } catch (IOException e) {
                    LOG.error("Could not write out Date tag", e);
                }
            }
        }
    }
    return super.end(writer, "");
}
Also used : LocalDateTime(java.time.LocalDateTime) ZoneId(java.time.ZoneId) Calendar(java.util.Calendar) Instant(java.time.Instant) IOException(java.io.IOException) TextProvider(com.opensymphony.xwork2.TextProvider) LocalDate(java.time.LocalDate) LocalDate(java.time.LocalDate) ZonedDateTime(java.time.ZonedDateTime)

Example 4 with Evaluated

use of com.opensymphony.xwork2.util.Evaluated in project struts by apache.

the class TextProviderHelper method getText.

/**
 * <p>Get a message from the first TextProvider encountered in the stack.
 * If the first TextProvider doesn't provide the message the default message is returned.</p>
 * The stack is searched if if no TextProvider is found, or the message is not found.
 * @param key             the message key in the resource bundle
 * @param defaultMessage  the message to return if not found (evaluated for OGNL)
 * @param args            an array args to be used in a {@link java.text.MessageFormat} message
 * @param stack           the value stack to use for finding the text
 *
 * @return the message if found, otherwise the defaultMessage
 */
public static String getText(String key, String defaultMessage, List<Object> args, ValueStack stack) {
    String msg = null;
    TextProvider tp = null;
    for (Object o : stack.getRoot()) {
        if (o instanceof TextProvider) {
            tp = (TextProvider) o;
            msg = tp.getText(key, null, args, stack);
            break;
        }
    }
    if (msg == null) {
        // use the defaultMessage literal value
        msg = defaultMessage;
        msg = StringEscapeUtils.escapeHtml4(msg);
        msg = StringEscapeUtils.escapeEcmaScript(msg);
        LOG.debug("Message for key '{}' is null, returns escaped default message [{}]", key, msg);
        if (LOG.isWarnEnabled()) {
            if (tp != null) {
                LOG.warn("The first TextProvider in the ValueStack ({}) could not locate the message resource with key '{}'", tp.getClass().getName(), key);
            } else {
                LOG.warn("Could not locate the message resource '{}' as there is no TextProvider in the ValueStack.", key);
            }
        }
    }
    return msg;
}
Also used : TextProvider(com.opensymphony.xwork2.TextProvider)

Example 5 with Evaluated

use of com.opensymphony.xwork2.util.Evaluated in project struts by apache.

the class JasperReportsResult method doExecute.

protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    // Will throw a runtime exception if no "datasource" property. TODO Best place for that is...?
    initializeProperties(invocation);
    LOG.debug("Creating JasperReport for dataSource = {}, format = {}", dataSource, format);
    HttpServletRequest request = invocation.getInvocationContext().getServletRequest();
    HttpServletResponse response = invocation.getInvocationContext().getServletResponse();
    // TODO Set content type to config settings?
    if ("contype".equals(request.getHeader("User-Agent"))) {
        try (OutputStream outputStream = response.getOutputStream()) {
            response.setContentType("application/pdf");
            response.setContentLength(0);
        } catch (IOException e) {
            LOG.error("Error writing report output", e);
            throw new ServletException(e.getMessage(), e);
        }
        return;
    }
    // Construct the data source for the report.
    ValueStack stack = invocation.getStack();
    ValueStackDataSource stackDataSource = null;
    Connection conn = (Connection) stack.findValue(connection);
    if (conn == null) {
        boolean evaluated = parsedDataSource != null && !parsedDataSource.equals(dataSource);
        boolean reevaluate = !evaluated || isAcceptableExpression(parsedDataSource);
        if (reevaluate) {
            stackDataSource = new ValueStackDataSource(stack, parsedDataSource, wrapField);
        } else {
            throw new ServletException(String.format("Error building dataSource for excluded or not accepted [%s]", parsedDataSource));
        }
    }
    if ("https".equalsIgnoreCase(request.getScheme())) {
        // set the the HTTP Header to work around IE SSL weirdness
        response.setHeader("CACHE-CONTROL", "PRIVATE");
        response.setHeader("Cache-Control", "maxage=3600");
        response.setHeader("Pragma", "public");
        response.setHeader("Accept-Ranges", "none");
    }
    // Determine the directory that the report file is in and set the reportDirectory parameter
    // For WW 2.1.7:
    // ServletContext servletContext = ((ServletConfig) invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONFIG)).getServletContext();
    ServletContext servletContext = invocation.getInvocationContext().getServletContext();
    String systemId = servletContext.getRealPath(finalLocation);
    Map<String, Object> parameters = new ValueStackShadowMap(stack);
    File directory = new File(systemId.substring(0, systemId.lastIndexOf(File.separator)));
    parameters.put("reportDirectory", directory);
    parameters.put(JRParameter.REPORT_LOCALE, invocation.getInvocationContext().getLocale());
    // put timezone in jasper report parameter
    if (timeZone != null) {
        timeZone = conditionalParse(timeZone, invocation);
        final TimeZone tz = TimeZone.getTimeZone(timeZone);
        if (tz != null) {
            // put the report time zone
            parameters.put(JRParameter.REPORT_TIME_ZONE, tz);
        }
    }
    // Add any report parameters from action to param map.
    boolean evaluated = parsedReportParameters != null && !parsedReportParameters.equals(reportParameters);
    boolean reevaluate = !evaluated || isAcceptableExpression(parsedReportParameters);
    Map reportParams = reevaluate ? (Map) stack.findValue(parsedReportParameters) : null;
    if (reportParams != null) {
        LOG.debug("Found report parameters; adding to parameters...");
        parameters.putAll(reportParams);
    }
    ByteArrayOutputStream output;
    JasperPrint jasperPrint;
    // Fill the report and produce a print object
    try {
        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(new File(systemId));
        if (conn == null) {
            jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, stackDataSource);
        } else {
            jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
        }
    } catch (JRException e) {
        LOG.error("Error building report for uri {}", systemId, e);
        throw new ServletException(e.getMessage(), e);
    }
    // Export the print object to the desired output format
    try {
        if (contentDisposition != null || documentName != null) {
            final StringBuilder tmp = new StringBuilder();
            tmp.append((contentDisposition == null) ? "inline" : contentDisposition);
            if (documentName != null) {
                tmp.append("; filename=");
                tmp.append(documentName);
                tmp.append(".");
                tmp.append(format.toLowerCase());
            }
            response.setHeader("Content-disposition", tmp.toString());
        }
        // TODO: replace deprecated logic
        JRExporter exporter;
        switch(format) {
            case FORMAT_PDF:
                response.setContentType("application/pdf");
                exporter = new JRPdfExporter();
                break;
            case FORMAT_CSV:
                response.setContentType("text/csv");
                exporter = new JRCsvExporter();
                break;
            case FORMAT_HTML:
                response.setContentType("text/html");
                // IMAGES_MAPS seems to be only supported as "backward compatible" from JasperReports 1.1.0
                Map imagesMap = new HashMap();
                request.getSession(true).setAttribute("IMAGES_MAP", imagesMap);
                exporter = new HtmlExporter();
                exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap);
                exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + imageServletUrl);
                // Needed to support chart images:
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print", jasperPrint);
                break;
            case FORMAT_XLS:
                response.setContentType("application/vnd.ms-excel");
                exporter = new JRXlsExporter();
                break;
            case FORMAT_XML:
                response.setContentType("text/xml");
                exporter = new JRXmlExporter();
                break;
            case FORMAT_RTF:
                response.setContentType("application/rtf");
                exporter = new JRRtfExporter();
                break;
            default:
                throw new ServletException("Unknown report format: " + format);
        }
        evaluated = parsedExportParameters != null && !parsedExportParameters.equals(exportParameters);
        reevaluate = !evaluated || isAcceptableExpression(parsedExportParameters);
        Map exportParams = reevaluate ? (Map) stack.findValue(parsedExportParameters) : null;
        if (exportParams != null) {
            LOG.debug("Found export parameters; adding to exporter parameters...");
            exporter.getParameters().putAll(exportParams);
        }
        output = exportReportToBytes(jasperPrint, exporter);
    } catch (JRException e) {
        LOG.error("Error producing {} report for uri {}", format, systemId, e);
        throw new ServletException(e.getMessage(), e);
    } finally {
        try {
            if (conn != null) {
                // avoid NPE if connection was not used for the report
                conn.close();
            }
        } catch (Exception e) {
            LOG.warn("Could not close db connection properly", e);
        }
    }
    response.setContentLength(output.size());
    // Will throw ServletException on IOException.
    writeReport(response, output);
}
Also used : ValueStack(com.opensymphony.xwork2.util.ValueStack) JRException(net.sf.jasperreports.engine.JRException) HtmlExporter(net.sf.jasperreports.engine.export.HtmlExporter) HashMap(java.util.HashMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) JasperReport(net.sf.jasperreports.engine.JasperReport) JRPdfExporter(net.sf.jasperreports.engine.export.JRPdfExporter) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletContext(javax.servlet.ServletContext) JRRtfExporter(net.sf.jasperreports.engine.export.JRRtfExporter) JRXmlExporter(net.sf.jasperreports.engine.export.JRXmlExporter) JasperPrint(net.sf.jasperreports.engine.JasperPrint) JRCsvExporter(net.sf.jasperreports.engine.export.JRCsvExporter) Connection(java.sql.Connection) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletException(javax.servlet.ServletException) JRException(net.sf.jasperreports.engine.JRException) IOException(java.io.IOException) TimeZone(java.util.TimeZone) JRXlsExporter(net.sf.jasperreports.engine.export.JRXlsExporter) JRExporter(net.sf.jasperreports.engine.JRExporter) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

ValueStack (com.opensymphony.xwork2.util.ValueStack)3 Map (java.util.Map)3 ActionContext (com.opensymphony.xwork2.ActionContext)2 TextProvider (com.opensymphony.xwork2.TextProvider)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 BooleanAttribute (com.agiletec.aps.system.common.entity.model.attribute.BooleanAttribute)1 Content (com.agiletec.plugins.jacms.aps.system.services.content.model.Content)1 ActionInvocation (com.opensymphony.xwork2.ActionInvocation)1 ActionSupport (com.opensymphony.xwork2.ActionSupport)1 ModelDriven (com.opensymphony.xwork2.ModelDriven)1 ConfigurationException (com.opensymphony.xwork2.config.ConfigurationException)1 ActionConfig (com.opensymphony.xwork2.config.entities.ActionConfig)1 ContainerBuilder (com.opensymphony.xwork2.inject.ContainerBuilder)1 StubConfigurationProvider (com.opensymphony.xwork2.test.StubConfigurationProvider)1 ClearableValueStack (com.opensymphony.xwork2.util.ClearableValueStack)1 Evaluated (com.opensymphony.xwork2.util.Evaluated)1 LocatableProperties (com.opensymphony.xwork2.util.location.LocatableProperties)1 PropertyDescriptor (java.beans.PropertyDescriptor)1