Example usage for javax.servlet.http HttpServletRequest getUserPrincipal

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

Introduction

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

Prototype

public java.security.Principal getUserPrincipal();

Source Link

Document

Returns a java.security.Principal object containing the name of the current authenticated user.

Usage

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * Make sure we have a Sakai session./*from w w w. j a  v  a  2 s  .co  m*/
 *
 * @param req
 *        The request object.
 * @param res
 *        The response object.
 * @return The Sakai Session object.
 */
protected Session assureSession(HttpServletRequest req, HttpServletResponse res) {
    Session s = null;
    String sessionId = null;
    boolean allowSetCookieEarly = true;
    Cookie c = null;

    // automatic, i.e. not from user activity, request?
    boolean auto = req.getParameter(PARAM_AUTO) != null;

    // session id provided in a request parameter?
    boolean reqsession = m_sessionParamAllow && req.getParameter(ATTR_SESSION) != null;

    String suffix = getCookieSuffix();

    // try finding a non-cookie session based on the remote user / principal
    // Note: use principal instead of remote user to avoid any possible confusion with the remote user set by single-signon
    // auth.
    // Principal is set by our Dav interface, which this is designed to cover. -ggolden

    Principal principal = req.getUserPrincipal();

    if (m_checkPrincipal && (principal != null) && (principal.getName() != null)) {
        // set our session id to the remote user id
        sessionId = SessionManager.makeSessionId(req, principal);

        // don't supply this cookie to the client
        allowSetCookieEarly = false;

        // find the session
        s = SessionManager.getSession(sessionId);

        // if not found, make a session for this user
        if (s == null) {
            s = SessionManager.startSession(sessionId);
        }

        // Make these sessions expire after 10 minutes
        s.setMaxInactiveInterval(10 * 60);
    }

    // if no principal, check request parameter and cookie
    if (sessionId == null || s == null) {
        if (m_sessionParamAllow) {
            sessionId = req.getParameter(ATTR_SESSION);
        }

        // find our session id from our cookie
        c = findCookie(req, cookieName, suffix);

        if (sessionId == null && c != null) {
            // get our session id
            sessionId = c.getValue();
        }

        if (sessionId != null) {
            // remove the server id suffix
            final int dotPosition = sessionId.indexOf(DOT);
            if (dotPosition > -1) {
                sessionId = sessionId.substring(0, dotPosition);
            }
            if (M_log.isDebugEnabled()) {
                M_log.debug("assureSession found sessionId in cookie: " + sessionId);
            }

            // find the session
            s = SessionManager.getSession(sessionId);
        }

        // ignore the session id provided in a request parameter
        // if the session is not authenticated
        if (reqsession && s != null && s.getUserId() == null) {
            s = null;
        }
    }

    // if found and not automatic, mark it as active
    if ((s != null) && (!auto)) {
        synchronized (s) {
            s.setActive();
        }
    }
    if (s == null && sessionId != null) {
        // check to see if this session has already been built.  If not, rebuild
        RebuildBreakdownService rebuildBreakdownService = (RebuildBreakdownService) ComponentManager
                .get(RebuildBreakdownService.class);
        if (rebuildBreakdownService != null) {
            s = SessionManager.startSession(sessionId);
            if (!rebuildBreakdownService.rebuildSession(s)) {
                s.invalidate();
                s = null;
            }
        }
    }

    // if missing, make one
    if (s == null) {
        s = SessionManager.startSession();

        // if we have a cookie, but didn't find the session and are creating a new one, mark this
        if (c != null) {
            ThreadLocalManager.set(SessionManager.CURRENT_INVALID_SESSION,
                    SessionManager.CURRENT_INVALID_SESSION);
        }
    }

    // put the session in the request attribute
    req.setAttribute(ATTR_SESSION, s);

    // set this as the current session
    SessionManager.setCurrentSession(s);

    // Now that we know the session exists, regardless of whether it's new or not, lets see if there
    // is a UsageSession.  If so, we want to check it's serverId
    UsageSession us = null;
    // FIXME synchronizing on a changing value is a bad practice plus it is possible for s to be null according to the visible code -AZ
    synchronized (s) {
        us = (UsageSession) s.getAttribute(UsageSessionService.USAGE_SESSION_KEY);
        if (us != null) {
            // check the server instance id
            ServerConfigurationService configService = org.sakaiproject.component.cover.ServerConfigurationService
                    .getInstance();
            String serverInstanceId = configService.getServerIdInstance();
            if ((serverInstanceId != null) && (!serverInstanceId.equals(us.getServer()))) {
                // Log that the UsageSession server value is changing
                M_log.info("UsageSession: Server change detected: Old Server=" + us.getServer()
                        + "    New Server=" + serverInstanceId);
                // set the new UsageSession server value
                us.setServer(serverInstanceId);
            }
        }
    }

    // if we had a cookie and we have no session, clear the cookie TODO: detect closed session in the request
    if ((s == null) && (c != null)) {
        // remove the cookie
        c = new Cookie(cookieName, "");
        c.setPath("/");
        c.setMaxAge(0);
        if (cookieDomain != null) {
            c.setDomain(cookieDomain);
        }
        addCookie(res, c);
    }

    // if we have a session and had no cookie,
    // or the cookie was to another session id, set the cookie
    if ((s != null) && allowSetCookieEarly) {
        // the cookie value we need to use
        sessionId = s.getId() + DOT + suffix;

        if ((c == null) || (!c.getValue().equals(sessionId))) {
            // set the cookie
            c = new Cookie(cookieName, sessionId);
            c.setPath("/");
            c.setMaxAge(-1);
            if (cookieDomain != null) {
                c.setDomain(cookieDomain);
            }
            if (req.isSecure() == true) {
                c.setSecure(true);
            }
            addCookie(res, c);
        }
    }

    return s;
}

