Search in sources :

Example 66 with IPentahoSession

use of org.pentaho.platform.api.engine.IPentahoSession in project pentaho-platform by pentaho.

the class HttpSessionPentahoSessionIntegrationFilter method doFilter.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    // Do we really need the checks on the types in practice ?
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("Can only process HttpServletRequest");
    }
    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("Can only process HttpServletResponse");
    }
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    if (httpRequest.getAttribute(FILTER_APPLIED) != null) {
        // ensure that filter is only applied once per request
        chain.doFilter(httpRequest, httpResponse);
        return;
    }
    HttpSession httpSession = safeGetSession(httpRequest, forceEagerSessionCreation);
    boolean httpSessionExistedAtStartOfRequest = httpSession != null;
    IPentahoSession pentahoSessionBeforeChainExecution = readPentahoSessionFromHttpSession(httpSession);
    if (httpSessionExistedAtStartOfRequest) {
        setSessionExpirationCookies(httpSession, pentahoSessionBeforeChainExecution, httpResponse);
    }
    // Make the HttpSession null, as we don't want to keep a reference to it lying
    // around in case chain.doFilter() invalidates it.
    httpSession = null;
    localeLeftovers(httpRequest);
    if (pentahoSessionBeforeChainExecution == null) {
        pentahoSessionBeforeChainExecution = generatePentahoSession(httpRequest);
        if (logger.isDebugEnabled()) {
            logger.debug("Found no IPentahoSession in HTTP session; created new IPentahoSession");
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Obtained a valid IPentahoSession from HTTP session to " + "associate with PentahoSessionHolder: '" + pentahoSessionBeforeChainExecution + "'");
        }
    }
    httpRequest.setAttribute(FILTER_APPLIED, Boolean.TRUE);
    // Create a wrapper that will eagerly update the session with the Hitachi Vantara session
    // if anything in the chain does a sendError() or sendRedirect().
    OnRedirectUpdateSessionResponseWrapper responseWrapper = new OnRedirectUpdateSessionResponseWrapper(httpResponse, httpRequest, httpSessionExistedAtStartOfRequest);
    try {
        // This is the only place in this class where PentahoSessionHolder.setSession() is called
        PentahoSessionHolder.setSession(pentahoSessionBeforeChainExecution);
        chain.doFilter(httpRequest, responseWrapper);
    } finally {
        // This is the only place in this class where PentahoSessionHolder.getSession() is called
        IPentahoSession pentahoSessionAfterChainExecution = PentahoSessionHolder.getSession();
        // Crucial removal of PentahoSessionHolder contents - do this before anything else.
        PentahoSessionHolder.removeSession();
        httpRequest.removeAttribute(FILTER_APPLIED);
        // once per request.
        if (!responseWrapper.isSessionUpdateDone()) {
            storePentahoSessionInHttpSession(pentahoSessionAfterChainExecution, httpRequest, httpSessionExistedAtStartOfRequest);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("PentahoSessionHolder now cleared, as request processing completed");
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpSession(javax.servlet.http.HttpSession) PentahoHttpSession(org.pentaho.platform.web.http.session.PentahoHttpSession) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 67 with IPentahoSession

use of org.pentaho.platform.api.engine.IPentahoSession in project pentaho-platform by pentaho.

the class PentahoWebContextFilter method getActiveThemeVar.

// region get Environment Variables
private String getActiveThemeVar(HttpServletRequest request) {
    IPentahoSession session = getSession();
    String activeTheme = (String) session.getAttribute("pentaho-user-theme");
    String ua = request.getHeader("User-Agent");
    // check if we're coming from a mobile device, if so, lock to system default (ruby)
    if (StringUtils.isNotEmpty(ua) && ua.matches(".*(?i)(iPad|iPod|iPhone|Android).*")) {
        activeTheme = PentahoSystem.getSystemSetting("default-theme", "ruby");
    }
    if (activeTheme == null) {
        IUserSettingService settingsService = getUserSettingsService();
        try {
            activeTheme = settingsService.getUserSetting("pentaho-user-theme", null).getSettingValue();
        } catch (Exception ignored) {
        // the user settings service is not valid in the agile-bi deployment of the server
        }
        if (activeTheme == null) {
            activeTheme = PentahoSystem.getSystemSetting("default-theme", "ruby");
        }
    }
    return activeTheme;
}
Also used : IUserSettingService(org.pentaho.platform.api.usersettings.IUserSettingService) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) ServletException(javax.servlet.ServletException) ConcurrentException(org.apache.commons.lang3.concurrent.ConcurrentException) IOException(java.io.IOException)

Example 68 with IPentahoSession

use of org.pentaho.platform.api.engine.IPentahoSession in project pentaho-platform by pentaho.

the class PentahoSessionFactory method getSession.

public static IPentahoSession getSession(final String userName, final HttpSession session, final HttpServletRequest request) {
    IPentahoSession userSession = (IPentahoSession) session.getAttribute(PentahoSystem.PENTAHO_SESSION_KEY);
    if (userSession != null) {
        return userSession;
    }
    userSession = new PentahoHttpSession(userName, session, request.getLocale(), userSession);
    ITempFileDeleter deleter = PentahoSystem.get(ITempFileDeleter.class, userSession);
    if (deleter != null) {
        userSession.setAttribute(ITempFileDeleter.DELETER_SESSION_VARIABLE, deleter);
    }
    return userSession;
}
Also used : ITempFileDeleter(org.pentaho.platform.api.util.ITempFileDeleter) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession)

