Search in sources :

Example 11 with Location

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

the class DefaultValidatorFileParser method addValidatorConfigs.

private void addValidatorConfigs(ValidatorFactory factory, NodeList validatorNodes, Map<String, Object> extraParams, List<ValidatorConfig> validatorCfgs) {
    for (int j = 0; j < validatorNodes.getLength(); j++) {
        Element validatorElement = (Element) validatorNodes.item(j);
        String validatorType = validatorElement.getAttribute("type");
        Map<String, Object> params = new HashMap<String, Object>(extraParams);
        params.putAll(XmlHelper.getParams(validatorElement));
        // ensure that the type is valid...
        try {
            factory.lookupRegisteredValidatorType(validatorType);
        } catch (IllegalArgumentException ex) {
            throw new ConfigurationException("Invalid validation type: " + validatorType, validatorElement);
        }
        ValidatorConfig.Builder vCfg = new ValidatorConfig.Builder(validatorType).addParams(params).location(DomHelper.getLocationObject(validatorElement)).shortCircuit(Boolean.valueOf(validatorElement.getAttribute("short-circuit")));
        NodeList messageNodes = validatorElement.getElementsByTagName("message");
        Element messageElement = (Element) messageNodes.item(0);
        final Node defaultMessageNode = messageElement.getFirstChild();
        String defaultMessage = (defaultMessageNode == null) ? "" : defaultMessageNode.getNodeValue();
        vCfg.defaultMessage(defaultMessage);
        Map<String, String> messageParams = XmlHelper.getParams(messageElement);
        String key = messageElement.getAttribute("key");
        if ((key != null) && (key.trim().length() > 0)) {
            vCfg.messageKey(key);
            if (messageParams.containsKey("defaultMessage")) {
                vCfg.defaultMessage(messageParams.get("defaultMessage"));
            }
            // Sort the message param. those with keys as '1', '2', '3' etc. (numeric values)
            // are i18n message parameter, others are excluded.
            TreeMap<Integer, String> sortedMessageParameters = new TreeMap<Integer, String>();
            for (Map.Entry<String, String> messageParamEntry : messageParams.entrySet()) {
                try {
                    int _order = Integer.parseInt(messageParamEntry.getKey());
                    sortedMessageParameters.put(_order, messageParamEntry.getValue());
                } catch (NumberFormatException e) {
                // ignore if its not numeric.
                }
            }
            vCfg.messageParams(sortedMessageParameters.values().toArray(new String[sortedMessageParameters.values().size()]));
        } else {
            if (messageParams != null && (messageParams.size() > 0)) {
                // let's warn the user.
                if (LOG.isWarnEnabled()) {
                    LOG.warn("validator of type [" + validatorType + "] have i18n message parameters defined but no i18n message key, it's parameters will be ignored");
                }
            }
        }
        validatorCfgs.add(vCfg.build());
    }
}
Also used : ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException)

Example 12 with Location

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

the class DomHelperTest method testGetLocationObject.

public void testGetLocationObject() throws Exception {
    InputSource in = new InputSource(new StringReader(xml));
    in.setSystemId("foo://bar");
    Document doc = DomHelper.parse(in);
    NodeList nl = doc.getElementsByTagName("bar");
    Location loc = DomHelper.getLocationObject((Element) nl.item(0));
    assertNotNull(loc);
    assertTrue("Should be line 6, was " + loc.getLineNumber(), 6 == loc.getLineNumber());
}
Also used : InputSource(org.xml.sax.InputSource) NodeList(org.w3c.dom.NodeList) StringReader(java.io.StringReader) Document(org.w3c.dom.Document) Location(com.opensymphony.xwork2.util.location.Location)

Example 13 with Location

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

the class TestConfigurationProvider method loadPackages.

/**
 * Initializes the configuration object.
 */
