Example usage for javax.servlet.http HttpServletRequest isUserInRole

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

Introduction

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

Prototype

public boolean isUserInRole(String role);

Source Link

Document

Returns a boolean indicating whether the authenticated user is included in the specified logical "role".

Usage

From source file:org.apache.struts.taglib.tiles.InsertTag.java

/**
 * Process nested ≶put> tag.
 * Method calls by nested ≶put> tags.
 * Nested list is added to current list.
 * If role is defined, it is checked immediately.
 *//*from  www.ja va 2 s .  co m*/
public void processNestedTag(PutTag nestedTag) throws JspException {
    // Check role
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    String role = nestedTag.getRole();
    if (role != null && !request.isUserInRole(role)) {
        // not allowed : skip attribute
        return;
    }

    putAttribute(nestedTag.getName(), nestedTag.getRealValue());
}

From source file:org.apache.struts.taglib.tiles.InsertTag.java

/**
 * Method calls by nested ≶putList> tags.
 * A new list is added to current insert object.
 *///  w  w w .jav a 2 s  . c o  m
public void putAttribute(PutListTag nestedTag) throws JspException {
    // Check role
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    String role = nestedTag.getRole();
    if (role != null && !request.isUserInRole(role)) {
        // not allowed : skip attribute
        return;
    }

    putAttribute(nestedTag.getName(), nestedTag.getList());
}

From source file:org.apache.struts.taglib.tiles.InsertTag.java

/**
 * Process nested ≶putList> tag.
 * Method calls by nested ≶putList> tags.
 * Nested list is added to sub-component attributes
 * If role is defined, it is checked immediately.
 *//*from  ww  w .  ja  v a2  s  .co m*/
public void processNestedTag(PutListTag nestedTag) throws JspException {
    // Check role
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    String role = nestedTag.getRole();
    if (role != null && !request.isUserInRole(role)) {
        // not allowed : skip attribute
        return;
    }

    // Check if a name is defined
    if (nestedTag.getName() == null) {
        throw new JspException(
                "Error - PutList : attribute name is not defined. It is mandatory as the list is added as attribute of 'insert'.");
    }

    // now add attribute to enclosing parent (i.e. : this object).
    putAttribute(nestedTag.getName(), nestedTag.getList());
}

From source file:org.apache.cxf.fediz.example.FederationServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head><title>WS Federation Tomcat Examples</title></head>");
    out.println("<body>");
    out.println("<h1>Hello World</h1>");
    out.println("Hello world<br>");
    out.println("Request url: " + request.getRequestURL().toString() + "<p>");

    out.println("<br><b>User</b><p>");
    Principal p = request.getUserPrincipal();
    if (p != null) {
        out.println("Principal: " + p.getName() + "<p>");
    }//w ww. j av a  2s .c om

    out.println("<br><b>Roles</b><p>");
    List<String> roleListToCheck = Arrays.asList("Admin", "Manager", "User", "Authenticated");
    for (String item : roleListToCheck) {
        out.println("Has role '" + item + "': " + ((request.isUserInRole(item)) ? "<b>yes</b>" : "no") + "<p>");
    }

    if (p instanceof FederationPrincipal) {
        FederationPrincipal fp = (FederationPrincipal) p;

        out.println("<br><b>Claims</b><p>");
        ClaimCollection claims = fp.getClaims();
        for (Claim c : claims) {
            out.println(c.getClaimType().toString() + ": " + c.getValue() + "<p>");
        }
    } else {
        out.println("Principal is not instance of FederationPrincipalImpl");
    }

    Greeter service = (Greeter) ApplicationContextProvider.getContext().getBean("HelloServiceClient");
    String reply = service.greetMe();

    out.println("<br><b>Greeter Service Response: " + reply + "</b><p>");

    out.println("</body>");
}

