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:javax.faces.webapp.FacesServlet.java

public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    String pathInfo = httpRequest.getPathInfo();

    // if it is a prefix mapping ...
    if (pathInfo != null && (pathInfo.startsWith("/WEB-INF") || pathInfo.startsWith("/META-INF"))) {
        StringBuffer buffer = new StringBuffer();

        buffer.append(" Someone is trying to access a secure resource : ").append(pathInfo);
        buffer.append("\n remote address is ").append(httpRequest.getRemoteAddr());
        buffer.append("\n remote host is ").append(httpRequest.getRemoteHost());
        buffer.append("\n remote user is ").append(httpRequest.getRemoteUser());
        buffer.append("\n request URI is ").append(httpRequest.getRequestURI());

        log.warn(buffer.toString());// w w w.j a v a 2 s  .co  m

        // Why does RI return a 404 and not a 403, SC_FORBIDDEN ?

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

    if (log.isTraceEnabled())
        log.trace("service begin");
    FacesContext facesContext = _facesContextFactory.getFacesContext(_servletConfig.getServletContext(),
            request, response, _lifecycle);
    try {
        _lifecycle.execute(facesContext);
        _lifecycle.render(facesContext);
    } catch (Throwable e) {
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e.getMessage() != null) {
            throw new ServletException(e.getMessage(), e);
        } else {
            throw new ServletException(e);
        }
    } finally {
        facesContext.release();
    }
    if (log.isTraceEnabled())
        log.trace("service end");
}

From source file:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

@DELETE
@Path("/{id}")
@Produces(APPLICATION_JSON)/*from  ww w .j  ava2 s  . c o m*/
public Response deleteReport(@Context HttpServletRequest request, @PathParam("id") Long id,
        @HeaderParam("scopeName") String scopeName, @HeaderParam("roleName") String roleName) {

    String username = request.getRemoteUser();

    log.debug("{} is requesting deleteReport(...), with a ID={} and scopeName={}", username, id, scopeName);
    ReportDTO originalReport;
    boolean isAdmin = request.isUserInRole(ReportFeatureEnum.MANAGE_ALL_REPORTS.toString());

    try {
        Set<String> features = usmService.getUserFeatures(username, getApplicationName(request), roleName,
                scopeName);
        // for delete operation, we don't really nead the permitted service layers,
        // therefore we pass null
        originalReport = reportService.findById(features, id, username, scopeName, isAdmin, null); // we need the
        // original
        // report
        // because of
        // the
        // 'owner/createdBy'
        // attribute,
        // which is not
        // contained in
        // the JSON
    } catch (Exception e) {
        String errorMsg = "Failed to get report.";
        log.error(errorMsg, e);
        return createErrorResponse(errorMsg);
    }

    if (originalReport == null) {
        createScNotFoundErrorResponse(ErrorCodes.ENTRY_NOT_FOUND);
    }

    ReportFeatureEnum requiredFeature = AuthorizationCheckUtil.getRequiredFeatureToDeleteReport(originalReport,
            username);

    if (requiredFeature != null && !request.isUserInRole(requiredFeature.toString())) {
        createScNotFoundErrorResponse(ErrorCodes.NOT_AUTHORIZED);
    }

    try {
        reportService.delete(id, username, scopeName, isAdmin);
    } catch (Exception exc) {
        log.error("Report deletion failed.", exc);
        createErrorResponse(ErrorCodes.DELETE_FAILED);
    }

    return createSuccessResponse();
}