public void loadPackages() {
    Map<String, String> successParams = new HashMap<>();
    successParams.put("propertyName", "executionCount");
    successParams.put("expectedValue", "1");
    ActionConfig executionCountActionConfig = new ActionConfig.Builder("", "", ExecutionCountTestAction.class.getName()).addResultConfig(new ResultConfig.Builder(Action.SUCCESS, TestResult.class.getName()).addParams(successParams).build()).build();
    ValidationInterceptor validationInterceptor = new ValidationInterceptor();
    validationInterceptor.setIncludeMethods("*");
    ActionConfig doubleValidationActionConfig = new ActionConfig.Builder("", "doubleValidationAction", DoubleValidationAction.class.getName()).addResultConfig(new ResultConfig.Builder(Action.SUCCESS, ServletDispatcherResult.class.getName()).addParam("location", "success.jsp").build()).addInterceptor(new InterceptorMapping("validation", validationInterceptor)).build();
    ActionConfig testActionConfig = new ActionConfig.Builder("", "", TestAction.class.getName()).addResultConfig(new ResultConfig.Builder(Action.SUCCESS, ServletDispatcherResult.class.getName()).addParam("location", "success.jsp").build()).addInterceptor(new InterceptorMapping("params", new ParametersInterceptor())).build();
    ActionConfig tokenActionConfig = new ActionConfig.Builder("", "", TestAction.class.getName()).addInterceptor(new InterceptorMapping("token", new TokenInterceptor())).addResultConfig(new ResultConfig.Builder("invalid.token", MockResult.class.getName()).build()).addResultConfig(new ResultConfig.Builder("success", MockResult.class.getName()).build()).build();
    // empty results for token session unit test
    ActionConfig tokenSessionActionConfig = new ActionConfig.Builder("", "", TestAction.class.getName()).addResultConfig(new ResultConfig.Builder("invalid.token", MockResult.class.getName()).build()).addResultConfig(new ResultConfig.Builder("success", MockResult.class.getName()).build()).addInterceptor(new InterceptorMapping("tokenSession", new TokenSessionStoreInterceptor())).build();
    PackageConfig defaultPackageConfig = new PackageConfig.Builder("").addActionConfig(EXECUTION_COUNT_ACTION_NAME, executionCountActionConfig).addActionConfig(TEST_ACTION_NAME, testActionConfig).addActionConfig("doubleValidationAction", doubleValidationActionConfig).addActionConfig(TOKEN_ACTION_NAME, tokenActionConfig).addActionConfig(TOKEN_SESSION_ACTION_NAME, tokenSessionActionConfig).addActionConfig("testActionTagAction", new ActionConfig.Builder("", "", TestAction.class.getName()).addResultConfig(new ResultConfig.Builder(Action.SUCCESS, TestActionTagResult.class.getName()).build()).addResultConfig(new ResultConfig.Builder(Action.INPUT, TestActionTagResult.class.getName()).build()).addAllowedMethod("input").build()).build();
    configuration.addPackageConfig("", defaultPackageConfig);
    PackageConfig namespacePackageConfig = new PackageConfig.Builder("namespacePackage").namespace(TEST_NAMESPACE).addParent(defaultPackageConfig).addActionConfig(TEST_NAMESPACE_ACTION, new ActionConfig.Builder("", "", TestAction.class.getName()).build()).build();
    configuration.addPackageConfig("namespacePackage", namespacePackageConfig);
    PackageConfig testActionWithNamespacePackageConfig = new PackageConfig.Builder("testActionNamespacePackages").namespace(TEST_NAMESPACE).addParent(defaultPackageConfig).addActionConfig(TEST_ACTION_NAME, new ActionConfig.Builder("", "", TestAction.class.getName()).build()).build();
    configuration.addPackageConfig("testActionNamespacePackages", testActionWithNamespacePackageConfig);
}
Also used : ValidationInterceptor(com.opensymphony.xwork2.validator.ValidationInterceptor) ActionConfig(com.opensymphony.xwork2.config.entities.ActionConfig) ResultConfig(com.opensymphony.xwork2.config.entities.ResultConfig) MockResult(com.opensymphony.xwork2.mock.MockResult) HashMap(java.util.HashMap) ContainerBuilder(com.opensymphony.xwork2.inject.ContainerBuilder) ParametersInterceptor(com.opensymphony.xwork2.interceptor.ParametersInterceptor) PackageConfig(com.opensymphony.xwork2.config.entities.PackageConfig) TokenSessionStoreInterceptor(org.apache.struts2.interceptor.TokenSessionStoreInterceptor) InterceptorMapping(com.opensymphony.xwork2.config.entities.InterceptorMapping) TokenInterceptor(org.apache.struts2.interceptor.TokenInterceptor)

Example 14 with Location

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

the class FelixOsgiHost method startFelix.

