Example usage for javax.servlet.http HttpServletRequest getRemoteUser

List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteUser.

Prototype

public String getRemoteUser();

Source Link

Document

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

Usage

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public void addJoinToReport(HttpServletRequest request, Connection conn, SimpleReportInfo report,
        JoinClauseInfo join) throws DisallowedException, SQLException, CantDoThatException,
        CodingErrorException, ObjectNotFoundException {
    if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE,
            report.getParentTable()))) {
        throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE,
                report.getParentTable());
    }//from   w  w  w  . j a v a  2 s .com
    HibernateUtil.activateObject(report);
    report.addJoin(join);
    this.updateViewDbAction(conn, report, request);
    this.dataManagement.logLastSchemaChangeTime(request);
    UsageLogger usageLogger = new UsageLogger(this.relationalDataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logReportSchemaChange(user, report, AppAction.ADD_JOIN_TO_REPORT, "join: " + join);
    UsageLogger.startLoggingThread(usageLogger);
}

From source file:edu.wisc.my.redirect.PortalUrlRedirectController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    final String serverName = request.getServerName();
    final PortalUrl portalUrl = this.portalUrlProvider.getPortalUrl(serverName);

    if (this.portletFunctionalName != null) {
        portalUrl.setTargetPortlet(this.portletFunctionalName);
    }//from  w w  w  .  j  a  v a2  s .  c  o  m

    if (this.tabIndex != null) {
        portalUrl.setTabIndex(this.tabIndex);
    }

    //If strict param matching only run if the request parameter keyset matches the mapped parameter keyset
    final Set<?> requestParameterKeys = request.getParameterMap().keySet();
    if (this.strictParameterMatching && !requestParameterKeys.equals(this.parameterMappings.keySet())) {
        if (this.logger.isInfoEnabled()) {
            this.logger.info("Sending not found error, requested parameter key set " + requestParameterKeys
                    + " does not match mapped parameter key set " + this.parameterMappings.keySet());
        }

        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    //Map static parameters
    logger.debug("Mapping " + staticParameters.size() + " static parameters");
    for (final Map.Entry<String, List<String>> parameterMappingEntry : this.staticParameters.entrySet()) {
        final String name = parameterMappingEntry.getKey();
        final List<String> values = parameterMappingEntry.getValue();

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Adding static parameter '" + name + "' with values: " + values);
        }

        portalUrl.setParameter(name, values.toArray(new String[values.size()]));
    }

    //Map request parameters
    logger.debug("Mapping " + parameterMappings.entrySet().size() + " request parameters");
    for (final Map.Entry<String, Set<String>> parameterMappingEntry : this.parameterMappings.entrySet()) {
        final String name = parameterMappingEntry.getKey();
        logger.debug("Mapping parameter " + name);
        final String[] values = request.getParameterValues(name);

        if (values != null) {
            for (final String mappedName : parameterMappingEntry.getValue()) {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Mapping parameter '" + name + "' to portal parameter '" + mappedName
                            + "' with values: " + Arrays.asList(values));
                }

                portalUrl.setParameter(mappedName, values);
            }

            //Add any conditional parameters for the URL parameter
            final Map<String, List<String>> conditionalParameters = this.conditionalParameterMappings.get(name);
            if (conditionalParameters != null) {
                for (final Map.Entry<String, List<String>> conditionalParameterEntry : conditionalParameters
                        .entrySet()) {
                    final String condName = conditionalParameterEntry.getKey();
                    final List<String> condValues = conditionalParameterEntry.getValue();

                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug(
                                "Adding conditional parameter '" + condName + "' with values: " + condValues);
                    }

                    portalUrl.setParameter(condName, condValues.toArray(new String[condValues.size()]));
                }
            }
        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug(
                    "Skipping mapped parameter '" + name + "' since it was not specified on the original URL");
        }
    }

    //Set public based on if remoteUser is set
    final String remoteUser = request.getRemoteUser();
    final boolean isAuthenticated = StringUtils.isNotBlank(remoteUser);
    portalUrl.setPublic(!isAuthenticated);

    if (this.windowState != null) {
        portalUrl.setWindowState(this.windowState);
    }

    if (this.portletMode != null) {
        portalUrl.setWindowState(this.portletMode);
    }

    portalUrl.setType(RequestType.ACTION);

    final String redirectUrl = portalUrl.toString();
    if (this.logger.isInfoEnabled()) {
        this.logger.info("Redirecting to: " + redirectUrl);
    }

    return new ModelAndView(new RedirectView(redirectUrl, false));
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public void addFilterToReport(HttpServletRequest request, Connection conn, SimpleReportInfo report,
        ReportFilterInfo filter) throws SQLException, DisallowedException, CantDoThatException,
        CodingErrorException, ObjectNotFoundException {
    if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE,
            report.getParentTable()))) {
        throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE,
                report.getParentTable());
    }//from  w  w  w.j a v a2 s  .c  o m
    HibernateUtil.activateObject(report);
    report.addFilter(filter);
    this.updateViewDbAction(conn, report, request);
    this.dataManagement.logLastSchemaChangeTime(request);
    UsageLogger usageLogger = new UsageLogger(this.relationalDataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logReportSchemaChange(user, report, AppAction.ADD_FILTER_TO_REPORT, "filter: " + filter);
    UsageLogger.startLoggingThread(usageLogger);
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public void addFunctionToChart(HttpServletRequest request, ChartAggregateInfo addedAggFn)
        throws DisallowedException, CantDoThatException, ObjectNotFoundException, SQLException {
    BaseReportInfo report = addedAggFn.getReportField().getParentReport();
    if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE,
            report.getParentTable()))) {
        throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE,
                report.getParentTable());
    }//  w  w w  .ja  v  a  2 s. c  om
    ChartInfo chart = report.getChart();
    HibernateUtil.activateObject(chart);
    chart.addFunction(addedAggFn);
    this.dataManagement.logLastSchemaChangeTime(request);
    UsageLogger usageLogger = new UsageLogger(this.relationalDataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logReportSchemaChange(user, report, AppAction.ADD_FUNCTION_TO_CHART, "function: " + addedAggFn);
    UsageLogger.startLoggingThread(usageLogger);
    // Test change by selecting rows from the database
    CompanyInfo company = this.getAuthManager().getCompanyForLoggedInUser(request);
    Map<BaseField, String> blankFilterValues = new HashMap<BaseField, String>();
    ChartDataInfo reportSummaryData = this.getDataManagement().getChartData(company, report.getChart(),
            blankFilterValues, false);
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public void removeJoinFromReport(HttpServletRequest request, Connection conn, SimpleReportInfo report,
        JoinClauseInfo join) throws DisallowedException, SQLException, CantDoThatException,
        CodingErrorException, ObjectNotFoundException {
    if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE,
            report.getParentTable()))) {
        throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE,
                report.getParentTable());
    }/*ww w.j  a va2s  . c om*/
    HibernateUtil.activateObject(report);
    report.removeJoin(join);
    this.updateViewDbAction(conn, report, request);
    HibernateUtil.currentSession().delete(join);
    this.dataManagement.logLastSchemaChangeTime(request);
    UsageLogger usageLogger = new UsageLogger(this.relationalDataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logReportSchemaChange(user, report, AppAction.REMOVE_JOIN_FROM_REPORT, "join: " + join);
    UsageLogger.startLoggingThread(usageLogger);
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public void removeFilterFromReport(HttpServletRequest request, Connection conn, SimpleReportInfo report,
        ReportFilterInfo filter) throws DisallowedException, ObjectNotFoundException, CantDoThatException,
        SQLException, CodingErrorException {
    if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE,
            report.getParentTable()))) {
        throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE,
                report.getParentTable());
    }/*  w  w  w.j  a  v  a  2s .co  m*/
    HibernateUtil.activateObject(report);
    report.removeFilter(filter);
    this.updateViewDbAction(conn, report, request);
    HibernateUtil.currentSession().delete(filter);
    this.dataManagement.logLastSchemaChangeTime(request);
    UsageLogger usageLogger = new UsageLogger(this.relationalDataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logReportSchemaChange(user, report, AppAction.REMOVE_FILTER_FROM_REPORT, "filter: " + filter);
    UsageLogger.startLoggingThread(usageLogger);
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public BaseField addField(HttpServletRequest request, Connection conn, TableInfo table, String fieldType,
        String internalFieldName, String fieldName, String fieldDesc) throws SQLException,
        ObjectNotFoundException, DisallowedException, CantDoThatException, CodingErrorException {
    if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE,
            table))) {//from  w  w  w  .  ja  va 2  s .c  o  m
        throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE,
                table);
    }
    BaseField field = null;
    field = this.generateFieldObject(request, table, fieldType, internalFieldName, fieldName, fieldDesc);
    this.addField(conn, table, field, request);
    // schema change time not recorded in memory because it doesn't affect
    // summary reports
    // this.dataManagement.logLastSchemaChangeTime(request);
    UsageLogger usageLogger = new UsageLogger(this.relationalDataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logTableSchemaChange(user, table, AppAction.ADD_FIELD, "field name: " + fieldName);
    UsageLogger.startLoggingThread(usageLogger);
    return field;
}