From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Sets the http request data./*from   ww  w  .ja v  a 2s  .co  m*/
 * 
 * @param request the request
 * @param requestContainer the request container
 */
private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) {
    requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType());
    requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding());
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength()));
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType());
    requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath());
    requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated());
    requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol());
    requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId());
    requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI());
    requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort()));
    requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath());
    if (request.getUserPrincipal() != null)
        requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE,
            String.valueOf(request.isRequestedSessionIdFromCookie()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL,
            String.valueOf(request.isRequestedSessionIdFromURL()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID,
            String.valueOf(request.isRequestedSessionIdValid()));
    requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure()));
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        requestContainer.setAttribute(headerName, headerValue);
    } // while (headerNames.hasMoreElements())
    requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId());
    requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE");
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("userTree")
@DELETE// www  . j  a  v a2 s .  c om
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN })
public Response deleteUserTree(@Context HttpServletRequest request,
        @DefaultValue("0") @QueryParam("id") Integer userTreeId,
        @DefaultValue("") @QueryParam("userGoogleUserId") String userGoogleUserId,
        @DefaultValue("") @QueryParam("supervisorGoogleUserId") String supervisorGoogleUserId,
        @DefaultValue("") @QueryParam("allGoogleUserId") String allGoogleUserId,
        @DefaultValue("0") @QueryParam("allDealershipId") Integer dealershipId,
        @DefaultValue("false") @QueryParam("all") boolean all) {

    if (userTreeId > 0)
        return Response.ok(this.dao.deleteUserTreeById(userTreeId)).build();
    if (userGoogleUserId.length() > 0)
        return Response.ok(this.dao.deleteUserTreesForGoogleUserId(userGoogleUserId)).build();
    if (supervisorGoogleUserId.length() > 0)
        return Response.ok(this.dao.deleteUserTreesForSupervisorId(supervisorGoogleUserId)).build();
    if (allGoogleUserId.length() > 0)
        return Response
                .ok(this.dao.deleteUserTreesForGoogleSupervisorIdGoogleUserId(allGoogleUserId, allGoogleUserId))
                .build();
    if (dealershipId > 0)
        return Response.ok(this.dao.deleteUserTreesForDealershipId(dealershipId)).build();
    if (all) {
        String googleUserId = request.getUserPrincipal().getName();
        Users user = this.dao.getUserByGoogleId(googleUserId);
        if (user.getType() > 2)
            return Response.ok(this.dao.deleteAllUserTrees()).build();
        return Response.status(401).entity(new ErrorMessage("You are not authorized to delete all userTree"))
                .build();
    }
    return Response.status(400)
            .entity(new ErrorMessage("You must specify one of the options, do an options request to see them"))
            .build();
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("userTree")
@GET//w w  w .ja va  2 s.c om
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getUserTree(@Context HttpServletRequest request,
        @DefaultValue("") @QueryParam("googleUserId") String requestedGoogleUserId,
        @DefaultValue("") @QueryParam("googleSupervisorId") String googleSupervisorId,
        @DefaultValue("0") @QueryParam("sbUserId") Integer sbUserId,
        @DefaultValue("0") @QueryParam("dealershipId") Integer dealershipId,
        @DefaultValue("false") @QueryParam("all") boolean all) {
    GenericEntity<List<UserTree>> entity = null;
    if (requestedGoogleUserId.length() > 0)
        entity = new GenericEntity<List<UserTree>>(
                this.dao.getUserTreesForGoogleUserId(requestedGoogleUserId)) {
        };// works 2-6-14
    if (googleSupervisorId.length() > 0)
        entity = new GenericEntity<List<UserTree>>(
                this.dao.getUserTreesForGoogleSupervisorId(googleSupervisorId)) {
        };// works 2-6-14
    if (sbUserId != 0)
        entity = new GenericEntity<List<UserTree>>(
                this.dao.getUserTreesForGoogleUserId(this.dao.getUserById(sbUserId).getGoogleUserId())) {
        };
    if (dealershipId != 0)
        entity = new GenericEntity<List<UserTree>>(this.dao.getUserTreesForDealershipId(dealershipId)) {
        };// works 2-6-14
    if (all) {
        String googleUserId = request.getUserPrincipal().getName();
        Users user = this.dao.getUserByGoogleId(googleUserId);
        if (user.getType() > 2)
            entity = new GenericEntity<List<UserTree>>(this.dao.getUserTrees()) {
            };// works 2-6-14
        else
            return Response.status(401).entity(new ErrorMessage("You are not authorized to get all userTree"))
                    .build();
    }

    if (entity != null)
        return Response.ok().entity(entity).build();
    return Response.status(400)
            .entity(new ErrorMessage("You must specify one of the options, do an options request to see them"))
            .build();
}

From source file:uk.ac.ox.oucs.vle.StreamRequestFilter.java

@Override
protected Session assureSession(HttpServletRequest req, HttpServletResponse res) {
    Session s = null;//from  ww  w. ja  va2 s  .  co m
    String sessionId = null;
    SessionManager sessionManager = org.sakaiproject.tool.cover.SessionManager.getInstance();

    // compute the session cookie suffix, based on this configured server id
    String suffix = System.getProperty(SAKAI_SERVERID);
    if ((suffix == null) || (suffix.length() == 0)) {
        if (m_displayModJkWarning) {
            log.info(
                    "no sakai.serverId system property set - mod_jk load balancing will not function properly");

            // only display warning once
            // FYI this is not thread safe, but the side effects are
            // negligible and not worth the overhead of synchronizing
            // -lance
            m_displayModJkWarning = false;
        }

        suffix = "sakai";
    }

    // automatic, i.e. not from user activite, request?
    // we cant do this and stream boolean auto =
    // req.getParameter(PARAM_AUTO) != null;
    boolean auto = true;

    //sessionId = req.getParameter(ATTR_SESSION);

    // find our session id from our cookie
    Cookie c = findCookie(req, cookieName, suffix);

    if (sessionId == null && c != null) {
        // get our session id
        sessionId = c.getValue();
    }

    if (sessionId != null) {
        // remove the server id suffix
        final int dotPosition = sessionId.indexOf(DOT);
        if (dotPosition > -1) {
            sessionId = sessionId.substring(0, dotPosition);
        }
        if (log.isDebugEnabled()) {
            log.debug("assureSession found sessionId in cookie: " + sessionId);
        }

        // find the session
        s = sessionManager.getSession(sessionId);
    }

    // if no cookie, try finding a non-cookie session based on the remote
    // user / principal
    else {
        // Note: use principal instead of remote user to avoid any possible
        // confusion with the remote user set by single-signon
        // auth.
        // Principal is set by our Dav interface, which this is desined to
        // cover. -ggolden
        // String remoteUser = req.getRemoteUser();
        Principal principal = req.getUserPrincipal();

        if ((principal != null) && (principal.getName() != null)) {
            // set our session id to the remote user id
            sessionId = principal.getName();

            // find the session
            s = sessionManager.getSession(sessionId);

            // if not found, make a session for this user
            if (s == null) {
                s = sessionManager.startSession(sessionId);
            }
        }
    }

    // if found and not automatic, mark it as active
    if ((s != null) && (!auto)) {
        s.setActive();
    }

    // if missing, make one
    if (s == null) {
        s = sessionManager.startSession();

        // if we have a cookie, but didn't find the session and are creating
        // a new one, mark this
        if (c != null) {
            ThreadLocalManager.getInstance().set(SessionManager.CURRENT_INVALID_SESSION,
                    SessionManager.CURRENT_INVALID_SESSION);
        }
    }

    // put the session in the request attribute
    req.setAttribute(ATTR_SESSION, s);

    // set this as the current session
    sessionManager.setCurrentSession(s);

    // if we had a cookie and we have no session, clear the cookie 
    // detect closed session in the request
    if ((s == null) && (c != null)) {
        // remove the cookie
        c = new Cookie(cookieName, "");
        c.setPath("/");
        c.setMaxAge(0);
        res.addCookie(c);
    }

    // if we have a session and had no cookie,
    // or the cookie was to another session id, set the cookie
    if (s != null) {
        // the cookie value we need to use
        sessionId = s.getId() + DOT + suffix;

        if ((c == null) || (!c.getValue().equals(sessionId))) {
            // set the cookie
            c = new Cookie(cookieName, sessionId);
            c.setPath("/");
            c.setMaxAge(-1);
            res.addCookie(c);
        }
    }

    return s;
}

From source file:nl.b3p.kaartenbalie.struts.DepositAction.java

@Override
public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }/*  w ww . j  a  va  2  s.  com*/

    ActionErrors errors = dynaForm.validate(mapping, request);
    if (!errors.isEmpty()) {
        super.addMessages(request, errors);
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    /*
     * Alle gegevens voor de betaling.
     */
    Integer amount = (Integer) dynaForm.get("amount");
    Integer fraction = (Integer) dynaForm.get("fraction");
    String description = dynaForm.getString("description");
    String paymentMethod = dynaForm.getString("paymentMethod");
    BigDecimal billing = integersToBD(amount, fraction);
    Integer exchangeRate = Transaction.getExchangeRate();
    if (billing.doubleValue() <= 0) {
        log.error("Amount cannot be less then or equal to zero!");
        throw new Exception("Amount cannot be less then or equal to zero!");
    }

    /*
     * Start de transactie
     */
    StringBuffer tdesc = new StringBuffer();
    if (description != null) {
        tdesc.append(description);
    }
    if (paymentMethod != null) {
        tdesc.append("/");
        tdesc.append(paymentMethod);
    }
    if (exchangeRate != null) {
        tdesc.append("/1:");
        tdesc.append(exchangeRate);
    }
    if (tdesc.length() > 32) {
        tdesc = new StringBuffer(tdesc.substring(0, 32));
    }
    Organization organization = getOrganization(dynaForm, request);
    AccountManager am = AccountManager.getAccountManager(organization.getId());

    /* Er komt null terug als accounting uit staat in AccountManager.java */
    Transaction tpd = am.prepareTransaction(Transaction.DEPOSIT, tdesc.toString());

    /* Prijs, koers, conversie */
    if (tpd != null) {
        tpd.setBillingAmount(billing);
        BigDecimal creditAlt = billing.multiply(new BigDecimal(exchangeRate.intValue()));
        tpd.setCreditAlteration(creditAlt);
        tpd.setTxExchangeRate(exchangeRate);
        am.commitTransaction(tpd, (User) request.getUserPrincipal());
    }

    ActionRedirect redirect = new ActionRedirect(mapping.findForward(BACK));
    redirect.addParameter("selectedOrganization", organization.getId().toString());

    return redirect;
}