Example 69 with IPentahoSession

use of org.pentaho.platform.api.engine.IPentahoSession in project pentaho-platform by pentaho.

the class GenericServlet method doGet.

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    if (showDeprecationMessage) {
        String deprecationMessage = "GenericServlet is deprecated and should no longer be handling requests. More detail below..." + "\n | You have issued a {0} request to {1} from referer {2} " + "\n | Please consider using one of the following REST services instead:" + "\n | * GET /api/repos/<pluginId>/<path> to read files from a plugin public dir" + "\n | * POST|GET /api/repos/<pathId>/generatedContent to create content resulting from execution of a " + "repo file" + "\n | * POST|GET /api/repos/<pluginId>/<contentGeneratorId> to execute a content generator by name (RPC " + "compatibility service)" + "\n \\ To turn this message off, set init-param 'showDeprecationMessage' to false in the GenericServlet " + "declaration" + "";
        String referer = StringUtils.defaultString(request.getHeader("Referer"), "");
        logger.warn(MessageFormat.format(deprecationMessage, request.getMethod(), request.getRequestURL(), referer));
    }
    PentahoSystem.systemEntryPoint();
    IOutputHandler outputHandler = null;
    // BISERVER-2767 - grabbing the current class loader so we can replace it at the end
    ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader();
    try {
        String servletPath = request.getServletPath();
        String pathInfo = request.getPathInfo();
        // $NON-NLS-1$
        String contentGeneratorId = "";
        // $NON-NLS-1$
        String urlPath = "";
        SimpleParameterProvider pathParams = new SimpleParameterProvider();
        if (StringUtils.isEmpty(pathInfo)) {
            logger.error(// $NON-NLS-1$
            Messages.getInstance().getErrorString("GenericServlet.ERROR_0005_NO_RESOURCE_SPECIFIED"));
            response.sendError(403);
            return;
        }
        String path = pathInfo.substring(1);
        int slashPos = path.indexOf('/');
        if (slashPos != -1) {
            // $NON-NLS-1$
            pathParams.setParameter("path", pathInfo.substring(slashPos + 1));
            contentGeneratorId = path.substring(0, slashPos);
        } else {
            contentGeneratorId = path;
        }
        // $NON-NLS-1$
        urlPath = "content/" + contentGeneratorId;
        IParameterProvider requestParameters = new HttpRequestParameterProvider(request);
        // $NON-NLS-1$
        pathParams.setParameter("query", request.getQueryString());
        // $NON-NLS-1$
        pathParams.setParameter("contentType", request.getContentType());
        InputStream in = request.getInputStream();
        // $NON-NLS-1$
        pathParams.setParameter("inputstream", in);
        // $NON-NLS-1$
        pathParams.setParameter("httpresponse", response);
        // $NON-NLS-1$
        pathParams.setParameter("httprequest", request);
        // $NON-NLS-1$
        pathParams.setParameter("remoteaddr", request.getRemoteAddr());
        if (PentahoSystem.debug) {
            // $NON-NLS-1$
            debug("GenericServlet contentGeneratorId=" + contentGeneratorId);
            // $NON-NLS-1$
            debug("GenericServlet urlPath=" + urlPath);
        }
        IPentahoSession session = getPentahoSession(request);
        IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, session);
        if (pluginManager == null) {
            OutputStream out = response.getOutputStream();
            String message = Messages.getInstance().getErrorString("GenericServlet.ERROR_0001_BAD_OBJECT", // $NON-NLS-1$
            IPluginManager.class.getSimpleName());
            error(message);
            out.write(message.getBytes());
            return;
        }
        // TODO make doing the HTTP headers configurable per content generator
        SimpleParameterProvider headerParams = new SimpleParameterProvider();
        Enumeration names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = request.getHeader(name);
            headerParams.setParameter(name, value);
        }
        String pluginId = pluginManager.getServicePlugin(pathInfo);
        if (pluginId != null && pluginManager.isStaticResource(pathInfo)) {
            boolean cacheOn = "true".equals(pluginManager.getPluginSetting(pluginId, "settings/cache", // $NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
            "false"));
            // $NON-NLS-1$
            String maxAge = (String) pluginManager.getPluginSetting(pluginId, "settings/max-age", null);
            allowBrowserCache(maxAge, pathParams);
            String mimeType = MimeHelper.getMimeTypeFromFileName(pathInfo);
            if (mimeType != null) {
                response.setContentType(mimeType);
            }
            OutputStream out = response.getOutputStream();
            // do we have this resource cached?
            ByteArrayOutputStream byteStream = null;
            if (cacheOn) {
                byteStream = (ByteArrayOutputStream) cache.getFromRegionCache(CACHE_FILE, pathInfo);
            }
            if (byteStream != null) {
                IOUtils.write(byteStream.toByteArray(), out);
                return;
            }
            InputStream resourceStream = pluginManager.getStaticResource(pathInfo);
            if (resourceStream != null) {
                try {
                    byteStream = new ByteArrayOutputStream();
                    IOUtils.copy(resourceStream, byteStream);
                    // if cache is enabled, drop file in cache
                    if (cacheOn) {
                        cache.putInRegionCache(CACHE_FILE, pathInfo, byteStream);
                    }
                    // write it out
                    IOUtils.write(byteStream.toByteArray(), out);
                    return;
                } finally {
                    IOUtils.closeQuietly(resourceStream);
                }
            }
            logger.error(Messages.getInstance().getErrorString("GenericServlet.ERROR_0004_RESOURCE_NOT_FOUND", pluginId, // $NON-NLS-1$
            pathInfo));
            response.sendError(404);
            return;
        }
        // content generators defined in plugin.xml are registered with 2 aliases, one is the id, the other is type
        // so, we can still retrieve a content generator by id, even though this is not the correct way to find
        // it. the correct way is to look up a content generator by pluginManager.getContentGenerator(type,
        // perspectiveName)
        IContentGenerator contentGenerator = (IContentGenerator) pluginManager.getBean(contentGeneratorId);
        if (contentGenerator == null) {
            OutputStream out = response.getOutputStream();
            String message = Messages.getInstance().getErrorString("GenericServlet.ERROR_0002_BAD_GENERATOR", // $NON-NLS-1$
            Encode.forHtml(contentGeneratorId));
            error(message);
            out.write(message.getBytes());
            return;
        }
        // set the classloader of the current thread to the class loader of
        // the plugin so that it can load its libraries
        // Note: we cannot ask the contentGenerator class for it's classloader, since the cg may
        // actually be a proxy object loaded by main the WebAppClassloader
        Thread.currentThread().setContextClassLoader(pluginManager.getClassLoader(pluginId));
        // String proxyClass = PentahoSystem.getSystemSetting( module+"/plugin.xml" ,
        // "plugin/content-generators/"+contentGeneratorId,
        // "content generator not found");
        // see if this is an upload
        // File uploading is a service provided by UploadFileServlet where appropriate protections
        // are in place to prevent uploads that are too large.
        // boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        // if (isMultipart) {
        // requestParameters = new SimpleParameterProvider();
        // // Create a factory for disk-based file items
        // FileItemFactory factory = new DiskFileItemFactory();
        // 
        // // Create a new file upload handler
        // ServletFileUpload upload = new ServletFileUpload(factory);
        // 
        // // Parse the request
        // List<?> /* FileItem */items = upload.parseRequest(request);
        // Iterator<?> iter = items.iterator();
        // while (iter.hasNext()) {
        // FileItem item = (FileItem) iter.next();
        // 
        // if (item.isFormField()) {
        // ((SimpleParameterProvider) requestParameters).setParameter(item.getFieldName(), item.getString());
        // } else {
        // String name = item.getName();
        // ((SimpleParameterProvider) requestParameters).setParameter(name, item.getInputStream());
        // }
        // }
        // }
        response.setCharacterEncoding(LocaleHelper.getSystemEncoding());
        IMimeTypeListener listener = new HttpMimeTypeListener(request, response);
        outputHandler = getOutputHandler(response, true);
        outputHandler.setMimeTypeListener(listener);
        IParameterProvider sessionParameters = new HttpSessionParameterProvider(session);
        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
        Map<String, IParameterProvider> parameterProviders = new HashMap<String, IParameterProvider>();
        parameterProviders.put(IParameterProvider.SCOPE_REQUEST, requestParameters);
        parameterProviders.put(IParameterProvider.SCOPE_SESSION, sessionParameters);
        // $NON-NLS-1$
        parameterProviders.put("headers", headerParams);
        // $NON-NLS-1$
        parameterProviders.put("path", pathParams);
        SimpleUrlFactory urlFactory = // $NON-NLS-1$ //$NON-NLS-2$
        new SimpleUrlFactory(requestContext.getContextPath() + urlPath + "?");
        List<String> messages = new ArrayList<String>();
        contentGenerator.setOutputHandler(outputHandler);
        contentGenerator.setMessagesList(messages);
        contentGenerator.setParameterProviders(parameterProviders);
        contentGenerator.setSession(session);
        contentGenerator.setUrlFactory(urlFactory);
        // String contentType = request.getContentType();
        // contentGenerator.setInput(input);
        contentGenerator.createContent();
        if (PentahoSystem.debug) {
            // $NON-NLS-1$
            debug("Generic Servlet content generate successfully");
        }
    } catch (Exception e) {
        StringBuffer buffer = new StringBuffer();
        error(Messages.getInstance().getErrorString("GenericServlet.ERROR_0002_BAD_GENERATOR", request.getQueryString()), // $NON-NLS-1$
        e);
        List errorList = new ArrayList();
        String msg = e.getMessage();
        errorList.add(msg);
        // $NON-NLS-1$
        MessageFormatUtils.formatFailureMessage("text/html", null, buffer, errorList);
        response.getOutputStream().write(buffer.toString().getBytes(LocaleHelper.getSystemEncoding()));
    } finally {
        // reset the classloader of the current thread
        Thread.currentThread().setContextClassLoader(origContextClassloader);
        PentahoSystem.systemExitPoint();
    }
}
Also used : IMimeTypeListener(org.pentaho.platform.api.engine.IMimeTypeListener) HashMap(java.util.HashMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) IParameterProvider(org.pentaho.platform.api.engine.IParameterProvider) HttpRequestParameterProvider(org.pentaho.platform.web.http.request.HttpRequestParameterProvider) IContentGenerator(org.pentaho.platform.api.engine.IContentGenerator) ArrayList(java.util.ArrayList) List(java.util.List) SimpleParameterProvider(org.pentaho.platform.engine.core.solution.SimpleParameterProvider) Enumeration(java.util.Enumeration) InputStream(java.io.InputStream) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) IPentahoRequestContext(org.pentaho.platform.api.engine.IPentahoRequestContext) IOutputHandler(org.pentaho.platform.api.engine.IOutputHandler) HttpSessionParameterProvider(org.pentaho.platform.web.http.session.HttpSessionParameterProvider) IPluginManager(org.pentaho.platform.api.engine.IPluginManager) SimpleUrlFactory(org.pentaho.platform.util.web.SimpleUrlFactory)

