Search in sources :

Example 1 with StrutsException

use of org.apache.struts2.StrutsException in project struts by apache.

the class ServletUrlRenderer method renderUrl.

/**
 * {@inheritDoc}
 */
@Override
public void renderUrl(Writer writer, UrlProvider urlComponent) {
    String scheme = urlComponent.getHttpServletRequest().getScheme();
    if (urlComponent.getScheme() != null) {
        ValueStack vs = ActionContext.getContext().getValueStack();
        scheme = vs.findString(urlComponent.getScheme());
        if (scheme == null) {
            scheme = urlComponent.getScheme();
        }
    }
    String result;
    ActionInvocation ai = ActionContext.getContext().getActionInvocation();
    if (urlComponent.getValue() == null && urlComponent.getAction() != null) {
        result = urlComponent.determineActionURL(urlComponent.getAction(), urlComponent.getNamespace(), urlComponent.getMethod(), urlComponent.getHttpServletRequest(), urlComponent.getHttpServletResponse(), urlComponent.getParameters(), scheme, urlComponent.isIncludeContext(), urlComponent.isEncode(), urlComponent.isForceAddSchemeHostAndPort(), urlComponent.isEscapeAmp());
    } else if (urlComponent.getValue() == null && urlComponent.getAction() == null && ai != null) {
        // both are null, we will default to the current action
        final String action = ai.getProxy().getActionName();
        final String namespace = ai.getProxy().getNamespace();
        final String method = urlComponent.getMethod() != null || !ai.getProxy().isMethodSpecified() ? urlComponent.getMethod() : ai.getProxy().getMethod();
        result = urlComponent.determineActionURL(action, namespace, method, urlComponent.getHttpServletRequest(), urlComponent.getHttpServletResponse(), urlComponent.getParameters(), scheme, urlComponent.isIncludeContext(), urlComponent.isEncode(), urlComponent.isForceAddSchemeHostAndPort(), urlComponent.isEscapeAmp());
    } else {
        String _value = urlComponent.getValue();
        // prioritised before this [in start(Writer) method]
        if (_value != null && _value.indexOf('?') > 0) {
            _value = _value.substring(0, _value.indexOf('?'));
        }
        result = urlHelper.buildUrl(_value, urlComponent.getHttpServletRequest(), urlComponent.getHttpServletResponse(), urlComponent.getParameters(), scheme, urlComponent.isIncludeContext(), urlComponent.isEncode(), urlComponent.isForceAddSchemeHostAndPort(), urlComponent.isEscapeAmp());
    }
    String anchor = urlComponent.getAnchor();
    if (StringUtils.isNotEmpty(anchor)) {
        result += '#' + urlComponent.findString(anchor);
    }
    if (urlComponent.isPutInContext()) {
        String var = urlComponent.getVar();
        if (StringUtils.isNotEmpty(var)) {
            urlComponent.putInContext(result);
            // Note: Old comments stated that var was placed in the page scope, but interactive checks with EL on JSPs prove otherwise.
            // Add the var attribute to the request scope as well.
            urlComponent.getHttpServletRequest().setAttribute(var, result);
        } else {
            try {
                writer.write(result);
            } catch (IOException e) {
                throw new StrutsException("IOError: " + e.getMessage(), e);
            }
        }
    } else {
        try {
            writer.write(result);
        } catch (IOException e) {
            throw new StrutsException("IOError: " + e.getMessage(), e);
        }
    }
}
Also used : StrutsException(org.apache.struts2.StrutsException) ValueStack(com.opensymphony.xwork2.util.ValueStack) ActionInvocation(com.opensymphony.xwork2.ActionInvocation) IOException(java.io.IOException)

Example 2 with StrutsException

use of org.apache.struts2.StrutsException in project struts by apache.

the class UIBean method end.

@Override
public boolean end(Writer writer, String body) {
    evaluateParams();
    try {
        super.end(writer, body, false);
        mergeTemplate(writer, buildTemplateName(template, getDefaultTemplate()));
    } catch (Exception e) {
        throw new StrutsException(e);
    } finally {
        popComponentStack();
    }
    return false;
}
Also used : StrutsException(org.apache.struts2.StrutsException) ConfigurationException(com.opensymphony.xwork2.config.ConfigurationException) StrutsException(org.apache.struts2.StrutsException)

Example 3 with StrutsException

use of org.apache.struts2.StrutsException in project struts by apache.

the class Jsr168Dispatcher method getActionMapping.

