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:alpha.portal.webapp.controller.UserFormController.java

/**
 * Show form.//from  ww w. j  a  v a 2 s .c  o m
 * 
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the model and view
 * @throws Exception
 *             the exception
 */
@ModelAttribute
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
protected ModelAndView showForm(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {

    final ModelAndView model = new ModelAndView();
    User user;

    // If not an administrator, make sure user is not trying to add or edit
    // another user
    if (!request.isUserInRole(Constants.ADMIN_ROLE) && !this.isFormSubmission(request)) {
        if (this.isAdd(request) || (request.getParameter("id") != null)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            this.log.warn("User '" + request.getRemoteUser() + "' is trying to edit user with id '"
                    + request.getParameter("id") + "'");

            throw new AccessDeniedException("You do not have permission to modify other users.");
        }
    }

    if (!this.isFormSubmission(request)) {
        final String userId = request.getParameter("id");

        // if user logged in with remember me, display a warning that they
        // can't change passwords
        this.log.debug("checking for remember me login...");

        final AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        final SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx.getAuthentication() != null) {
            final Authentication auth = ctx.getAuthentication();

            if (resolver.isRememberMe(auth)) {
                request.getSession().setAttribute("cookieLogin", "true");

                // add warning message
                this.saveMessage(request, this.getText("userProfile.cookieLogin", request.getLocale()));
            }
        }

        if ((userId == null) && !this.isAdd(request)) {
            user = this.getUserManager().getUserByUsername(request.getRemoteUser());
        } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) {
            user = this.getUserManager().getUser(userId);
        } else {
            user = new User();
            user.addRole(new Role(Constants.USER_ROLE));
        }

        user.setConfirmPassword(user.getPassword());

        UserExtension userExtension;
        final Long uId = user.getId();
        if ((uId != null) && this.userExtensionManager.exists(uId)) {
            userExtension = this.userExtensionManager.get(uId);
        } else {
            userExtension = new UserExtension(user);
        }

        model.addObject("userExtension", userExtension);
        model.addObject("contributorRoles", this.contributorRoleManager.getAll());

    } else {
        // populate user object from database, so all fields don't need to
        // be hidden fields in form
        user = this.getUserManager().getUser(request.getParameter("id"));
    }

    model.addObject("user", user);

    return model;
}

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

private boolean isScopeAllowed(VisibilityEnum visibility, HttpServletRequest request) {
    boolean isScopeAllowed = false;
    if (visibility.equals(VisibilityEnum.PRIVATE)
            || request.isUserInRole(ReportFeatureEnum.MANAGE_ALL_REPORTS.toString())) {
        isScopeAllowed = true;//from   w w  w  .j a  v  a2  s.c  om
    } else {
        switch (visibility) {
        case SCOPE:
            isScopeAllowed = request.isUserInRole(ReportFeatureEnum.SHARE_REPORT_SCOPE.toString());
            break;
        case PUBLIC:
            isScopeAllowed = request.isUserInRole(ReportFeatureEnum.SHARE_REPORT_PUBLIC.toString());
            break;
        }
    }
    return isScopeAllowed;
}

From source file:org.jboss.dashboard.ui.controller.requestChain.HttpSSOProcessor.java

public boolean processRequest() throws Exception {
    HttpServletRequest request = getHttpRequest();
    String login = request.getRemoteUser();
    UserStatus us = UserStatus.lookup();

    // Catch J2EE container login requests.
    if (!StringUtils.isBlank(login) && us.isAnonymous()) {

        // Login as root.
        if (us.getRootLogin().equals(login)) {
            us.initSessionAsRoot();/*from w  w  w.  j av  a 2 s  .c  om*/
        }
        // Login as normal user.
        else {
            Set<String> roleIds = new HashSet<String>();
            Set<Role> roles = getRolesManager().getAllRoles();
            for (Role role : roles) {
                String roleId = role.getName();
                if (request.isUserInRole(roleId))
                    roleIds.add(roleId);
            }
            us.initSession(login, roleIds);
        }
    }
    return true;
}