From source file:org.apache.cxf.fediz.example.FederationServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head><title>WS Federation Tomcat Examples</title></head>");
    out.println("<body>");
    out.println("<h1>Hello World</h1>");
    out.println("Hello world<br>");
    out.println("Request url: " + request.getRequestURL().toString() + "<p>");

    out.println("<br><b>User</b><p>");
    Principal p = request.getUserPrincipal();
    if (p != null) {
        out.println("Principal: " + p.getName() + "<p>");
    }/*from w w  w .  j a  va  2 s.  c  o m*/

    out.println("<br><b>Roles</b><p>");
    List<String> roleListToCheck = Arrays.asList("Admin", "Manager", "User", "Authenticated");
    for (String item : roleListToCheck) {
        out.println("Has role '" + item + "': " + ((request.isUserInRole(item)) ? "<b>yes</b>" : "no") + "<p>");
    }

    if (p instanceof FederationPrincipal) {
        FederationPrincipal fp = (FederationPrincipal) p;

        out.println("<br><b>Claims</b><p>");
        ClaimCollection claims = fp.getClaims();
        for (Claim c : claims) {
            out.println(c.getClaimType().toString() + ": " + c.getValue() + "<p>");
        }
    } else {
        out.println("Principal is not instance of FederationPrincipal");
    }

    Element el = SecurityTokenThreadLocal.getToken();
    if (el != null) {
        out.println("<p>Bootstrap token...");
        String token = null;
        try {
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            StringWriter buffer = new StringWriter();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(el), new StreamResult(buffer));
            token = buffer.toString();
            out.println("<p>" + StringEscapeUtils.escapeXml(token));
        } catch (Exception ex) {
            out.println("<p>Failed to transform cached element to string: " + ex.toString());
        }
    } else {
        out.println("<p>Bootstrap token not cached in thread local storage");
    }

    out.println("</body>");
}