From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {/* w w w.j av  a  2s. c  o  m*/
        String userApprovedParamS = req.getParameter(ProxyUriUtils.PROXY_APPROVAL_PARAM);
        boolean userWasWarned = false;
        boolean userApproved = (userApprovedParamS != null && Boolean.valueOf(userApprovedParamS));
        boolean securityEnabled = isSecurityEnabled();
        final String remoteUser = req.getRemoteUser();
        final String pathInfo = req.getPathInfo();

        String parts[] = pathInfo.split("/", 3);
        if (parts.length < 2) {
            LOG.warn(remoteUser + " Gave an invalid proxy path " + pathInfo);
            notFound(resp, "Your path appears to be formatted incorrectly.");
            return;
        }
        //parts[0] is empty because path info always starts with a /
        String appId = parts[1];
        String rest = parts.length > 2 ? parts[2] : "";
        ApplicationId id = Apps.toAppID(appId);
        if (id == null) {
            LOG.warn(req.getRemoteUser() + " Attempting to access " + appId + " that is invalid");
            notFound(resp, appId + " appears to be formatted incorrectly.");
            return;
        }

        if (securityEnabled) {
            String cookieName = getCheckCookieName(id);
            Cookie[] cookies = req.getCookies();
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if (cookieName.equals(c.getName())) {
                        userWasWarned = true;
                        userApproved = userApproved || Boolean.valueOf(c.getValue());
                        break;
                    }
                }
            }
        }

        boolean checkUser = securityEnabled && (!userWasWarned || !userApproved);

        ApplicationReport applicationReport = null;
        try {
            applicationReport = getApplicationReport(id);
        } catch (ApplicationNotFoundException e) {
            applicationReport = null;
        }
        if (applicationReport == null) {
            LOG.warn(req.getRemoteUser() + " Attempting to access " + id + " that was not found");

            URI toFetch = ProxyUriUtils.getUriFromTrackingPlugins(id, this.trackingUriPlugins);
            if (toFetch != null) {
                resp.sendRedirect(resp.encodeRedirectURL(toFetch.toString()));
                return;
            }

            notFound(resp, "Application " + appId + " could not be found, " + "please try the history server");
            return;
        }
        String original = applicationReport.getOriginalTrackingUrl();
        URI trackingUri = null;
        // fallback to ResourceManager's app page if no tracking URI provided
        if (original == null || original.equals("N/A")) {
            resp.sendRedirect(resp.encodeRedirectURL(StringHelper.pjoin(rmAppPageUrlBase, id.toString())));
            return;
        } else {
            if (ProxyUriUtils.getSchemeFromUrl(original).isEmpty()) {
                trackingUri = ProxyUriUtils.getUriFromAMUrl(WebAppUtils.getHttpSchemePrefix(conf), original);
            } else {
                trackingUri = new URI(original);
            }
        }

        String runningUser = applicationReport.getUser();
        if (checkUser && !runningUser.equals(remoteUser)) {
            LOG.info("Asking " + remoteUser + " if they want to connect to the " + "app master GUI of " + appId
                    + " owned by " + runningUser);
            warnUserPage(resp, ProxyUriUtils.getPathAndQuery(id, rest, req.getQueryString(), true), runningUser,
                    id);
            return;
        }
        URI toFetch = new URI(trackingUri.getScheme(), trackingUri.getAuthority(),
                StringHelper.ujoin(trackingUri.getPath(), rest), req.getQueryString(), null);

        LOG.info(req.getRemoteUser() + " is accessing unchecked " + toFetch + " which is the app master GUI of "
                + appId + " owned by " + runningUser);

        switch (applicationReport.getYarnApplicationState()) {
        case KILLED:
        case FINISHED:
        case FAILED:
            resp.sendRedirect(resp.encodeRedirectURL(toFetch.toString()));
            return;
        }
        Cookie c = null;
        if (userWasWarned && userApproved) {
            c = makeCheckCookie(id, true);
        }
        proxyLink(req, resp, toFetch, c, getProxyHost());

    } catch (URISyntaxException e) {
        throw new IOException(e);
    } catch (YarnException e) {
        throw new IOException(e);
    }
}