From source file:com.openmeap.admin.web.servlet.AdminServlet.java

@SuppressWarnings("unchecked")
@Override/*  w  w  w.j a va  2  s  . c  o m*/
public void service(HttpServletRequest request, HttpServletResponse response) {

    logger.trace("Entering service()");

    try {
        DocumentProcessor documentProcessor = null;

        logger.debug("Request uri: {}", request.getRequestURI());
        logger.debug("Request url: {}", request.getRequestURL());
        logger.debug("Query string: {}", request.getQueryString());
        if (logger.isDebugEnabled()) {
            logger.debug("Parameter map: {}", ParameterMapUtils.toString(request.getParameterMap()));
        }

        if (request.getParameter("logout") != null) {
            logger.trace("Executing logout");
            request.getSession().invalidate();
            response.sendRedirect(request.getContextPath() + "/interface/");
        }

        if (request.getParameter("refreshContext") != null && context instanceof AbstractApplicationContext) {
            logger.trace("Refreshing context");
            ((AbstractApplicationContext) context).refresh();
        }

        // support for clearing the persistence context
        if (request.getParameter("clearPersistenceContext") != null
                && context instanceof AbstractApplicationContext) {
            logger.trace("Clearing the persistence context");
            ModelServiceImpl ms = (ModelServiceImpl) ((AbstractApplicationContext) context)
                    .getBean("modelService");
            ms.clearPersistenceContext();
        }

        // default to the mainOptionPage, unless otherwise specified
        String pageBean = null;
        if (request.getParameter(FormConstants.PAGE_BEAN) != null)
            pageBean = request.getParameter(FormConstants.PAGE_BEAN);
        else
            pageBean = FormConstants.PAGE_BEAN_MAIN;
        logger.debug("Using page bean: {}", pageBean);
        documentProcessor = (DocumentProcessor) context.getBean(pageBean);

        ModelManager mgr = getModelManager();
        Map<Object, Object> map = new HashMap<Object, Object>();

        // TODO: I'm not really happy with this hacky work-around for the login form not being in actual request scope
        if (documentProcessor.getProcessesFormData()) {
            GlobalSettings settings = mgr.getGlobalSettings();
            map = ServletUtils.cloneParameterMap(settings.getMaxFileUploadSize(),
                    settings.getTemporaryStoragePath(), request);
            map.put("userPrincipalName", new String[] { request.getUserPrincipal().getName() });
            AuthorizerImpl authorizer = (AuthorizerImpl) context.getBean("authorizer");
            authorizer.setRequest(request);
        }

        response.setContentType(FormConstants.CONT_TYPE_HTML);

        Map<Object, Object> defaultTemplateVars = new HashMap<Object, Object>();
        defaultTemplateVars.put("request", new BeanModel(request, new DefaultObjectWrapper()));
        documentProcessor.setTemplateVariables(defaultTemplateVars);
        documentProcessor.handleProcessAndRender(map, response.getWriter());

        response.getWriter().flush();
        response.getWriter().close();
    } catch (IOException te) {
        throw new RuntimeException(te);
    }

    logger.trace("Leaving service()");
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

@RequestMapping("/graphTimeSeries")
public void graphTimeSeries(HttpServletRequest req, HttpServletResponse resp,
        @RequestParam("graphDataId") String dataId, @RequestParam(required = false) String graphTitle,
        @RequestParam(required = false) String xAxisLabel,
        // TODO put these all in a graph model object and let Spring deserialize from JSON
        @RequestParam(required = false) String yAxisLabel, @RequestParam(required = false) Double yAxisMin,
        @RequestParam(required = false) Double yAxisMax, @RequestParam(required = false) String dataDisplayKey,
        @RequestParam(required = false) String getImageMap, @RequestParam(required = false) String imageType,
        @RequestParam(required = false) String resolution,
        @RequestParam(required = false) String getHighResFile) throws GraphException, IOException {

    GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir);
    GraphController gc = getGraphController(dataId, hndl, req.getUserPrincipal().getName());

    GraphDataInterface data = hndl.getGraphData(dataId);

    if (graphTitle != null) {
        data.setGraphTitle(graphTitle);/*w  w w  .j  a va  2 s .c om*/
    }
    if (xAxisLabel != null) {
        data.setXAxisLabel(xAxisLabel);
    }
    if (yAxisLabel != null) {
        data.setYAxisLabel(yAxisLabel);
    }

    GraphObject graph = gc.createTimeSeriesGraph(data, yAxisMin, yAxisMax, dataDisplayKey);
    BufferedOutputStream out = new BufferedOutputStream(resp.getOutputStream());

    if (getImageMap != null && (getImageMap.equals("1") || getImageMap.equalsIgnoreCase("true"))) {
        resp.setContentType("text/plain;charset=utf-8");
        StringBuffer sb = new StringBuffer();
        sb.append(graph.getImageMap());
        out.write(sb.toString().getBytes());
    } else {
        resp.setContentType("image/png;charset=utf-8");
        String filename = graph.getImageFileName();
        filename = filename.replaceAll("\\s", "_");
        resp.setHeader("Content-disposition", "attachment; filename=" + filename);
        int imageResolution = 300;
        if (resolution != null) {
            try {
                imageResolution = Integer.parseInt(resolution);
                graph.writeChartAsHighResolutionPNG(out, data.getGraphWidth(), data.getGraphHeight(),
                        imageResolution);
            } catch (Exception e) {
                log.error("", e);
            }
        } else {
            graph.writeChartAsPNG(out, data.getGraphWidth(), data.getGraphHeight());
        }
    }
}