From source file:net.yacy.http.servlets.SolrSelectServlet.java

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

    HttpServletRequest hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = (HttpServletResponse) response;
    SolrQueryRequest req = null;//w w w .  j a  v a 2  s .co  m

    final Method reqMethod = Method.getMethod(hrequest.getMethod());

    Writer out = null;
    try {
        // prepare request to solr
        MultiMapSolrParams mmsp = SolrRequestParsers.parseQueryString(hrequest.getQueryString());

        Switchboard sb = Switchboard.getSwitchboard();
        // TODO: isUserInRole needs a login to jetty container (not done automatically on admin from localhost)
        boolean authenticated = hrequest.isUserInRole(UserDB.AccessRight.ADMIN_RIGHT.toString());

        // count remote searches if this was part of a p2p search
        if (mmsp.getMap().containsKey("partitions")) {
            final int partitions = mmsp.getInt("partitions", 30);
            sb.searchQueriesGlobal += 1.0f / partitions; // increase query counter
        }

        // get the ranking profile id
        int profileNr = mmsp.getInt("profileNr", 0);

        // rename post fields according to result style
        String querystring = "";
        if (!mmsp.getMap().containsKey(CommonParams.Q) && mmsp.getMap().containsKey(CommonParams.QUERY)) {
            querystring = mmsp.get(CommonParams.QUERY, "");
            mmsp.getMap().remove(CommonParams.QUERY);
            QueryModifier modifier = new QueryModifier(0);
            querystring = modifier.parse(querystring);
            modifier.apply(mmsp);
            QueryGoal qg = new QueryGoal(querystring);
            StringBuilder solrQ = qg.collectionTextQuery();
            mmsp.getMap().put(CommonParams.Q, new String[] { solrQ.toString() }); // sru patch

            // experimental p2p enrichment if flag to do so is set
            /*
            final String p2pQuery = querystring;
            new Thread() {
            @Override
            public void run() {
                FederateSearchManager.getManager().query(p2pQuery);
            }
            }.start();
            */
        }
        String q = mmsp.get(CommonParams.Q, "");
        if (querystring.length() == 0)
            querystring = q;
        if (!mmsp.getMap().containsKey(CommonParams.START)) {
            int startRecord = mmsp.getFieldInt("startRecord", null, 0);
            mmsp.getMap().remove("startRecord");
            mmsp.getMap().put(CommonParams.START, new String[] { Integer.toString(startRecord) }); // sru patch
        }
        if (!mmsp.getMap().containsKey(CommonParams.ROWS)) {
            int maximumRecords = mmsp.getFieldInt("maximumRecords", null, 10);
            mmsp.getMap().remove("maximumRecords");
            mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer.toString(maximumRecords) }); // sru patch
        }
        mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer
                .toString(Math.min(mmsp.getInt(CommonParams.ROWS, 10), (authenticated) ? 100000000 : 100)) });

        // set ranking according to profile number if ranking attributes are not given in the request
        Ranking ranking = sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr);
        if (!mmsp.getMap().containsKey(CommonParams.SORT) && !mmsp.getMap().containsKey(DisMaxParams.BQ)
                && !mmsp.getMap().containsKey(DisMaxParams.BF) && !mmsp.getMap().containsKey("boost")) {
            if (!mmsp.getMap().containsKey("defType"))
                mmsp.getMap().put("defType", new String[] { "edismax" });
            String fq = ranking.getFilterQuery();
            String bq = ranking.getBoostQuery();
            String bf = ranking.getBoostFunction();
            if (fq.length() > 0)
                mmsp.getMap().put(CommonParams.FQ, new String[] { fq });
            if (bq.length() > 0)
                mmsp.getMap().put(DisMaxParams.BQ, StringUtils.split(bq, "\t\n\r\f")); // bq split into multiple query params, allowing space in single query
            if (bf.length() > 0)
                mmsp.getMap().put("boost", new String[] { bf }); // a boost function extension, see http://wiki.apache.org/solr/ExtendedDisMax#bf_.28Boost_Function.2C_additive.29
        }

        // get a response writer for the result
        String wt = mmsp.get(CommonParams.WT, "xml"); // maybe use /solr/select?q=*:*&start=0&rows=10&wt=exml
        QueryResponseWriter responseWriter = RESPONSE_WRITER.get(wt);
        if (responseWriter == null)
            throw new ServletException("no response writer");
        if (responseWriter instanceof OpensearchResponseWriter) {
            // set the title every time, it is possible that it has changed
            final String promoteSearchPageGreeting = (sb
                    .getConfigBool(SwitchboardConstants.GREETING_NETWORK_NAME, false))
                            ? sb.getConfig("network.unit.description", "")
                            : sb.getConfig(SwitchboardConstants.GREETING, "");
            ((OpensearchResponseWriter) responseWriter).setTitle(promoteSearchPageGreeting);
        }

        // if this is a call to YaCys special search formats, enhance the query with field assignments
        if ((responseWriter instanceof YJsonResponseWriter
                || responseWriter instanceof OpensearchResponseWriter)
                && "true".equals(mmsp.get("hl", "true"))) {
            // add options for snippet generation
            if (!mmsp.getMap().containsKey("hl.q"))
                mmsp.getMap().put("hl.q", new String[] { q });
            if (!mmsp.getMap().containsKey("hl.fl"))
                mmsp.getMap().put("hl.fl",
                        new String[] { CollectionSchema.description_txt.getSolrFieldName() + ","
                                + CollectionSchema.h4_txt.getSolrFieldName() + ","
                                + CollectionSchema.h3_txt.getSolrFieldName() + ","
                                + CollectionSchema.h2_txt.getSolrFieldName() + ","
                                + CollectionSchema.h1_txt.getSolrFieldName() + ","
                                + CollectionSchema.text_t.getSolrFieldName() });
            if (!mmsp.getMap().containsKey("hl.alternateField"))
                mmsp.getMap().put("hl.alternateField",
                        new String[] { CollectionSchema.description_txt.getSolrFieldName() });
            if (!mmsp.getMap().containsKey("hl.simple.pre"))
                mmsp.getMap().put("hl.simple.pre", new String[] { "<b>" });
            if (!mmsp.getMap().containsKey("hl.simple.post"))
                mmsp.getMap().put("hl.simple.post", new String[] { "</b>" });
            if (!mmsp.getMap().containsKey("hl.fragsize"))
                mmsp.getMap().put("hl.fragsize",
                        new String[] { Integer.toString(SearchEvent.SNIPPET_MAX_LENGTH) });
            if (!mmsp.getMap().containsKey("fl"))
                mmsp.getMap().put("fl",
                        new String[] { CollectionSchema.sku.getSolrFieldName() + "," + CollectionSchema.title
                                + "," + CollectionSchema.description_txt.getSolrFieldName() + ","
                                + CollectionSchema.id.getSolrFieldName() + ","
                                + CollectionSchema.url_paths_sxt.getSolrFieldName() + ","
                                + CollectionSchema.last_modified.getSolrFieldName() + ","
                                + CollectionSchema.size_i.getSolrFieldName() + ","
                                + CollectionSchema.url_protocol_s.getSolrFieldName() + ","
                                + CollectionSchema.url_file_ext_s.getSolrFieldName() });
        }

        // get the embedded connector
        String requestURI = hrequest.getRequestURI();
        boolean defaultConnector = (requestURI.startsWith("/solr/" + WebgraphSchema.CORE_NAME)) ? false
                : requestURI.startsWith("/solr/" + CollectionSchema.CORE_NAME)
                        || mmsp.get("core", CollectionSchema.CORE_NAME).equals(CollectionSchema.CORE_NAME);
        mmsp.getMap().remove("core");
        SolrConnector connector = defaultConnector ? sb.index.fulltext().getDefaultEmbeddedConnector()
                : sb.index.fulltext().getEmbeddedConnector(WebgraphSchema.CORE_NAME);
        if (connector == null) {
            connector = defaultConnector ? sb.index.fulltext().getDefaultConnector()
                    : sb.index.fulltext().getConnectorForRead(WebgraphSchema.CORE_NAME);
        }
        if (connector == null)
            throw new ServletException("no core");

        // add default queryfield parameter according to local ranking config (or defaultfield)
        if (ranking != null) { // ranking normally never null
            final String qf = ranking.getQueryFields();
            if (qf.length() > 4) { // make sure qf has content (else use df)
                addParam(DisMaxParams.QF, qf, mmsp.getMap()); // add QF that we set to be best suited for our index
                // TODO: if every peer applies a decent QF itself, this can be reverted to getMap().put()
            } else {
                mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() });
            }
        } else {
            mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() });
        }

        // do the solr request, generate facets if we use a special YaCy format
        final SolrQueryResponse rsp;
        if (connector instanceof EmbeddedSolrConnector) {
            req = ((EmbeddedSolrConnector) connector).request(mmsp);
            rsp = ((EmbeddedSolrConnector) connector).query(req);

            // prepare response
            hresponse.setHeader("Cache-Control", "no-cache, no-store");
            HttpCacheHeaderUtil.checkHttpCachingVeto(rsp, hresponse, reqMethod);

            // check error
            if (rsp.getException() != null) {
                AccessTracker.addToDump(querystring, "0", new Date());
                sendError(hresponse, rsp.getException());
                return;
            }

            NamedList<?> values = rsp.getValues();
            DocList r = ((ResultContext) values.get("response")).docs;
            int numFound = r.matches();
            AccessTracker.addToDump(querystring, Integer.toString(numFound), new Date());

            // write response header
            final String contentType = responseWriter.getContentType(req, rsp);
            if (null != contentType)
                response.setContentType(contentType);

            if (Method.HEAD == reqMethod) {
                return;
            }

            // write response body
            if (responseWriter instanceof BinaryResponseWriter) {
                ((BinaryResponseWriter) responseWriter).write(response.getOutputStream(), req, rsp);
            } else {
                out = new FastWriter(
                        new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
                responseWriter.write(out, req, rsp);
                out.flush();
            }
        } else {
            // write a 'faked' response using a call to the backend
            SolrDocumentList sdl = connector.getDocumentListByQuery(mmsp.getMap().get(CommonParams.Q)[0],
                    mmsp.getMap().get(CommonParams.SORT) == null ? null
                            : mmsp.getMap().get(CommonParams.SORT)[0],
                    Integer.parseInt(mmsp.getMap().get(CommonParams.START)[0]),
                    Integer.parseInt(mmsp.getMap().get(CommonParams.ROWS)[0]),
                    mmsp.getMap().get(CommonParams.FL));
            OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
            EnhancedXMLResponseWriter.write(osw, req, sdl);
            osw.close();
        }
    } catch (final Throwable ex) {
        sendError(hresponse, ex);
    } finally {
        if (req != null) {
            req.close();
        }
        SolrRequestInfo.clearRequestInfo();
        if (out != null)
            try {
                out.close();
            } catch (final IOException e1) {
            }
    }
}