From source file:com.ikon.servlet.frontend.DownloadServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("service({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String path = request.getParameter("path");
    String uuid = request.getParameter("uuid");
    String[] uuidList = request.getParameterValues("uuidList");
    String[] pathList = request.getParameterValues("pathList");
    String checkout = request.getParameter("checkout");
    String ver = request.getParameter("ver");
    boolean export = request.getParameter("export") != null;
    boolean inline = request.getParameter("inline") != null;
    File tmp = File.createTempFile("okm", ".tmp");
    Document doc = null;/*from  w w  w. j ava  2s  .  c om*/
    InputStream is = null;
    updateSessionManager(request);

    try {
        // Now an document can be located by UUID
        if (uuid != null && !uuid.equals("")) {
            path = OKMRepository.getInstance().getNodePath(null, uuid);
        } else if (path != null) {
            path = new String(path.getBytes("ISO-8859-1"), "UTF-8");
        }

        if (export) {
            if (exportZip) {
                String fileName = "export.zip";

                // Get document
                FileOutputStream os = new FileOutputStream(tmp);

                if (path != null) {
                    exportFolderAsZip(path, os);
                    fileName = PathUtils.getName(path) + ".zip";
                } else if (uuidList != null || pathList != null) {
                    // Export into a zip file multiple documents
                    List<String> paths = new ArrayList<String>();

                    if (uuidList != null) {
                        for (String uuidElto : uuidList) {
                            String foo = new String(uuidElto.getBytes("ISO-8859-1"), "UTF-8");
                            paths.add(OKMRepository.getInstance().getNodePath(null, foo));
                        }
                    } else if (pathList != null) {
                        for (String pathElto : pathList) {
                            String foo = new String(pathElto.getBytes("ISO-8859-1"), "UTF-8");
                            paths.add(foo);
                        }
                    }

                    fileName = PathUtils.getName(PathUtils.getParent(paths.get(0)));
                    exportDocumentsAsZip(paths, os, fileName);
                    fileName += ".zip";
                }

                os.flush();
                os.close();
                is = new FileInputStream(tmp);

                // Send document
                WebUtils.sendFile(request, response, fileName, MimeTypeConfig.MIME_ZIP, inline, is);
            } else if (exportJar) {
                // Get document
                FileOutputStream os = new FileOutputStream(tmp);
                exportFolderAsJar(path, os);
                os.flush();
                os.close();
                is = new FileInputStream(tmp);

                // Send document
                String fileName = PathUtils.getName(path) + ".jar";
                WebUtils.sendFile(request, response, fileName, "application/x-java-archive", inline, is);

            }
        } else {
            // Get document
            doc = OKMDocument.getInstance().getProperties(null, path);

            if (ver != null && !ver.equals("")) {
                is = OKMDocument.getInstance().getContentByVersion(null, path, ver);
            } else {
                is = OKMDocument.getInstance().getContent(null, path, checkout != null);
            }

            // Send document
            String fileName = PathUtils.getName(doc.getPath());
            WebUtils.sendFile(request, response, fileName, doc.getMimeType(), inline, is);

            UserActivity.log(request.getRemoteUser(), "DOWNLOAD_DOCUMENT", uuid, path, null);
        }
    } catch (PathNotFoundException e) {
        log.warn(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_PathNotFound),
                e.getMessage()));
    } catch (RepositoryException e) {
        log.warn(e.getMessage(), e);
        throw new ServletException(
                new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Repository),
                        e.getMessage()));
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_IO), e.getMessage()));
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Database), e.getMessage()));
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_General), e.getMessage()));
    } finally {
        IOUtils.closeQuietly(is);
        FileUtils.deleteQuietly(tmp);
    }

    log.debug("service: void");
}