/**
 * Gets the namespace of the action from the request. The namespace is the
 * same as the portlet mode. E.g, view mode is mapped to namespace
 * <code>view</code>, and edit mode is mapped to the namespace
 * <code>edit</code>
 *
 * @param portletRequest the PortletRequest object.
 * @param servletRequest the ServletRequest to use
 * @return the namespace of the action.
 */
protected ActionMapping getActionMapping(final PortletRequest portletRequest, final HttpServletRequest servletRequest) {
    ActionMapping mapping;
    String actionPath = getDefaultActionPath(portletRequest);
    if (resetAction(portletRequest)) {
        mapping = actionMap.get(portletRequest.getPortletMode());
    } else {
        actionPath = servletRequest.getParameter(ACTION_PARAM);
        if (StringUtils.isEmpty(actionPath)) {
            mapping = actionMap.get(portletRequest.getPortletMode());
        } else {
            // Use the usual action mapper, but it is expecting an action extension
            // on the uri, so we add the default one, which should be ok as the
            // portlet is a portlet first, a servlet second
            mapping = actionMapper.getMapping(servletRequest, dispatcherUtils.getConfigurationManager());
        }
    }
    if (mapping == null) {
        throw new StrutsException("Unable to locate action mapping for request, probably due to an invalid action path: " + actionPath);
    }
    return mapping;
}
Also used : StrutsException(org.apache.struts2.StrutsException) ActionMapping(org.apache.struts2.dispatcher.mapper.ActionMapping)

Example 4 with StrutsException

use of org.apache.struts2.StrutsException in project struts by apache.

the class PortletUrlHelper method buildResourceUrl.

/**
 * Encode an url to a non Struts action resource, like stylesheet, image or
 * servlet.
 *
 * @param value base url
 * @param params url parameters
 * @return encoded url to non Struts action resources.
 */