protected void startFelix() {
    // Retrieve Felix properties path from ServletContext (default to "default.properties" if not present).
    String felixPropertiesPath = getServletContextParam("struts.osgi.felixPropertiesPath", "default.properties");
    felixPropertiesPath = felixPropertiesPath.trim();
    if (felixPropertiesPath.startsWith("/")) {
        // Must strip leading "/" if present.
        felixPropertiesPath = felixPropertiesPath.substring(1);
    }
    // Load properties from felix embedded file or value specified in servlet init parameter "struts.osgi.felixPropertiesPath".
    final Properties configProps = getProperties(felixPropertiesPath);
    // Copy framework properties from the system properties.
    Main.copySystemProperties(configProps);
    replaceSystemPackages(configProps);
    LOG.debug("Felix framework system capabilities: [{}]", configProps.getProperty(Constants.FRAMEWORK_SYSTEMCAPABILITIES));
    LOG.debug("Felix framework execution environment: [{}]", configProps.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT));
    LOG.debug("Felix service caps: [{}]", configProps.getProperty(FELIX_SERVICE_CAPS_KEY));
    replaceFelixSystemPackages(configProps);
    replaceFelixFrameworkSystemCapabilities(configProps);
    replaceFelixExecutionEnvironment(configProps);
    // Retrieve Struts OSGi properties path from ServletContext (default to "struts-osgi.properties" if not present).
    String strutsOSGiPropertiesPath = getServletContextParam("struts.osgi.strutsOSGiPropertiesPath", "struts-osgi.properties");
    strutsOSGiPropertiesPath = strutsOSGiPropertiesPath.trim();
    if (strutsOSGiPropertiesPath.startsWith("/")) {
        // Must strip leading "/" if present.
        strutsOSGiPropertiesPath = strutsOSGiPropertiesPath.substring(1);
    }
    LOG.trace("FelixOSGiHost: Before addExportedPackages");
    // struts, xwork and felix exported packages
    final Properties strutsConfigProps = getProperties(strutsOSGiPropertiesPath);
    try {
        addExportedPackages(strutsConfigProps, configProps);
    } catch (Throwable t) {
        throw new ConfigurationException("FelixOSGiHost couldn't start Apache Felix", t);
    }
    LOG.trace("FelixOSGiHost: After addExportedPackages, before addAutoStartBundles");
    // find bundles and adde em to autostart property
    try {
        addAutoStartBundles(configProps);
    } catch (Throwable t) {
        throw new ConfigurationException("FelixOSGiHost couldn't start Apache Felix", t);
    }
    LOG.trace("FelixOSGiHost: After addAutoStartBundles. before bundle cache processing");
    // Bundle cache
    String storageDir = configProps.getProperty(Constants.FRAMEWORK_STORAGE);
    if (storageDir == null || storageDir.isEmpty()) {
        String javaTmpDir = System.getProperty("java.io.tmpdir");
        if (javaTmpDir == null || javaTmpDir.isEmpty()) {
            LOG.warn("Felix environment 'java.io.tmpdir': [{}], and 'org.osgi.framework.storage': [{}].  Felix bundle cache will be created at the root directory (probable failure)", javaTmpDir, storageDir);
            javaTmpDir = File.separator;
        }
        if (javaTmpDir.endsWith(File.separator)) {
            storageDir = javaTmpDir + ".felix-cache";
        } else {
            storageDir = javaTmpDir + File.separator + ".felix-cache";
        }
        configProps.setProperty(Constants.FRAMEWORK_STORAGE, storageDir);
    }
    LOG.debug("Storing bundles at [{}]", storageDir);
    String cleanBundleCache = getServletContextParam("struts.osgi.clearBundleCache", "true");
    if ("true".equalsIgnoreCase(cleanBundleCache)) {
        LOG.debug("Clearing bundle cache");
        configProps.put(FelixConstants.FRAMEWORK_STORAGE_CLEAN, FelixConstants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    }
    String cacheLocking = getServletContextParam("struts.osgi.felixCacheLocking", "true");
    configProps.put("felix.cache.locking", cacheLocking);
    LOG.debug("Felix bundle cache locking: [{}]", cacheLocking);
    LOG.trace("FelixOSGiHost: After bundle cache processing, before configProps and init");
    // other properties
    configProps.put(FelixConstants.SERVICE_URLHANDLERS_PROP, "false");
    configProps.put(FelixConstants.LOG_LEVEL_PROP, getServletContextParam("struts.osgi.logLevel", "1"));
    configProps.put(FelixConstants.BUNDLE_CLASSPATH, ".");
    configProps.put(FelixConstants.FRAMEWORK_BEGINNING_STARTLEVEL, getServletContextParam("struts.osgi.runLevel", "3"));
    try {
        felix = new Felix(configProps);
        LOG.trace("FelixOSGiHost: After Felix construct. before init");
        felix.init();
        LOG.trace("FelixOSGiHost: After Felix init. before AutoProcessor process");
        AutoProcessor.process(configProps, felix.getBundleContext());
        LOG.trace("FelixOSGiHost: After Felix AutoProcessor process, before start");
        felix.start();
        LOG.trace("FelixOSGiHost: After Felix start");
        // Start detailed service/bundle state for debugging.
        if (LOG.isDebugEnabled()) {
            ServiceReference[] serviceReferences = felix.getRegisteredServices();
            LOG.debug("Felix registered service references: [{}]", Arrays.toString(serviceReferences));
            serviceReferences = felix.getServicesInUse();
            LOG.debug("Felix in-use service references: [{}]", Arrays.toString(serviceReferences));
            Map<String, Bundle> bundleMap = this.getBundles();
            LOG.debug("Felix bundle map has size: [{}]", bundleMap.size());
            Set<String> bundleKeys = bundleMap.keySet();
            Iterator<String> keyIterator = bundleKeys.iterator();
            while (keyIterator.hasNext()) {
                String currentKey = keyIterator.next();
                Bundle currentBundle = bundleMap.get(currentKey);
                if (currentBundle != null) {
                    ServiceReference[] bundleRegisteredServices = currentBundle.getRegisteredServices();
                    ServiceReference[] bundleServicesInUse = currentBundle.getServicesInUse();
                    LOG.debug("    Key: [{}], SymbolicName: [{}], Location: [{}], BundleID: [{}], State: [{}]", currentKey, currentBundle.getSymbolicName(), currentBundle.getLocation(), currentBundle.getBundleId(), currentBundle.getState());
                    LOG.debug("        Bundle Registered Services: [{}]", Arrays.toString(bundleRegisteredServices));
                    LOG.debug("        Bundle Services In Use: [{}]", Arrays.toString(bundleServicesInUse));
                } else {
                    LOG.debug("    Key: [{}] returned a null bundle", currentKey);
                }
            }
            Bundle[] bundles = this.getBundleContext().getBundles();
            if (bundles != null) {
                LOG.debug("BundleContext bundle array has size: [{}]", bundles.length);
                for (int index = 0; index < bundles.length; index++) {
                    Bundle currentBundle = bundles[index];
                    if (currentBundle != null) {
                        LOG.debug("    Bundle [{}], SymbolicName: [{}], Location: [{}], BundleID: [{}], State: [{}]", index, currentBundle.getSymbolicName(), currentBundle.getLocation(), currentBundle.getBundleId(), currentBundle.getState());
                    } else {
                        LOG.debug("    Bundle [{}] is null", index);
                    }
                }
            } else {
                LOG.debug("Default Bundle Context bundle array is null");
            }
        }
        // End detailed service/bundle state for debugging.
        LOG.trace("Apache Felix is running");
    } catch (Throwable t) {
        throw new ConfigurationException("FelixOSGiHost couldn't start Apache Felix", t);
    }
    addSpringOSGiSupport();
    // add the bundle context to the ServletContext
    servletContext.setAttribute(OSGI_BUNDLE_CONTEXT, felix.getBundleContext());
}
Also used : Bundle(org.osgi.framework.Bundle) Properties(java.util.Properties) ServiceReference(org.osgi.framework.ServiceReference) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) Felix(org.apache.felix.framework.Felix)