From source file:io.hops.hopsworks.api.admin.HDFSUIProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;/*  www .  j a va 2 s. c  om*/
    }
    if (!servletRequest.isUserInRole("HOPS_ADMIN")) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this service");
        return;
    }
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not 
    // sure it would truly be compatible
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);

    try {
        String[] targetHost_port = settings.getHDFSWebUIAddress().split(":");
        File keyStore = new File(baseHadoopClientsService.getSuperKeystorePath());
        File trustStore = new File(baseHadoopClientsService.getSuperTrustStorePath());
        // Assume that KeyStore password and Key password are the same
        Protocol httpsProto = new Protocol("https",
                new CustomSSLProtocolSocketFactory(keyStore,
                        baseHadoopClientsService.getSuperKeystorePassword(),
                        baseHadoopClientsService.getSuperKeystorePassword(), trustStore,
                        baseHadoopClientsService.getSuperTrustStorePassword()),
                Integer.parseInt(targetHost_port[1]));
        Protocol.registerProtocol("https", httpsProto);
        // Execute the request
        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);
        HostConfiguration config = new HostConfiguration();
        InetAddress localAddress = InetAddress.getLocalHost();
        config.setLocalAddress(localAddress);

        HttpMethod m = new GetMethod(proxyRequestUri);
        Enumeration<String> names = servletRequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String headerName = names.nextElement();
            String value = servletRequest.getHeader(headerName);
            if (PASS_THROUGH_HEADERS.contains(headerName)) {
                //hdfs does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null
                        || !servletRequest.getPathInfo().contains(".js"))) {
                    continue;
                } else {
                    m.setRequestHeader(headerName, value);
                }
            }
        }
        String user = servletRequest.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(config, m);

        // Process the response
        int statusCode = m.getStatusCode();

        // Pass the response code. This method with the "reason phrase" is 
        //deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase());

        copyResponseHeaders(m, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(m, servletResponse);

    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    }
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private Boolean isAuthorised(final HttpServletRequest httpRequest, final Token token) {
    String uriString = null;//from  w  w w .jav  a 2  s .  c  o  m
    final Boolean isRootContext = "".equals(httpRequest.getContextPath());
    if (isRootContext) {
        uriString = httpRequest.getRequestURI();
    } else {
        final int length = httpRequest.getRequestURI().length();
        uriString = httpRequest.getRequestURI().substring(length);
    }
    int index = 0;
    for (final String urlPattern : authenticationConfigurationService.get().getAuthorisationUriPatternList()) {
        final Pattern pattern = authenticationConfigurationService.get().getAuthorisationRegexPatternList()
                .get(index++);
        final Matcher matcher = pattern.matcher(uriString);
        final Boolean isMatchFound = matcher.matches();
        if (isMatchFound) {
            final HttpServletRequest authRequest = getAuthenticationWrapper(httpRequest, token);
            for (final String roleName : authenticationConfigurationService.get().getAuthorisationRoleMap()
                    .get(urlPattern)) {
                final Boolean isUserInRole = authRequest.isUserInRole(roleName);
                if (isUserInRole) {
                    return Boolean.TRUE;
                }
            }
            return Boolean.FALSE;
        }
    }
    return Boolean.TRUE;
}

From source file:be.fedict.hsm.admin.webapp.security.AuthenticationController.java