public String buildResourceUrl(String value, Map params) {
    StringBuffer sb = new StringBuffer();
    // Relative URLs are not allowed in a portlet
    if (!value.startsWith("/")) {
        sb.append("/");
    }
    sb.append(value);
    if (params != null && params.size() > 0) {
        sb.append("?");
        Iterator it = params.keySet().iterator();
        try {
            while (it.hasNext()) {
                String key = (String) it.next();
                String val = (String) params.get(key);
                sb.append(URLEncoder.encode(key, ENCODING)).append("=");
                sb.append(URLEncoder.encode(val, ENCODING));
                if (it.hasNext()) {
                    sb.append("&");
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new StrutsException("Encoding " + ENCODING + " not found");
        }
    }
    PortletRequest req = PortletActionContext.getRequest();
    return encodeUrl(sb, req);
}
Also used : StrutsException(org.apache.struts2.StrutsException) PortletRequest(javax.portlet.PortletRequest) Iterator(java.util.Iterator) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 5 with StrutsException

use of org.apache.struts2.StrutsException in project struts by apache.

the class JSPLoader method compileJava.

/**
 * Compiles the given source code into java bytecode
 */
private void compileJava(String className, final String source, Set<String> extraClassPath) throws IOException {
    LOG.trace("Compiling [{}], source: [{}]", className, source);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    // the generated bytecode is fed to the class loader
    JavaFileManager jfm = new ForwardingJavaFileManager<StandardJavaFileManager>(compiler.getStandardFileManager(diagnostics, null, null)) {

        @Override
        public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
            MemoryJavaFileObject fileObject = new MemoryJavaFileObject(name, kind);
            classLoader.addMemoryJavaFileObject(name, fileObject);
            return fileObject;
        }
    };
    // read java source code from memory
    String fileName = className.replace('.', '/') + ".java";
    SimpleJavaFileObject sourceCodeObject = new SimpleJavaFileObject(toURI(fileName), JavaFileObject.Kind.SOURCE) {

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException, IllegalStateException, UnsupportedOperationException {
            return source;
        }
    };
    // build classpath
    // some entries will be added multiple times, hence the set
    List<String> optionList = new ArrayList<String>();
    Set<String> classPath = new HashSet<String>();
    // find available jars
    ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
    UrlSet urlSet = new UrlSet(classLoaderInterface);
    // find jars
    List<URL> urls = urlSet.getUrls();
    if (urls != null && urls.size() > 0) {
        final FileManagerFactory fileManagerFactoryGetInstance = ServletActionContext.getActionContext().getInstance(FileManagerFactory.class);
        final FileManagerFactory contextFileManagerFactory = (fileManagerFactoryGetInstance != null ? fileManagerFactoryGetInstance : (FileManagerFactory) ServletActionContext.getActionContext().get(StrutsConstants.STRUTS_FILE_MANAGER_FACTORY));
        final FileManagerFactory fileManagerFactory = (contextFileManagerFactory != null ? contextFileManagerFactory : new DefaultFileManagerFactory());
        final FileManager fileManagerGetInstance = fileManagerFactory.getFileManager();
        final FileManager contextFileManager = (fileManagerGetInstance != null ? fileManagerGetInstance : (FileManager) ServletActionContext.getActionContext().get(StrutsConstants.STRUTS_FILE_MANAGER));
        final FileManager fileManager = (contextFileManager != null ? contextFileManager : new DefaultFileManager());
        for (URL url : urls) {
            URL normalizedUrl = fileManager.normalizeToFileProtocol(url);
            File file = FileUtils.toFile(ObjectUtils.defaultIfNull(normalizedUrl, url));
            if (file.exists())
                classPath.add(file.getAbsolutePath());
        }
    }
    // these should be in the list already, but I am feeling paranoid
    // this jar
    classPath.add(getJarUrl(EmbeddedJSPResult.class));
    // servlet api
    classPath.add(getJarUrl(Servlet.class));
    // jsp api
    classPath.add(getJarUrl(JspPage.class));
    try {
        Class instanceManager = Class.forName("org.apache.tomcat.InstanceManager");
        classPath.add(getJarUrl(instanceManager));
    } catch (ClassNotFoundException e) {
    // ok ignore
    }
    // add extra classpath entries (jars where tlds were found will be here)
    for (Iterator<String> iterator = extraClassPath.iterator(); iterator.hasNext(); ) {
        String entry = iterator.next();
        classPath.add(entry);
    }
    String classPathString = StringUtils.join(classPath, File.pathSeparator);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Compiling [#0] with classpath [#1]", className, classPathString);
    }
    optionList.addAll(Arrays.asList("-classpath", classPathString));
    // compile
    JavaCompiler.CompilationTask task = compiler.getTask(null, jfm, diagnostics, optionList, null, Arrays.asList(sourceCodeObject));
    if (!task.call()) {
        throw new StrutsException("Compilation failed:" + diagnostics.getDiagnostics().get(0).toString());
    }
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) DefaultFileManagerFactory(com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory) ArrayList(java.util.ArrayList) JspPage(javax.servlet.jsp.JspPage) URL(java.net.URL) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) MemoryJavaFileObject(org.apache.struts2.compiler.MemoryJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) UrlSet(com.opensymphony.xwork2.util.finder.UrlSet) Servlet(javax.servlet.Servlet) DiagnosticCollector(javax.tools.DiagnosticCollector) FileObject(javax.tools.FileObject) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) MemoryJavaFileObject(org.apache.struts2.compiler.MemoryJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) MemoryJavaFileObject(org.apache.struts2.compiler.MemoryJavaFileObject) HashSet(java.util.HashSet) FileManagerFactory(com.opensymphony.xwork2.FileManagerFactory) DefaultFileManagerFactory(com.opensymphony.xwork2.util.fs.DefaultFileManagerFactory) JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager) ClassLoaderInterface(com.opensymphony.xwork2.util.finder.ClassLoaderInterface) JavaCompiler(javax.tools.JavaCompiler) DefaultFileManager(com.opensymphony.xwork2.util.fs.DefaultFileManager) JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) FileManager(com.opensymphony.xwork2.FileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) DefaultFileManager(com.opensymphony.xwork2.util.fs.DefaultFileManager) File(java.io.File)

Aggregations

StrutsException (org.apache.struts2.StrutsException)46 IOException (java.io.IOException)17 ConfigurationException (com.opensymphony.xwork2.config.ConfigurationException)9 ArrayList (java.util.ArrayList)7 InputStream (java.io.InputStream)6 URL (java.net.URL)6 ValueStack (com.opensymphony.xwork2.util.ValueStack)5 List (java.util.List)4 ServletContext (javax.servlet.ServletContext)4 ActionContext (com.opensymphony.xwork2.ActionContext)3 IntrospectionException (java.beans.IntrospectionException)3 ActionInvocation (com.opensymphony.xwork2.ActionInvocation)2 ActionConfig (com.opensymphony.xwork2.config.entities.ActionConfig)2 CompoundRoot (com.opensymphony.xwork2.util.CompoundRoot)2 File (java.io.File)2 Method (java.lang.reflect.Method)2 Iterator (java.util.Iterator)2 Map (java.util.Map)2 Properties (java.util.Properties)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2