From source file:Properties.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter out = resp.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>My First Servlet</title>");
    out.println("</head>");
    out.println("<h2><center>");
    out.println("Information About You</center></h2>");
    out.println("<br>");

    out.println("<center><table border>");
    out.println("<tr>");
    out.println("<td>Method</td>");
    out.println("<td>" + req.getMethod() + "</td>");
    out.println("</tr>");

    out.println("<tr>");
    out.println("<td>User</td>");
    out.println("<td>" + req.getRemoteUser() + "</td>");
    out.println("</tr>");

    out.println("<tr>");
    out.println("<td>Client</td>");
    out.println("<td>" + req.getRemoteHost() + "</td>");
    out.println("</tr>");

    out.println("<tr>");
    out.println("<td>Protocol</td>");
    out.println("<td>" + req.getProtocol() + "</td>");
    out.println("</tr>");

    java.util.Enumeration e = req.getParameterNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println("<tr>");
        out.println("<td>Parameter '" + name + "'</td>");
        out.println("<td>" + req.getParameter(name) + "</td>");
        out.println("</tr>");
    }/*from ww  w  .  j ava2s  .  co m*/

    out.println("</table></center><br><hr><br>");

    out.println("<h2><center>");
    out.println("Server Properties</center></h2>");
    out.println("<br>");

    out.println("<center><table border width=80%>");

    java.util.Properties props = System.getProperties();
    e = props.propertyNames();

    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println("<tr>");
        out.println("<td>" + name + "</td>");
        out.println("<td>" + props.getProperty(name) + "</td>");
        out.println("</tr>");
    }
    out.println("</table></center>");

    out.println("</html>");
    out.flush();
}

From source file:br.com.siprot.framework.servlet.FacesServlet.java

public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    String pathInfo = httpRequest.getPathInfo();

    // if it is a prefix mapping ...
    if (pathInfo != null && (pathInfo.startsWith("/WEB-INF") || pathInfo.startsWith("/META-INF"))) {
        StringBuffer buffer = new StringBuffer();

        buffer.append(" Someone is trying to access a secure resource : ").append(pathInfo);
        buffer.append("\n remote address is ").append(httpRequest.getRemoteAddr());
        buffer.append("\n remote host is ").append(httpRequest.getRemoteHost());
        buffer.append("\n remote user is ").append(httpRequest.getRemoteUser());
        buffer.append("\n request URI is ").append(httpRequest.getRequestURI());

        log.warn(buffer.toString());//from w w  w .jav  a2  s . co  m

        // Why does RI return a 404 and not a 403, SC_FORBIDDEN ?

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

    if (log.isTraceEnabled())
        log.trace("service begin");
    FacesContext facesContext = _facesContextFactory.getFacesContext(_servletConfig.getServletContext(),
            request, response, _lifecycle);
    try {
        _lifecycle.execute(facesContext);
        _lifecycle.render(facesContext);
    } catch (Throwable e) {
        //bloco de tratamento para excecao tratada
        if (e instanceof FacesException) {
            try {
                ErrorHandler.handleException(facesContext, (Exception) e);
                _lifecycle.render(facesContext);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
        //fim do bloco de  tratamento
        else if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e.getMessage() != null) {
            throw new ServletException(e.getMessage(), e);
        } else {
            throw new ServletException(e);
        }
    } finally {
        facesContext.release();
    }
    if (log.isTraceEnabled())
        log.trace("service end");
}

From source file:org.eclipse.orion.server.git.servlets.GitConfigHandlerV1.java

@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String path)
        throws ServletException {
    try {/*from  w  w w  .j  a v a 2  s.c o m*/
        Path p = new Path(path);
        IPath filePath = p;
        if (p.segment(0).equals(Clone.RESOURCE) && p.segment(1).equals("file")) { //$NON-NLS-1$
            filePath = p.removeFirstSegments(1);
        } else if (p.segment(1).equals(Clone.RESOURCE) && p.segment(2).equals("file")) { //$NON-NLS-1$
            filePath = p.removeFirstSegments(2);
        }
        if (!AuthorizationService.checkRights(request.getRemoteUser(), "/" + filePath.toString(),
                request.getMethod())) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return true;
        }

        switch (getMethod(request)) {
        case GET:
            return handleGet(request, response, path);
        case POST:
            return handlePost(request, response, path);
        case PUT:
            return handlePut(request, response, path);
        case DELETE:
            return handleDelete(request, response, path);
        }
    } catch (Exception e) {
        String msg = NLS.bind("Failed to process an operation on commits for {0}", path); //$NON-NLS-1$
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
    }
    return false;
}