Example 70 with IPentahoSession

use of org.pentaho.platform.api.engine.IPentahoSession in project pentaho-platform by pentaho.

the class GetResource method doPost.

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    // TODO perform any authorization here...
    // TODO support caching
    PentahoSystem.systemEntryPoint();
    try {
        IPentahoSession session = getPentahoSession(request);
        // $NON-NLS-1$
        String resource = request.getParameter("resource");
        if ((resource == null) || StringUtil.doesPathContainParentPathSegment(resource)) {
            // $NON-NLS-1$
            error(Messages.getInstance().getErrorString("GetResource.ERROR_0001_RESOURCE_PARAMETER_MISSING"));
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }
        String resLower = resource.toLowerCase();
        String resourcePath;
        if (resLower.endsWith(".xsl")) {
            // $NON-NLS-1$
            // $NON-NLS-1$
            resourcePath = "system/custom/xsl/" + resource;
        } else if (resLower.endsWith(".mondrian.xml")) {
            // $NON-NLS-1$
            // Ensure user is authenticated by checking the default role
            // gets defaultRole from pentahoObjects-s-s.x
            String defaultRole = PentahoSystem.get(String.class, "defaultRole", null);
            if (defaultRole != null) {
                if (!SecurityHelper.getInstance().isGranted(session, new SimpleGrantedAuthority(defaultRole))) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            }
            // If no defaultRole is defined, then just continue action as per normal.
            resourcePath = resource;
        } else if (resLower.endsWith(".jpg") || resLower.endsWith(".jpeg") || resLower.endsWith(".gif") || resLower.endsWith(".png") || resLower.endsWith(".bmp")) {
            // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
            resourcePath = resource;
        } else {
            // $NON-NLS-1$
            error(Messages.getInstance().getErrorString("GetResource.ERROR_0002_INVALID_FILE", resource));
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }
        IActionSequenceResource asqr = new // $NON-NLS-1$ //$NON-NLS-2$
        ActionSequenceResource(// $NON-NLS-1$ //$NON-NLS-2$
        "", // $NON-NLS-1$ //$NON-NLS-2$
        IActionSequenceResource.SOLUTION_FILE_RESOURCE, // $NON-NLS-1$ //$NON-NLS-2$
        "", resourcePath);
        InputStream in = asqr.getInputStream(RepositoryFilePermission.READ, LocaleHelper.getLocale());
        if (in == null) {
            // $NON-NLS-1$
            error(Messages.getInstance().getErrorString("GetResource.ERROR_0003_RESOURCE_MISSING", resourcePath));
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }
        String mimeType = getServletContext().getMimeType(resourcePath);
        String resourceName = resourcePath;
        if (resourcePath.indexOf("/") != -1) {
            // $NON-NLS-1$
            // $NON-NLS-1$
            resourceName = resourcePath.substring(resourcePath.lastIndexOf("/") + 1);
        }
        // $NON-NLS-1$ //$NON-NLS-2$
        response.setHeader("content-disposition", "attachment;filename=" + resourceName);
        if ((null == mimeType) || (mimeType.length() <= 0)) {
            // Hard coded to PNG because BIRT does not give us a mime type at
            // all...
            // $NON-NLS-1$
            response.setContentType("image/png");
        } else {
            response.setContentType(mimeType);
        }
        response.setCharacterEncoding(LocaleHelper.getSystemEncoding());
        // $NON-NLS-1$ //$NON-NLS-2$
        response.setHeader("expires", "0");
        // Open the input and output streams
        OutputStream out = response.getOutputStream();
        try {
            // Copy the contents of the file to the output stream
            byte[] buf = new byte[1024];
            int count = 0;
            int totalBytes = 0;
            while ((count = in.read(buf)) >= 0) {
                out.write(buf, 0, count);
                totalBytes += count;
            }
            response.setContentLength(totalBytes);
        } finally {
            in.close();
            out.close();
        }
    } finally {
        PentahoSystem.systemExitPoint();
    }
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IActionSequenceResource(org.pentaho.platform.api.engine.IActionSequenceResource) ActionSequenceResource(org.pentaho.platform.engine.services.actionsequence.ActionSequenceResource) IActionSequenceResource(org.pentaho.platform.api.engine.IActionSequenceResource)

Aggregations

IPentahoSession (org.pentaho.platform.api.engine.IPentahoSession)231 StandaloneSession (org.pentaho.platform.engine.core.system.StandaloneSession)76 Test (org.junit.Test)70 Matchers.anyString (org.mockito.Matchers.anyString)40 ArrayList (java.util.ArrayList)32 ITenant (org.pentaho.platform.api.mt.ITenant)22 IOException (java.io.IOException)20 StandaloneObjectFactory (org.pentaho.platform.engine.core.system.objfac.StandaloneObjectFactory)18 File (java.io.File)17 RepositoryFile (org.pentaho.platform.api.repository2.unified.RepositoryFile)16 Before (org.junit.Before)14 OutputStream (java.io.OutputStream)13 HashMap (java.util.HashMap)13 InputStream (java.io.InputStream)12 IRuntimeContext (org.pentaho.platform.api.engine.IRuntimeContext)12 ModelInfo (org.pentaho.platform.dataaccess.datasource.wizard.models.ModelInfo)12 Domain (org.pentaho.metadata.model.Domain)11 ObjectFactoryException (org.pentaho.platform.api.engine.ObjectFactoryException)11 List (java.util.List)10 IPentahoResultSet (org.pentaho.commons.connection.IPentahoResultSet)10