From source file:alpha.portal.webapp.controller.UserFormController.java

/**
 * On user role save./*  ww w.j  a  v a 2  s  .  co m*/
 * 
 * @param jspUserExtension
 *            the jsp user extension
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the string
 */
@RequestMapping(method = RequestMethod.POST, params = { "saveRoles" })
public String onUserRoleSave(final UserExtension jspUserExtension, final HttpServletRequest request,
        final HttpServletResponse response) {
    // parameters when editing users as an admin
    final String id = request.getParameter("id");
    final String from = request.getParameter("from");
    Long idL = null;
    if (id != null) {
        try {
            idL = Long.parseLong(id);
        } catch (final NumberFormatException e) {
            return "redirect:/caseMenu";
        }
    }
    // get current user for checks
    final User user = this.getUserManager().getUserByUsername(request.getRemoteUser());
    // check whether id exists and user is allowed to edit this one
    if (((id != null) && !this.getUserManager().exists(idL))
            || ((id != null) && (idL != user.getId()) && !request.isUserInRole(Constants.ADMIN_ROLE)))
        return "redirect:/caseMenu";
    // reload UserExtension from database or create a new one
    UserExtension userExtension;
    // if user is editing himself
    if (id == null) {
        if (this.userExtensionManager.exists(user.getId())) {
            userExtension = this.userExtensionManager.get(user.getId());
        } else {
            userExtension = new UserExtension(this.getUserManager().get(user.getId()));
        }
    } else {// if admin is editing other users
        if (this.userExtensionManager.exists(idL)) {
            userExtension = this.userExtensionManager.get(idL);
        } else {
            userExtension = new UserExtension(this.getUserManager().get(idL));
        }
    }
    // parse submitted roleIds to ContributorRole
    final Set<ContributorRole> roles = new HashSet<ContributorRole>();
    if ((jspUserExtension != null) && (jspUserExtension.getRoles() != null)) {
        for (final ContributorRole jspRole : jspUserExtension.getRoles()) {
            Long roleId = null;
            try {
                // WTF, Spring puts the submitted roleIds into name!
                roleId = Long.parseLong(jspRole.getName());
            } catch (final NumberFormatException e) {
                this.saveError(request, "userextension.invalidRole");
                continue;
            }
            if (!this.contributorRoleManager.exists(roleId)) {
                this.saveError(request, "userextension.invalidRole");
                continue;
            } else {
                roles.add(this.contributorRoleManager.get(roleId));
            }
        }
    }
    userExtension.setRoles(roles);
    userExtension = this.userExtensionManager.save(userExtension);

    return "redirect:/userform?id=" + userExtension.getUserId() + (from != null ? "&from=" + from : "");

}

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