Example 15 with Location

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

the class FreemarkerResult method doExecute.

/**
 * Execute this result, using the specified template locationArg.
 * <p>
 * The template locationArg has already been interpolated for any variable substitutions
 * </p>
 * <p>
 * this method obtains the freemarker configuration and the object wrapper from the provided hooks.
 * It them implements the template processing workflow by calling the hooks for
 * preTemplateProcess and postTemplateProcess
 * </p>
 *
 * @param locationArg location argument
 * @param invocation  the action invocation
 * @throws IOException       in case of IO errors
 * @throws TemplateException in case of freemarker template errors
 */
public void doExecute(String locationArg, ActionInvocation invocation) throws IOException, TemplateException {
    this.location = locationArg;
    this.invocation = invocation;
    this.configuration = getConfiguration();
    this.wrapper = getObjectWrapper();
    ActionContext ctx = invocation.getInvocationContext();
    HttpServletRequest req = ctx.getServletRequest();
    String absoluteLocation;
    if (location.startsWith("/")) {
        absoluteLocation = location;
    } else {
        String namespace = invocation.getProxy().getNamespace();
        if (namespace == null || namespace.length() == 0 || namespace.equals("/")) {
            absoluteLocation = "/" + location;
        } else if (namespace.startsWith("/")) {
            absoluteLocation = namespace + "/" + location;
        } else {
            absoluteLocation = "/" + namespace + "/" + location;
        }
    }
    Template template = configuration.getTemplate(absoluteLocation, deduceLocale());
    TemplateModel model = createModel();
    // Give subclasses a chance to hook into preprocessing
    if (preTemplateProcess(template, model)) {
        try {
            final boolean willWriteIfCompleted;
            if (writeIfCompleted != null) {
                willWriteIfCompleted = isWriteIfCompleted();
            } else {
                willWriteIfCompleted = template.getTemplateExceptionHandler() == TemplateExceptionHandler.RETHROW_HANDLER;
            }
            // Process the template
            Writer writer = getWriter();
            if (willWriteIfCompleted) {
                CharArrayWriter parentCharArrayWriter = (CharArrayWriter) req.getAttribute(PARENT_TEMPLATE_WRITER);
                boolean isTopTemplate;
                if (isTopTemplate = (parentCharArrayWriter == null)) {
                    // this is the top template
                    parentCharArrayWriter = new CharArrayWriter();
                    // set it in the request because when the "action" tag is used a new VS and ActionContext is created
                    req.setAttribute(PARENT_TEMPLATE_WRITER, parentCharArrayWriter);
                }
                try {
                    template.process(model, parentCharArrayWriter);
                    if (isTopTemplate) {
                        parentCharArrayWriter.flush();
                        parentCharArrayWriter.writeTo(writer);
                    }
                } catch (TemplateException | IOException e) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Error processing Freemarker result!", e);
                    }
                    throw e;
                } finally {
                    if (isTopTemplate) {
                        req.removeAttribute(PARENT_TEMPLATE_WRITER);
                        parentCharArrayWriter.close();
                    }
                }
            } else {
                template.process(model, writer);
            }
        } finally {
            // Give subclasses a chance to hook into postprocessing
            postTemplateProcess(template, model);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) TemplateException(freemarker.template.TemplateException) TemplateModel(freemarker.template.TemplateModel) IOException(java.io.IOException) ActionContext(com.opensymphony.xwork2.ActionContext) ServletActionContext(org.apache.struts2.ServletActionContext) CharArrayWriter(java.io.CharArrayWriter) Writer(java.io.Writer) CharArrayWriter(java.io.CharArrayWriter) Template(freemarker.template.Template)