public void login(ComponentSystemEvent event) {
    LOG.debug("login");
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (facesContext.getResponseComplete()) {
        return;/*from  www.ja v  a2s  . c o m*/
    }
    if (null == this.authenticationCertificate) {
        /*
         * Caused by a direct navigation to post-login.jsf
         */
        redirect(facesContext, "/index.xhtml");
        return;
    }
    byte[] encodedCertificate;
    try {
        encodedCertificate = this.authenticationCertificate.getEncoded();
    } catch (CertificateEncodingException e) {
        LOG.error("certificate encoding error: " + e.getMessage(), e);
        return;
    }
    /*
     * The challenged certificate is the unique user identifier.
     */
    String username = DigestUtils.sha1Hex(encodedCertificate);
    String password = this.identity.getCardNumber();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
    try {
        httpServletRequest.login(username, password);
    } catch (ServletException e) {
        LOG.error("login error: " + e.getMessage(), e);
        accessDenied(facesContext);
        return;
    }
    Principal userPrincipal = httpServletRequest.getUserPrincipal();
    if (null == userPrincipal) {
        accessDenied(facesContext);
        return;
    }
    LOG.debug("user principal: " + userPrincipal.getName());
    LOG.debug("admin role: " + httpServletRequest.isUserInRole(AdministratorRoles.ADMINISTRATOR));
    if (false == httpServletRequest.isUserInRole(AdministratorRoles.ADMINISTRATOR)) {
        accessDenied(facesContext);
        return;
    }
    String targetViewId = SecurityPhaseListener.getTargetViewId(externalContext);
    redirect(facesContext, targetViewId);
}

From source file:org.rti.zcore.dar.struts.action.HomeAction.java