From source file:com.edgenius.wiki.webapp.servlet.UploadServlet.java

@SuppressWarnings("unchecked")
protected void doService(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if ("GET".equalsIgnoreCase(request.getMethod())) {
        //just render blank page for upload
        String pageUuid = request.getParameter("puuid");
        String spaceUname = request.getParameter("uname");
        String draft = request.getParameter("draft");

        request.setAttribute("pageUuid", pageUuid);
        request.setAttribute("spaceUname", spaceUname);
        request.setAttribute("draft", NumberUtils.toInt(draft, PageType.NONE_DRAFT.value()));

        request.getRequestDispatcher("/WEB-INF/pages/upload.jsp").forward(request, response);

        return;/*from w  ww.  jav  a  2s.  c  o m*/
    }

    //post - upload

    //      if(WikiUtil.getUser().isAnonymous()){
    //      //anonymous can not allow to upload any files

    PageService pageService = getPageService();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

    List<FileNode> files = new ArrayList<FileNode>();
    String pageUuid = null, spaceUname = null;
    try {
        int status = PageType.NONE_DRAFT.value();
        // index->filename
        Map<String, FileItem> fileMap = new HashMap<String, FileItem>();
        Map<String, String> descMap = new HashMap<String, String>();
        // index->index
        Map<String, String> indexMap = new HashMap<String, String>();

        //offline submission, filename put into hidden variable rather than <input type="file> tag
        Map<String, String> filenameMap = new HashMap<String, String>();
        //TODO: offline submission, version also upload together with file, this give a change to do failure tolerance check:
        //if version is same with online save, then it is OK, if greater, means it maybe duplicated upload, if less, unpexected case
        Map<String, String> versionMap = new HashMap<String, String>();

        Map<String, Boolean> bulkMap = new HashMap<String, Boolean>();

        Map<String, Boolean> sharedMap = new HashMap<String, Boolean>();
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            String name = item.getFieldName();
            if (StringUtils.equals(name, "spaceUname")) {
                spaceUname = item.getString(Constants.UTF8);
            } else if (StringUtils.equals(name, "pageUuid")) {
                pageUuid = item.getString();
            } else if (name.startsWith("draft")) {
                // check this upload is from "click save button" or "auto upload in draft status"
                status = Integer.parseInt(item.getString());
            } else if (name.startsWith("file")) {
                fileMap.put(name.substring(4), item);
                indexMap.put(name.substring(4), name.substring(4));
            } else if (name.startsWith("desc")) {
                descMap.put(name.substring(4), item.getString(Constants.UTF8));
            } else if (name.startsWith("shar")) {
                sharedMap.put(name.substring(4), Boolean.parseBoolean(item.getString()));
            } else if (name.startsWith("name")) {
                filenameMap.put(name.substring(4), item.getString());
            } else if (name.startsWith("vers")) {
                versionMap.put(name.substring(4), item.getString());
            } else if (name.startsWith("bulk")) {
                bulkMap.put(name.substring(4), BooleanUtils.toBoolean(item.getString()));
            }
        }
        if (StringUtils.isBlank(pageUuid)) {
            log.error("Attachment can not be load because of page does not save successfully.");
            throw new PageException("Attachment can not be load because of page does not save successfully.");
        }

        List<FileNode> bulkFiles = new ArrayList<FileNode>();
        String username = request.getRemoteUser();
        // put file/desc pair into final Map
        for (String id : fileMap.keySet()) {
            FileItem item = fileMap.get(id);
            if (item == null || item.getInputStream() == null || item.getSize() <= 0) {
                log.warn("Empty upload item:" + (item != null ? item.getName() : ""));
                continue;
            }
            FileNode node = new FileNode();
            node.setComment(descMap.get(id));
            node.setShared(sharedMap.get(id) == null ? false : sharedMap.get(id));
            node.setFile(item.getInputStream());
            String filename = item.getName();
            if (StringUtils.isBlank(filename)) {
                //this could be offline submission, get name from map
                filename = filenameMap.get(id);
            }
            node.setFilename(FileUtil.getFileName(filename));
            node.setContentType(item.getContentType());
            node.setIndex(indexMap.get(id));
            node.setType(RepositoryService.TYPE_ATTACHMENT);
            node.setIdentifier(pageUuid);
            node.setCreateor(username);
            node.setStatus(status);
            node.setSize(item.getSize());
            node.setBulkZip(bulkMap.get(id) == null ? false : bulkMap.get(id));

            files.add(node);

            if (node.isBulkZip())
                bulkFiles.add(node);
        }
        if (spaceUname != null && pageUuid != null && files.size() > 0) {
            files = pageService.uploadAttachments(spaceUname, pageUuid, files, false);

            //only save non-draft uploaded attachment
            if (status == 0) {
                try {
                    getActivityLog().logAttachmentUploaded(spaceUname,
                            pageService.getCurrentPageByUuid(pageUuid).getTitle(), WikiUtil.getUser(), files);
                } catch (Exception e) {
                    log.warn("Activity log save error for attachment upload", e);
                }
            }
            //as bulk files won't in return list in PageService.uploadAttachments(), here need 
            //append to all return list, but only for client side "uploading panel" clean purpose
            files.addAll(bulkFiles);
            //TODO: if version come in together, then do check
            //            if(versionMap.size() > 0){
            //               for (FileNode node: files) {
            //                  
            //               }
            //            }
        }

    } catch (RepositoryQuotaException e) {
        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.quota.exhaust"));
        files = Arrays.asList(att);
    } catch (AuthenticationException e) {
        String redir = ((RedirectResponseWrapper) response).getRedirect();
        if (redir == null)
            redir = WikiConstants.URL_LOGIN;
        log.info("Send Authentication redirect URL " + redir);

        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.authentication.required"));
        files = Arrays.asList(att);

    } catch (AccessDeniedException e) {
        String redir = ((RedirectResponseWrapper) response).getRedirect();
        if (redir == null)
            redir = WikiConstants.URL_ACCESS_DENIED;
        log.info("Send AccessDenied redirect URL " + redir);

        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.access.denied"));
        files = Arrays.asList(att);

    } catch (Exception e) {
        // FileUploadException,RepositoryException
        log.error("File upload failed ", e);
        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.upload"));
        files = Arrays.asList(att);
    }

    try {
        String json = FileNode.toAttachmentsJson(files, spaceUname, WikiUtil.getUser(), getMessageService(),
                getUserReadingService());

        //TODO: does not compress request in Gzip, refer to 
        //http://www.google.com/codesearch?hl=en&q=+RemoteServiceServlet+show:PAbNFg2Qpdo:akEoB_bGF1c:4aNSrXYgYQ4&sa=N&cd=1&ct=rc&cs_p=https://ssl.shinobun.org/svn/repos/trunk&cs_f=proprietary/gwt/gwt-user/src/main/java/com/google/gwt/user/server/rpc/RemoteServiceServlet.java#first
        byte[] reply = json.getBytes(Constants.UTF8);
        response.setContentLength(reply.length);
        response.setContentType("text/plain; charset=utf-8");
        response.getOutputStream().write(reply);
    } catch (IOException e) {
        log.error(e.toString(), e);
    }
}