From source file:org.opennms.web.controller.ksc.AscoTlcCustomViewController.java

/** {@inheritDoc} */
@Override/* w w w.j  av  a  2s. c  o m*/
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    // Get Form Variable
    String username = request.getRemoteUser();
    if (username == null)
        throw new ServletException("Username is null: must be authenticated");

    Integer reportId = getReportId(username);
    if (reportId == null) {
        System.out.println("AscoTlc: DEBUG no KSC report found for username: " + username);

        KscReportEditor editor = KscReportEditor.getFromSession(request.getSession(), false);
        editor.loadNewWorkingReport();
        Report newreport = editor.getWorkingReport();
        newreport.setTitle(username);
        newreport.setShow_graphtype_button(false);
        newreport.setGraphs_per_line(getDefaultGraphsPerLine());
        newreport.setShow_timespan_button(true);
        System.out.println("AscoTlc: DEBUG creating new KSC report for username: " + username);

        List<String> resources = new ArrayList<String>();

        OnmsCriteria criteria = new OnmsCriteria(OnmsSnmpInterface.class);
        criteria.add(Restrictions.ilike("ifAlias", username, MatchMode.ANYWHERE));
        for (OnmsSnmpInterface snmpiface : m_snmpInterfaceDao.findMatching(criteria)) {
            String resourceId = "node[" + snmpiface.getNode().getNodeId() + "].interfaceSnmp["
                    + snmpiface.computeLabelForRRD() + "]";
            System.out.println("AscoTlc: DEBUG snmpinterface ifalias match found: resourceId:" + resourceId);
            resources.add(resourceId);
        }

        for (String resourceId : resources) {
            System.out.println("AscoTlc: DEBUG try to add graph for resource: " + resourceId);
            Graph vGraph = new Graph();
            vGraph.setTitle("");
            vGraph.setResourceId(resourceId);
            vGraph.setTimespan(DEFAULT_TIME_SPAN);

            // Check the resource
            OnmsResource resource = getResourceService().getResourceById(resourceId);

            if (resource == null) {
                System.out.println("AscoTlc: DEBUG no active resource found: skipping");
                continue;
            } else {
                System.out.println("AscoTlc: DEBUG adding graphs for active resource: " + resource.getId());
            }
            PrefabGraph[] prefab_graphs = getResourceService().findPrefabGraphsForResource(resource);
            for (PrefabGraph pg : prefab_graphs) {

                if (OPT_GRAPH_TYPE.equals(pg.getName())) {
                    vGraph.setGraphtype(OPT_GRAPH_TYPE);
                    break;
                } else if (DEFAULT_GRAPH_TYPE.equals(pg.getName())) {
                    vGraph.setGraphtype(DEFAULT_GRAPH_TYPE);
                    break;
                }
            }

            if (vGraph.getGraphtype() != null) {
                System.out.println("AscoTlc: DEBUG adding graph: " + vGraph.getResourceId());
                System.out.println("AscoTlc: DEBUG adding graph: " + vGraph.getGraphtype());
                newreport.addGraph(vGraph);
            } else {
                System.out.println("AscoTlc: DEBUG no default graph found: skipping resource: " + resourceId);
            }
        }
        System.out.println("AscoTlc: DEBUG saving KSC report for username: " + username);
        editor.unloadWorkingReport(getKscReportFactory());
        // Save the changes to the config file
        getKscReportFactory().saveCurrent();

        reportId = getReportId(username);
        if (reportId == null)
            throw new ServletException(
                    "Report could not be found in config file for username: '" + username + "'");
    }

    String overrideTimespan = WebSecurityUtils
            .sanitizeString(request.getParameter(Parameters.timespan.toString()));
    if ("null".equals(overrideTimespan) || "none".equals(overrideTimespan)) {
        overrideTimespan = null;
    }

    String overrideGraphType = WebSecurityUtils
            .sanitizeString(request.getParameter(Parameters.graphtype.toString()));
    if ("null".equals(overrideGraphType) || "none".equals(overrideGraphType)) {
        overrideGraphType = null;
    }

    // Load report to view 
    Report report = m_kscReportFactory.getReportByIndex(reportId);
    if (report == null) {

        throw new ServletException("Report could not be found in config file for index '" + reportId + "'");
    }

    // Get the list of available prefabricated graph options 
    Map<String, OnmsResource> resourceMap = new HashMap<String, OnmsResource>();
    Set<PrefabGraph> prefabGraphs = new TreeSet<PrefabGraph>();
    removeBrokenGraphsFromReport(report);
    List<Graph> graphCollection = report.getGraphCollection();
    if (!graphCollection.isEmpty()) {
        List<OnmsResource> resources = getKscReportService().getResourcesFromGraphs(graphCollection);
        for (int i = 0; i < graphCollection.size(); i++) {
            Graph graph = graphCollection.get(i);
            OnmsResource resource = null;
            try {
                resource = resources.get(i);
            } catch (IndexOutOfBoundsException e) {
                log().debug("Resource List Index Out Of Bounds Caught ", e);
            }

            resourceMap.put(graph.toString(), resource);
            if (resource == null) {
                log().debug("Could not get resource for graph " + graph + " in report " + report.getTitle());
            } else {
                prefabGraphs.addAll(Arrays.asList(getResourceService().findPrefabGraphsForResource(resource)));
            }

        }

        // Get default graph type from first element of graph_options
        // XXX Do we care about the tests on reportType?
    }

    List<KscResultSet> resultSets = new ArrayList<KscResultSet>(report.getGraphCount());
    for (Graph graph : graphCollection) {
        OnmsResource resource = resourceMap.get(graph.toString());
        if (resource != null) {
            promoteResourceAttributesIfNecessary(resource);
        }

        String displayGraphType;
        if (overrideGraphType == null) {
            displayGraphType = graph.getGraphtype();
        } else {
            displayGraphType = overrideGraphType;
        }

        PrefabGraph displayGraph;
        try {
            displayGraph = getResourceService().getPrefabGraph(displayGraphType);
        } catch (ObjectRetrievalFailureException e) {
            if (log().isDebugEnabled()) {
                log().debug("The prefabricated graph '" + displayGraphType + "' does not exist: " + e, e);
            }
            displayGraph = null;
        }

        boolean foundGraph = false;
        if (resource != null) {
            for (PrefabGraph availableGraph : getResourceService().findPrefabGraphsForResource(resource)) {
                if (availableGraph.equals(displayGraph)) {
                    foundGraph = true;
                    break;
                }
            }
        }

        if (!foundGraph) {
            displayGraph = null;
        }

        // gather start/stop time information
        String displayTimespan = null;
        if (overrideTimespan == null) {
            displayTimespan = graph.getTimespan();
        } else {
            displayTimespan = overrideTimespan;
        }
        Calendar beginTime = Calendar.getInstance();
        Calendar endTime = Calendar.getInstance();
        KSC_PerformanceReportFactory.getBeginEndTime(displayTimespan, beginTime, endTime);

        KscResultSet resultSet = new KscResultSet(graph.getTitle(), beginTime.getTime(), endTime.getTime(),
                resource, displayGraph);
        resultSets.add(resultSet);
    }

    ModelAndView modelAndView = new ModelAndView("/dashboard/ascoTlcCustomView");

    modelAndView.addObject("loggedIn", request.getRemoteUser() != null);
    if (report != null) {
        modelAndView.addObject("report", username);
    }

    modelAndView.addObject("title", report.getTitle());
    modelAndView.addObject("resultSets", resultSets);

    if (report.getShow_timespan_button()) {
        if (overrideTimespan == null
                || !getKscReportService().getTimeSpans(true).containsKey(overrideTimespan)) {
            modelAndView.addObject("timeSpan", "none");
        } else {
            modelAndView.addObject("timeSpan", overrideTimespan);
        }
        modelAndView.addObject("timeSpans", getKscReportService().getTimeSpans(true));
    } else {
        // Make sure it's null so the pulldown list isn't shown
        modelAndView.addObject("timeSpan", null);
    }

    if (report.getShow_graphtype_button()) {
        LinkedHashMap<String, String> graphTypes = new LinkedHashMap<String, String>();
        graphTypes.put("none", "none");
        for (PrefabGraph graphOption : prefabGraphs) {
            graphTypes.put(graphOption.getName(), graphOption.getName());
        }

        if (overrideGraphType == null || !graphTypes.containsKey(overrideGraphType)) {
            modelAndView.addObject("graphType", "none");
        } else {
            modelAndView.addObject("graphType", overrideGraphType);
        }
        modelAndView.addObject("graphTypes", graphTypes);
    } else {
        // Make sure it's null so the pulldown list isn't shown
        modelAndView.addObject("graphType", null);
    }

    modelAndView.addObject("showCustomizeButton", false);

    if (report.getGraphs_per_line() > 0) {
        modelAndView.addObject("graphsPerLine", report.getGraphs_per_line());
    } else {
        modelAndView.addObject("graphsPerLine", getDefaultGraphsPerLine());
    }

    return modelAndView;
}