/**
 * Build the ZEPRS home page, incorporating the search interface/results
 * if it's a report-only user, send to reports
 * otherwise, send to permissions page./*from  ww  w  .  j  ava2s . c om*/
 *
 * @param mapping  The ActionMapping used to select this instance
 * @param form     The optional ActionForm bean for this request (if any)
 * @param request  The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return Action to forward to
 * @throws Exception if an input/output error or servlet exception occurs
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    Integer maxRows = 0;
    Integer offset = 0;
    Integer prevRows = 0;
    Integer nextRows = 0;
    Connection conn = null;
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);
        if (request.isUserInRole("VIEW_INDIVIDUAL_PATIENT_RECORDS")
                || request.isUserInRole("CREATE_NEW_PATIENTS_AND_SEARCH")) {
            String searchStringRequest = request.getParameter("search_string");
            String firstSurname = request.getParameter("first_surname"); // used in a-z search
            String labour = request.getParameter("labour"); // used in a-z search
            String searchType = "keyword";
            String searchString = "";
            if (searchStringRequest == null) {
                searchString = "";
            } else {
                searchString = searchStringRequest.trim().toLowerCase();
            }
            if (firstSurname != null && !firstSurname.equals("")) {
                searchType = "firstSurname";
                searchString = firstSurname;
                request.setAttribute("firstSurname", firstSurname);
            }
            request.setAttribute("searchString", searchString);
            String patientSiteId = SessionUtil.getInstance(session).getClientSettings().getSiteId().toString();
            request.setAttribute("patientSiteId", patientSiteId);

            String site = request.getParameter("site");
            request.setAttribute("site", site);
            if (site != null) {
                if (site.equals("")) {
                    site = patientSiteId;
                }
            }
            if (request.getParameter("maxRows") != null) {
                maxRows = Integer.decode(request.getParameter("maxRows"));
            } else if (request.getAttribute("maxRows") != null) {
                maxRows = Integer.decode(request.getAttribute("maxRows").toString());
            } else {
                maxRows = 20;
            }
            if (request.getParameter("offset") != null) {
                offset = Integer.decode(request.getParameter("offset"));
            } else if (request.getAttribute("offset") != null) {
                offset = Integer.decode(request.getAttribute("offset").toString());
            }
            if (request.getParameter("prevRows") != null) {
                prevRows = Integer.decode(request.getParameter("prevRows"));
                offset = prevRows;
            } else if (request.getAttribute("prevRows") != null) {
                prevRows = Integer.decode(request.getAttribute("prevRows").toString());
                offset = prevRows;
            }
            if (request.getParameter("nextRows") != null) {
                nextRows = Integer.decode(request.getParameter("nextRows"));
            } else if (request.getAttribute("nextRows") != null) {
                nextRows = Integer.decode(request.getAttribute("nextRows").toString());
            }
            if (site == null) {
                site = patientSiteId;
            }
            List results = null;
            results = PatientSearchDAO.getResults(conn, site, searchString, offset, maxRows, searchType, 0,
                    username);
            request.setAttribute("results", results);

            request.setAttribute("maxRows", maxRows);
            nextRows = offset + maxRows;
            if (results.size() < maxRows) {
                if (offset == 0) {
                    request.setAttribute("noNavigationWidget", "1");
                }
            } else {
                request.setAttribute("offset", nextRows);
            }

            if (offset - maxRows >= 0) {
                prevRows = offset - maxRows;
                request.setAttribute("prevRows", prevRows);
            }
            request.setAttribute("nextRows", nextRows);
            SessionUtil.getInstance(session).setSessionPatient(null);

            List sites = null;
            sites = DynaSiteObjects.getClinics();//
            request.setAttribute("sites", sites);

            if (SessionUtil.getInstance(request.getSession()).isClientConfigured()) {
                String sitename = SessionUtil.getInstance(session).getClientSettings().getSite().getName();
                request.setAttribute("sitename", sitename);
            } else {
                request.setAttribute("sitename", "Configure PC: ");
            }
            String fullname = null;
            try {
                fullname = SessionUtil.getInstance(session).getFullname();
            } catch (SessionUtil.AttributeNotFoundException e) {
                // ok
            }
            //List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn);
            //List<Task> stockAlertList = PatientRecordUtils.getStockAlerts();
            List<Task> stockAlertList = null;
            if (DynaSiteObjects.getStatusMap().get("stockAlertList") != null) {
                stockAlertList = (List<Task>) DynaSiteObjects.getStatusMap().get("stockAlertList");
            }
            request.setAttribute("activeProblems", stockAlertList);
            request.setAttribute("fullname", fullname);
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn = null;
            }
            return mapping.findForward("success");
        } else if (request.isUserInRole("VIEW_SELECTED_REPORTS_AND_VIEW_STATISTICAL_SUMMARIES")) {
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn = null;
            }
            return mapping.findForward("reports");
        } else if (request.isUserInRole("CREATE_MEDICAL_STAFF_IDS_AND_PASSWORDS_FOR_MEDICAL_STAFF")) {
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn = null;
            }

            // Create user accounts
            ActionForward fwd = mapping.findForward("admin/records/list");
            String path = fwd.getPath();
            path += "?formId=";
            path += "170";
            return new ActionForward(path);
        }
    } catch (ServletException e) {
        log.error(e);
        request.setAttribute("exception",
                "There is an error generating the Search Results for the Home page. Please stand by - the system may be undergoing maintenance.");
        return mapping.findForward("error");
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
            conn = null;
        }

    }

    return mapping.findForward("noPermissions");
}

From source file:com.pkrete.locationservice.admin.controller.mvc.LocationController.java