Aggregations

ResultConfig (com.opensymphony.xwork2.config.entities.ResultConfig)32 ServletContext (javax.servlet.ServletContext)22 PackageConfig (com.opensymphony.xwork2.config.entities.PackageConfig)21 HashSet (java.util.HashSet)15 ConfigurationException (com.opensymphony.xwork2.config.ConfigurationException)11 ActionContext (com.opensymphony.xwork2.ActionContext)10 ValueStack (com.opensymphony.xwork2.util.ValueStack)10 HashMap (java.util.HashMap)9 ActionInvocation (com.opensymphony.xwork2.ActionInvocation)8 ActionConfig (com.opensymphony.xwork2.config.entities.ActionConfig)8 ServletActionContext (org.apache.struts2.ServletActionContext)8 ResultTypeConfig (com.opensymphony.xwork2.config.entities.ResultTypeConfig)7 Location (com.opensymphony.xwork2.util.location.Location)7 ArrayList (java.util.ArrayList)7 NoAnnotationAction (org.apache.struts2.convention.actions.NoAnnotationAction)7 ClassLevelResultPathAction (org.apache.struts2.convention.actions.resultpath.ClassLevelResultPathAction)6 Action (org.apache.struts2.convention.annotation.Action)6 NodeList (org.w3c.dom.NodeList)6 ActionProxy (com.opensymphony.xwork2.ActionProxy)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5