From source file:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

@POST
@Path("/execute/{id}")
@Produces(APPLICATION_JSON)/*from   ww w.j av a2  s .  c om*/
@Consumes(APPLICATION_JSON)
public Response runReport(@Context HttpServletRequest request, @PathParam("id") Long id,
        @HeaderParam("scopeName") String scopeName, @HeaderParam("roleName") String roleName,
        DisplayFormat format) {

    String username = request.getRemoteUser();

    log.debug("{} is requesting runReport(...), with a ID={}", username, id);

    try {
        Map additionalProperties = (Map) format.getAdditionalProperties().get(ADDITIONAL_PROPERTIES);
        DateTime dateTime = DateUtils.UI_FORMATTER.parseDateTime((String) additionalProperties.get(TIMESTAMP));
        List<AreaIdentifierType> areaRestrictions = getRestrictionAreas(username, scopeName, roleName);
        Boolean isAdmin = request.isUserInRole(ReportFeatureEnum.MANAGE_ALL_REPORTS.toString());
        Boolean withActivity = request.isUserInRole(ActivityFeaturesEnum.ACTIVITY_ALLOWED.value());

        ExecutionResultDTO reportExecutionByReportId = reportExecutionService.getReportExecutionByReportId(id,
                username, scopeName, areaRestrictions, dateTime, isAdmin, withActivity, format);

        ObjectNode rootNode = mapToGeoJson(reportExecutionByReportId);
        return createSuccessResponse(rootNode);

    } catch (Exception e) {
        log.error("Report execution failed.", e);
        return createErrorResponse(e.getMessage());
    }
}