@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws Exception, ServletException, IOException {
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");
    if (user == null) {
        user = usersService.getUser(request.getRemoteUser());
        session.setAttribute("user", user);
    }/*  ww  w . j  av a  2  s  . c  om*/

    /**
     * If user is administrator and index parameter is present in the URL,
     * recreate search index.
     */
    if (request.isUserInRole(UserGroup.ADMIN.toString()) && request.getParameter("index") != null) {
        locationsService.recreateSearchIndex();
    }

    /* Id of the selected  library */
    String idLibrary = request.getParameter("select_library");
    /* Id of the selected collection */
    String idCollection = request.getParameter("select_collection");
    /* Id of the selected shelf */
    String idShelf = request.getParameter("select_shelf");

    if (idLibrary == null && idCollection != null) {
        int temp = this.locationsService.getLibraryId(idCollection);
        idLibrary = temp == 0 ? null : Integer.toString(temp);
    }
    if (idShelf != null) {
        if (idCollection == null) {
            int temp = this.locationsService.getCollectionId(idShelf);
            idCollection = temp == 0 ? null : Integer.toString(temp);
        }
        if (idLibrary == null) {
            int temp = this.locationsService.getLibraryId(idCollection);
            idLibrary = temp == 0 ? null : Integer.toString(temp);
        }
    }

    if (request.getParameter("btn_add_library") != null) {
        return new ModelAndView("redirect:addlibrary.htm");
    } else if (request.getParameter("btn_edit_library") != null && idLibrary != null) {
        return new ModelAndView("redirect:editlibrary.htm?select_library=" + idLibrary);
    } else if (request.getParameter("btn_delete_library") != null && idLibrary != null) {
        if (idLibrary != null) {
            Library temp = locationsService.getLibraryToBeDeleted(this.converterService.strToInt(idLibrary),
                    user.getOwner());
            if (!locationsService.delete(temp)) {
                throw new Exception("Deleting library failed.");
            }
            idLibrary = null;
            idCollection = null;
            idShelf = null;
        }
    } else if (request.getParameter("btn_add_collection") != null && idLibrary != null) {
        return new ModelAndView("redirect:addcollection.htm?select_library=" + idLibrary);
    } else if (request.getParameter("btn_edit_collection") != null && idCollection != null) {
        return new ModelAndView("redirect:editcollection.htm?select_library=" + idLibrary
                + "&select_collection=" + idCollection);
    } else if (request.getParameter("btn_delete_collection") != null && idCollection != null) {
        if (idCollection != null) {
            LibraryCollection temp = locationsService
                    .getCollectionToBeDeleted(this.converterService.strToInt(idCollection), user.getOwner());
            if (!locationsService.delete(temp)) {
                throw new Exception("Deleting collection failed.");
            }
            idCollection = null;
            idShelf = null;
        }
    } else if (request.getParameter("btn_add_shelf") != null && idCollection != null) {
        return new ModelAndView(
                "redirect:addshelf.htm?select_library=" + idLibrary + "&select_collection=" + idCollection);
    } else if (request.getParameter("btn_edit_shelf") != null && idShelf != null) {
        return new ModelAndView("redirect:editshelf.htm?select_library=" + idLibrary + "&select_collection="
                + idCollection + "&select_shelf=" + idShelf);
    } else if (request.getParameter("btn_delete_shelf") != null && idShelf != null) {
        if (idCollection != null) {
            Shelf temp = locationsService.getShelfToBeDeleted(this.converterService.strToInt(idShelf),
                    user.getOwner());
            if (!locationsService.delete(temp)) {
                throw new Exception("Deleting shelf failed.");
            }
            idShelf = null;
        }
    }

    /* Model that is returned together with the view */
    Map<String, Object> model = new HashMap<String, Object>();

    /* Load list of all the libraries that the user is allowed to see from DB */
    List<SimpleLocation> libraries = locationsService.getlLibraries(user.getOwner());
    List<SimpleLocation> collections = new ArrayList<SimpleLocation>();
    List<SimpleLocation> shelves = new ArrayList<SimpleLocation>();

    if (!libraries.isEmpty()) {
        /* If no library is selected, select the first library on the list */
        if (idLibrary == null) {
            idLibrary = Integer.toString(libraries.get(0).getLocationId());
        }

        /* Load the collections of the selected library */
        collections = locationsService.getCollectionsByLibraryId(this.converterService.strToInt(idLibrary),
                user.getOwner());

        if (!collections.isEmpty()) {
            /* If no collection is selected or selected library has changed, */
            /* select the first collection on the list */
            if (idCollection == null || request.getParameter("btn_list_library") != null) {
                idCollection = Integer.toString(collections.get(0).getLocationId());
            }

            /* Load the shelves of the selected collection */
            shelves = locationsService.getShelvesByCollectionId(this.converterService.strToInt(idCollection),
                    user.getOwner());
        }
    }
    model.put("owner", UsersUtil.getUser(request, usersService).getOwner().getCode());
    model.put("libraries", libraries);
    model.put("collections", collections);
    model.put("shelves", shelves);
    model.put("libraryId", idLibrary);
    model.put("collectionId", idCollection);
    model.put("shelfId", idShelf);

    if (request.isUserInRole(UserGroup.ADMIN.toString())) {
        model.put("isAdmin", "");
    }
    return new ModelAndView("location", "model", model);
}