From source file:com.edgenius.wiki.webapp.servlet.DownloadServlet.java

protected void doService(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    initServiceBean();//from   w  w  w . j  a  v  a2  s . c  o m

    String instance = request.getParameter("instance");
    String logo = request.getParameter("logo");
    String slogo = request.getParameter("slogo");
    String portrait = request.getParameter("portrait");
    String username = request.getParameter("user");
    String export = request.getParameter("export");
    String spaceUname;
    String uuid;
    String version;

    if (!StringUtils.isBlank(export)) {
        FileNode attachment = null;
        try {
            attachment = exportService.getExportFileNode(export);
            if (attachment != null)
                handleFileNode(response, attachment, true);
        } finally {
            if (attachment != null) {
                //some trick, the return Identifier from exportService.getExportFileNode() is full file name with path info...
                File file = new File(attachment.getIdentifier());
                if (!file.delete())
                    file.deleteOnExit();
            }
        }
        return;
    } else if (!StringUtils.isBlank(portrait)) {
        //special for user portrait image download
        spaceUname = RepositoryService.DEFAULT_SPACE_NAME;
        uuid = portrait;
        version = null;
        if (uuid == null) {
            //this user does not have customized portrait. replace system default one
            response.sendRedirect(WebUtil.getWebConext() + "static/images/" + SharedConstants.NO_PORTRAIT_IMG);
            return;
        }
    } else if (!StringUtils.isBlank(logo) || !StringUtils.isBlank(slogo)) {
        spaceUname = request.getParameter("space");
        uuid = StringUtils.isBlank(logo) ? slogo : logo;
        version = null;
        if (uuid == null) {
            //this space does not has customized logo,get from theme
            Space space = spaceService.getSpaceByUname(spaceUname);
            Theme theme = themeService.getSpaceTheme(space);
            response.sendRedirect(
                    StringUtils.isBlank(logo) ? theme.getSmallLogoURL() : theme.getLargeLogoURL());
            return;
        }
    } else if (!StringUtils.isBlank(username)) {
        //special for user portrait image download
        spaceUname = RepositoryService.DEFAULT_SPACE_NAME;
        User user = userReadingService.getUserByName(username);
        uuid = user == null ? null : user.getPortrait();
        version = null;
        if (uuid == null) {
            //this user does not have customized portrait. replace system default one
            response.sendRedirect(WebUtil.getWebConext() + "static/images/" + SharedConstants.NO_PORTRAIT_IMG);
            return;
        }
    } else if (!StringUtils.isBlank(instance)) {
        spaceUname = RepositoryService.DEFAULT_SPACE_NAME;
        version = null;
        uuid = themeService.getSystemLogo();
        if (uuid == null) {
            //this user does not have customized portrait. replace system default one
            response.sendRedirect(WebUtil.getWebConext() + "static/images/" + SharedConstants.INSANCE_LOGO);
            return;
        }
    } else {
        //general download by node UUID and Version.
        spaceUname = request.getParameter("space");
        uuid = request.getParameter("uuid");
        version = request.getParameter("version");
    }

    boolean downloadFile = Boolean.parseBoolean(request.getParameter("download"));
    FileNode attachment = null;
    try {
        ITicket ticket = repoService.login(spaceUname, spaceUname, spaceUname);
        attachment = repoService.downloadFile(ticket, uuid, version, WikiUtil.getUser());
        if (attachment != null) {
            // do security check first
            User user = userReadingService.getUserByName(request.getRemoteUser());
            boolean readAllow = true;
            //default space attachment allow all user download!!!
            //only not default repository space, it need check attachment permission.
            if (!RepositoryService.DEFAULT_SPACE_NAME.equals(spaceUname)) {
                if (Boolean.valueOf(attachment.isShared()).booleanValue()
                        || attachment.getType().equalsIgnoreCase(RepositoryService.TYPE_SPACE)) {
                    // shared, only need check space level permission
                    readAllow = securityService.isAllowSpaceReading(spaceUname, user);
                } else {
                    // non-shared, need check page level permission
                    readAllow = securityService.isAllowPageReading(spaceUname, attachment.getIdentifier(),
                            user);
                }
            }
            if (readAllow) {
                // process download
                handleFileNode(response, attachment, downloadFile);
            } else {
                response.getOutputStream()
                        .write(messageService.getMessage("no.perm.download").getBytes(Constants.UTF8));
            }
        } else {
            response.getOutputStream()
                    .write(messageService.getMessage("no.file.download").getBytes(Constants.UTF8));
        }
    } catch (RepositoryException e) {
        log.error("Failed get file from repository: ", e);
    } finally {
        if (attachment != null)
            attachment.closeStream();
    }

}