From source file:com.ikon.servlet.admin.OmrServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);/*w  ww  . ja  va  2  s.  c  o  m*/

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            String fileName = null;
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Set<String> properties = new HashSet<String>();
            Omr om = new Omr();

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("om_id")) {
                        om.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("om_name")) {
                        om.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("om_properties")) {
                        properties.add(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("om_active")) {
                        om.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    fileName = item.getName();
                }
            }

            om.setProperties(properties);

            if (action.equals("create") || action.equals("edit")) {
                // Store locally template file to be used later
                if (is != null && is.available() > 0) { // Case update only name
                    byte[] data = IOUtils.toByteArray(is);
                    File tmp = FileUtils.createTempFile();
                    FileOutputStream fos = new FileOutputStream(tmp);
                    IOUtils.write(data, fos);
                    IOUtils.closeQuietly(fos);

                    // Store template file
                    om.setTemplateFileName(FilenameUtils.getName(fileName));
                    om.setTemplateFileMime(MimeTypeConfig.mimeTypes.getContentType(fileName));
                    om.setTemplateFilContent(data);
                    IOUtils.closeQuietly(is);

                    // Create training files
                    Map<String, File> trainingMap = OMRHelper.trainingTemplate(tmp);
                    File ascFile = trainingMap.get(OMRHelper.ASC_FILE);
                    File configFile = trainingMap.get(OMRHelper.CONFIG_FILE);

                    // Store asc file
                    om.setAscFileName(om.getTemplateFileName() + ".asc");
                    om.setAscFileMime(MimeTypeConfig.MIME_TEXT);
                    is = new FileInputStream(ascFile);
                    om.setAscFileContent(IOUtils.toByteArray(is));
                    IOUtils.closeQuietly(is);

                    // Store config file
                    om.setConfigFileName(om.getTemplateFileName() + ".config");
                    om.setConfigFileMime(MimeTypeConfig.MIME_TEXT);
                    is = new FileInputStream(configFile);
                    om.setConfigFileContent(IOUtils.toByteArray(is));
                    IOUtils.closeQuietly(is);

                    // Delete temporal files
                    FileUtils.deleteQuietly(tmp);
                    FileUtils.deleteQuietly(ascFile);
                    FileUtils.deleteQuietly(configFile);
                }

                if (action.equals("create")) {
                    long id = OmrDAO.getInstance().create(om);

                    // Activity log
                    UserActivity.log(userId, "ADMIN_OMR_CREATE", Long.toString(id), null, om.toString());
                } else if (action.equals("edit")) {
                    OmrDAO.getInstance().updateTemplate(om);
                    om = OmrDAO.getInstance().findByPk(om.getId());

                    // Activity log
                    UserActivity.log(userId, "ADMIN_OMR_EDIT", Long.toString(om.getId()), null, om.toString());
                }

                list(userId, request, response);
            } else if (action.equals("delete")) {
                OmrDAO.getInstance().delete(om.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_DELETE", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("editAsc")) {
                Omr omr = OmrDAO.getInstance().findByPk(om.getId());
                omr.setAscFileContent(IOUtils.toByteArray(is));
                omr.setAscFileMime(MimeTypeConfig.MIME_TEXT);
                omr.setAscFileName(omr.getTemplateFileName() + ".asc");
                OmrDAO.getInstance().update(omr);
                omr = OmrDAO.getInstance().findByPk(om.getId());
                IOUtils.closeQuietly(is);

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_EDIT_ASC", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("editFields")) {
                Omr omr = OmrDAO.getInstance().findByPk(om.getId());
                omr.setFieldsFileContent(IOUtils.toByteArray(is));
                omr.setFieldsFileMime(MimeTypeConfig.MIME_TEXT);
                omr.setFieldsFileName(omr.getTemplateFileName() + ".fields");
                OmrDAO.getInstance().update(omr);
                omr = OmrDAO.getInstance().findByPk(om.getId());
                IOUtils.closeQuietly(is);

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_EDIT_FIELDS", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("check")) {
                File form = FileUtils.createTempFile();
                OutputStream formFile = new FileOutputStream(form);
                formFile.write(IOUtils.toByteArray(is));
                IOUtils.closeQuietly(formFile);
                formFile.close();
                Map<String, String> results = OMRHelper.process(form, om.getId());
                FileUtils.deleteQuietly(form);
                IOUtils.closeQuietly(is);
                UserActivity.log(userId, "ADMIN_OMR_CHECK_TEMPLATE", Long.toString(om.getId()), null, null);
                results(userId, request, response, action, results, om.getId());
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (OMRException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (InvalidFileStructureException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (InvalidImageIndexException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (UnsupportedTypeException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (MissingParameterException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (WrongParameterException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:com.openkm.servlet.admin.LogCatServlet.java

/**
 * Download log/*from www.  j ava  2 s .  c  om*/
 */
private void download(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("download({}, {})", request, response);
    String file = WebUtils.getString(request, "file");
    String filename = com.openkm.util.FileUtils.getFileName(file);
    File lf = new File(logFolder, file);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArchiveUtils.createZip(lf, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    WebUtils.sendFile(request, response, filename + ".zip", MimeTypeConfig.MIME_ZIP, false, bais);

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_LOGCAT_DOWNLOAD", null, null, null);

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