From source file:org.accada.epcis.repository.capture.CaptureOperationsServlet.java

/**
 * Implements the EPCIS capture operation. Takes HTTP POST request, extracts
 * the payload into an XML document, validates the document against the
 * EPCIS schema, and captures the EPCIS events given in the document. Errors
 * are caught and returned as simple plaintext messages via HTTP.
 * /*from ww w  .  java  2s . com*/
 * @param req
 *            The HttpServletRequest.
 * @param rsp
 *            The HttpServletResponse.
 * @throws IOException
 *             If an error occurred while validating the request or writing
 *             the response.
 */
public void doPost(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException {
    LOG.info("EPCIS Capture Interface invoked.");
    rsp.setContentType("text/plain");
    final PrintWriter out = rsp.getWriter();

    InputStream is = null;
    // check if we have a POST request with form parameters
    if ("application/x-www-form-urlencoded".equalsIgnoreCase(req.getContentType())) {
        // check if the 'event' or 'dbReset' form parameter are given
        String event = req.getParameter("event");
        String dbReset = req.getParameter("dbReset");
        if (event != null) {
            LOG.info("Found deprecated 'event=' parameter. Refusing to process request.");
            String msg = "Starting from version 0.2.2, the EPCIS repository does not accept the EPCISDocument in the HTTP POST form parameter 'event' anymore. Please provide the EPCISDocument as HTTP POST payload instead.";
            rsp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            out.println(msg);
        } else if (dbReset != null && dbReset.equalsIgnoreCase("true")) {
            LOG.debug("Found 'dbReset' parameter set to 'true'.");
            rsp.setContentType("text/plain");
            try {
                captureOperationsModule.doDbReset();
                String msg = "db reset successfull";
                LOG.info(msg);
                rsp.setStatus(HttpServletResponse.SC_OK);
                out.println(msg);
            } catch (SQLException e) {
                String msg = "An error involving the database occurred";
                LOG.error(msg, e);
                rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.println(msg);
            } catch (IOException e) {
                String msg = "An unexpected error occurred";
                LOG.error(msg, e);
                rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.println(msg);
            } catch (UnsupportedOperationException e) {
                String msg = "'dbReset' operation not allowed!";
                LOG.info(msg);
                rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                out.println(msg);
            }
        }
        out.flush();
        out.close();
        return;
    } else {
        is = req.getInputStream();
        try {
            captureOperationsModule.doCapture(is, req.getUserPrincipal());
            rsp.setStatus(HttpServletResponse.SC_OK);
            out.println("Capture request succeeded.");
        } catch (SAXException e) {
            String msg = "An error processing the XML document occurred";
            LOG.error(msg, e);
            rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println(msg);
        } catch (InvalidFormatException e) {
            String msg = "An error parsing the XML contents occurred";
            LOG.error(msg, e);
            rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println(msg);
        } catch (final Exception e) {
            String msg = "An unexpected error occurred";
            LOG.error(msg, e);
            rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.println(msg);
        }

        out.flush();
        out.close();
    }
}

From source file:com.yoshio3.modules.AzureADServerAuthModule.java

@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {
    HttpServletRequest httpRequest = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse httpResponse = (HttpServletResponse) messageInfo.getResponseMessage();

    Callback[] callbacks;/* www . j a va2 s . co m*/

    //Azure AD ??????????
    // if returning as a redirect after authenticating on Azure AD
    //???????????????
    //??????????????????????????
    // as there is no principal information, if authentication was successful add info to the principal
    Map<String, String> params = new HashMap<>();
    httpRequest.getParameterMap().keySet().stream().forEach(key -> {
        params.put(key, httpRequest.getParameterMap().get(key)[0]);
    });
    String currentUri = getCurrentUri(httpRequest);

    //?????????
    // if the authentication result is not included in the session
    if (!getSessionPrincipal(httpRequest)) {
        if (!isRedirectedRequestFromAuthServer(httpRequest, params)) {
            try {
                // Azure AD ? Redirect
                // redirect to Azure ID
                return redirectOpenIDServer(httpResponse, currentUri);
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, "Invalid redirect URL", ex);
                return AuthStatus.SEND_FAILURE;
            }
        } else {
            // Azure AD ????????
            // if it's a request returning from Azure AD
            messageInfo.getMap().put("javax.servlet.http.registerSession", Boolean.TRUE.toString());
            messageInfo.getMap().put("javax.servlet.http.authType", "AzureADServerAuthModule");
            return getAuthResultFromServerAndSetSession(clientSubject, httpRequest, params, currentUri);
        }
    } else {
        try {
            //???????
            // if the authentication result is included in the session
            AzureADUserPrincipal sessionPrincipal = (AzureADUserPrincipal) httpRequest.getUserPrincipal();
            AuthenticationResult authenticationResult = sessionPrincipal.getAuthenticationResult();
            if (authenticationResult.getExpiresOnDate().before(new Date())) {
                //????????
                // if the authentication date is old - get an access token from the refresh token
                AuthenticationResult authResult = getAccessTokenFromRefreshToken(
                        authenticationResult.getRefreshToken(), currentUri);
                setSessionPrincipal(httpRequest, new AzureADUserPrincipal(authResult));
            }
            CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject,
                    sessionPrincipal);
            String[] groups = getGroupList(sessionPrincipal);
            GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, groups);

            callbacks = new Callback[] { callerCallBack, groupPrincipalCallback };
            handler.handle(callbacks);
            return AuthStatus.SUCCESS;
        } catch (Throwable ex) {
            LOGGER.log(Level.SEVERE, "Invalid Session Info", ex);
            return AuthStatus.SEND_FAILURE;
        }
    }
}