@PUT
@Path("/{id}")
@Produces(APPLICATION_JSON)//from  www .  j a v a 2 s .com
@Consumes(APPLICATION_JSON)
public Response updateReport(@Context HttpServletRequest request, ReportDTO report,
        @DefaultValue("default") @QueryParam(value = "projection") String projection,
        @HeaderParam("scopeName") String scopeName, @HeaderParam("roleName") String roleName,
        @PathParam("id") Long id) {

    String username = request.getRemoteUser();
    log.info("{} is requesting updateReport(...), with a ID={}", username, report.getId());
    Response result;

    try {
        Set<String> features = usmService.getUserFeatures(username, getApplicationName(request), roleName,
                scopeName);
        boolean isAdmin = request.isUserInRole(ReportFeatureEnum.MANAGE_ALL_REPORTS.toString());
        List<String> permittedServiceLayers = new ArrayList<>(ServiceLayerUtils
                .getUserPermittedLayersNames(usmService, request.getRemoteUser(), roleName, scopeName));
        ReportDTO originalReport = reportService.findById(features, report.getId(), username, scopeName,
                isAdmin, permittedServiceLayers); // we need the original report because of the 'owner/createdBy' attribute,
        // which is not contained in the JSO
        ReportFeatureEnum requiredFeature = AuthorizationCheckUtil
                .getRequiredFeatureToEditReport(originalReport, username);

        if (requiredFeature != null && !request.isUserInRole(requiredFeature.toString())) {
            result = createErrorResponse(ErrorCodes.NOT_AUTHORIZED);
        } else {
            ReportDTO update = reportService.update(report, username, originalReport.getWithMap(),
                    originalReport.getMapConfiguration());
            switch (Projection.valueOf(projection.toUpperCase())) {

            case DETAILED:
                result = createSuccessResponse(update);
                break;

            default:
                result = createSuccessResponse(update.getId());
            }
        }

    } catch (Exception exc) {
        log.error("Update failed.", exc);
        result = createErrorResponse(ErrorCodes.UPDATE_FAILED);
    }
    return result;
}

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

@POST
@Path("/execute/{id}")
@Produces(APPLICATION_JSON)//from  w  ww  .j  a v  a 2s  . c  o  m
@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());
    }
}