From source file:co.bluepass.web.rest.ClubResource.java

/**
 * Update response entity.//from   w ww .  j  a v  a2s  . co  m
 *
 * @param dto       the dto
 * @param request   the request
 * @param principal the principal
 * @return the response entity
 * @throws URISyntaxException the uri syntax exception
 */
@RequestMapping(value = "/clubs", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> update(@Valid @RequestBody ClubDTO dto, HttpServletRequest request,
        Principal principal) throws URISyntaxException {
    log.debug("REST request to update Club : {}", dto);

    if (dto.getId() == null) {
        return ResponseEntity.badRequest().header("Failure", " ?? ? .")
                .build();
    }

    Club club = clubRepository.findOne(dto.getId());

    if (!request.isUserInRole("ROLE_ADMIN")
            && !club.getCreator().getEmail().equals(SecurityUtils.getCurrentLogin())) {
        return ResponseEntity.badRequest().header("Failure", "??  ? .")
                .build();
    }

    CommonCode category = dto.getCategory();

    club.update(dto.getName(), dto.getLicenseNumber(), dto.getPhoneNumber(), dto.getZipcode(),
            dto.getAddress1(), dto.getAddress2(), dto.getOldAddress(), dto.getAddressSimple(),
            dto.getDescription(), dto.getHomepage(), dto.getOnlyFemale(), category, dto.getManagerMobile(),
            dto.getNotificationType(), dto.getReservationClose());

    clubRepository.save(club);

    List<CommonCode> featureCodes = null;
    if (dto.getFeatures() != null) {
        List<Feature> oldFeatures = featureRepository.findByClub(club);
        featureRepository.delete(oldFeatures);
        //featureCodes = commonCodeRepository.findByNameIn(dto.getFeatures());
        featureCodes = commonCodeRepository.findAll(Arrays.asList(dto.getFeatures()));
        if (featureCodes != null && !featureCodes.isEmpty()) {
            List<Feature> features = new ArrayList<Feature>();
            for (CommonCode featureCode : featureCodes) {
                features.add(new Feature(club, featureCode));
            }
            featureRepository.save(features);
        }
    }

    try {
        if (StringUtils.isNotEmpty(club.getOldAddress())) {
            addressIndexRepository.save(new AddressIndex(club.getOldAddress()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return ResponseEntity.ok().build();
}

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

@GET
@Path("/{id}")
@Produces(APPLICATION_JSON)/*  w ww  .  jav a2  s  . c om*/
public Response getReport(@Context HttpServletRequest request, @PathParam("id") Long id,
        @HeaderParam("scopeName") String scopeName, @HeaderParam("roleName") String roleName) {

    String username = request.getRemoteUser();
    ReportDTO report;

    try {
        boolean isAdmin = request.isUserInRole(ReportFeatureEnum.MANAGE_ALL_REPORTS.toString());
        Set<String> features = usmService.getUserFeatures(username, getApplicationName(request), roleName,
                scopeName);
        List<String> permittedServiceLayers = new ArrayList<>(ServiceLayerUtils
                .getUserPermittedLayersNames(usmService, request.getRemoteUser(), roleName, scopeName));
        report = reportService.findById(features, id, username, scopeName, isAdmin, permittedServiceLayers);
    } catch (Exception e) {
        log.error("Failed to get report.", e);
        return createErrorResponse();
    }

    Response restResponse;

    if (report != null) {
        restResponse = createSuccessResponse(report);
    } else {
        restResponse = createScNotFoundErrorResponse(ErrorCodes.ENTRY_NOT_FOUND);
    }

    return restResponse;
}