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:at.fh.swenga.firefighters.controller.FireFighterController.java

@Transactional
@RequestMapping("deleteFireBrigade")
public String deleteFireBrigade(Model model, @RequestParam int id, HttpServletRequest request) {
    FireBrigadeModel deletedFireBrigade = fireBrigadeRepository.findById(id);

    if (!fireFighterRepository.findByFireBrigade_Id(id).isEmpty()) {
        System.out.println(fireFighterRepository.findByFireBrigade_Id(id));
        model.addAttribute("errorMessage", "Lschen Sie zuerst alle Mitglieder!");
        return "forward:feuerwehr";
    }/*w w  w.j  ava  2s.com*/
    if (!fireEngineRepository.findByFireBrigade_Id(id).isEmpty()) {
        model.addAttribute("errorMessage", "Lschen Sie zuerst alle Fahrzeuge!");
        return "forward:feuerwehr";
    }
    if (deletedFireBrigade == null) {
        model.addAttribute("errorMessage", "Feuerwehr konnte nicht gefunden werden.");
        return "forward:feuerwehr";
    }

    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        User user = userRepository.findByFireBrigade(deletedFireBrigade);
        if (user == null) {
            model.addAttribute("errorMessage", "Es gibt keinen dazugehrigen User!");
            return "forward:feuerwehr";
        }
        fireBrigadeRepository.delete(id);
        model.addAttribute("message", "Feuerwehr Nr." + id + " " + "wurde erfolgreich gelscht!");
        System.out.println(user);
        userRepository.delete(user);
    }
    return "forward:feuerwehr";
}

From source file:org.carcv.web.servlet.CarTableServlet.java

/**
 * @see CarTableServlet/*  w ww  . j a  v a 2 s.  c  o  m*/
 * @param request the HttpServletRequest
 * @param response the HttpServletResponse
 * @throws ServletException
 * @throws IOException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final ArrayList<FileEntry> requestEntries = (ArrayList<FileEntry>) bean.getAll();

    @SuppressWarnings("unchecked")
    ArrayList<FileEntry> abstractEntries = (ArrayList<FileEntry>) requestEntries.clone();

    // Timezone
    String timeZoneStr = request.getParameter("timezone");
    TimeZone tz = TimeZone.getTimeZone(timeZoneStr);

    DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
    dateFormat.setTimeZone(tz);
    DateFormat timeFormat = new SimpleDateFormat("HH:mm");
    timeFormat.setTimeZone(tz);

    Collections.sort(abstractEntries, new Comparator<FileEntry>() {
        @Override
        public int compare(FileEntry o1, FileEntry o2) {
            return new CompareToBuilder().append(o2.getCarData().getTimestamp(), o1.getCarData().getTimestamp())
                    .toComparison();
        }
    });

    String date, time, entryId, licensePlate, location, previewPath;
    ArrayList<WebReportTableMember> wrtmList = new ArrayList<>();

    for (FileEntry e : abstractEntries) {
        // initialize
        date = dateFormat.format(e.getCarData().getTimestamp());
        time = timeFormat.format(e.getCarData().getTimestamp());

        entryId = e.getId().toString();

        licensePlate = e.getCarData().getNumberPlate().getOrigin() + ": "
                + e.getCarData().getNumberPlate().getText();

        location = e.getCarData().getAddress().printBR();

        FileCarImage fci = e.getCarImages().get(0);
        previewPath = fci.getFilepath().toString();

        WebReportTableMember wrtm = new WebReportTableMember(previewPath, entryId, time, date, location,
                licensePlate, timeZoneStr);

        wrtmList.add(wrtm);
    }

    request.setAttribute("wrtmList", wrtmList);

    boolean isAdmin = request.isUserInRole(adminRole);
    request.setAttribute("isAdmin", isAdmin);

    RequestDispatcher rd = getServletContext().getRequestDispatcher("/app/cartable.jsp");
    rd.forward(request, response);
}

From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java

@Override
public List<MenuEntry> getViews(final HttpServletRequest request, final Object object) {
    if (object instanceof ChannelInformation) {
        final ChannelInformation channel = (ChannelInformation) object;

        final Map<String, Object> model = new HashMap<>(1);
        model.put("channelId", channel.getId());

        final List<MenuEntry> result = new LinkedList<>();

        result.add(new MenuEntry("Content", 100,
                LinkTarget.createFromController(ChannelController.class, "view").expand(model),
                Modifier.DEFAULT, null));
        result.add(new MenuEntry("List", 120,
                LinkTarget.createFromController(ChannelController.class, "viewPlain").expand(model),
                Modifier.DEFAULT, null));
        result.add(new MenuEntry("Details", 200,
                LinkTarget.createFromController(ChannelController.class, "details").expand(model),
                Modifier.DEFAULT, null));

        result.add(new MenuEntry(null, -1, "Validation", 210,
                LinkTarget.createFromController(ChannelController.class, "viewValidation").expand(model),
                Modifier.DEFAULT, null).setBadge(channel.getState().getValidationErrorCount()));

        if (request.isUserInRole("MANAGER")) {
            result.add(new MenuEntry("Deploy Keys", 1000,
                    LinkTarget.createFromController(ChannelController.class, "deployKeys").expand(model),
                    Modifier.DEFAULT, null));
        }//from   w  w w  .j  av  a 2 s  .  co  m

        if (request.isUserInRole("MANAGER") || request.isUserInRole("ADMIN")) {
            result.add(new MenuEntry("Internal", 400, "View Cache", 100,
                    LinkTarget.createFromController(ChannelController.class, "viewCache").expand(model),
                    Modifier.DEFAULT, null));
            result.add(new MenuEntry(
                    "Internal", 400, "Aspect Versions", 100, LinkTarget
                            .createFromController(ChannelController.class, "viewAspectVersions").expand(model),
                    Modifier.DEFAULT, null));
        }

        /* FIXME:
        if ( channel.hasAspect ( "p2.repo" ) )
        {
        result.add ( new MenuEntry ( "Help", Integer.MAX_VALUE, "P2 Repository", 2_000, LinkTarget.createFromController ( ChannelController.class, "helpP2" ).expand ( model ), Modifier.DEFAULT, "info-sign" ) );
        }
        */

        result.add(new MenuEntry("Help", Integer.MAX_VALUE, "API Upload", 1_100,
                LinkTarget.createFromController(ChannelController.class, "helpApi").expand(model),
                Modifier.DEFAULT, "upload"));

        return result;
    }
    return null;
}

From source file:org.eclipse.packagedrone.repo.channel.web.channel.ChannelController.java

@Override
public List<MenuEntry> getViews(final HttpServletRequest request, final Object object) {
    if (object instanceof ChannelInformation) {
        final ChannelInformation channel = (ChannelInformation) object;

        final Map<String, Object> model = new HashMap<>(1);
        model.put("channelId", channel.getId());

        final List<MenuEntry> result = new LinkedList<>();

        result.add(new MenuEntry("Content", 100,
                LinkTarget.createFromController(ChannelController.class, "view").expand(model),
                Modifier.DEFAULT, null));
        result.add(new MenuEntry("List", 120,
                LinkTarget.createFromController(ChannelController.class, "viewPlain").expand(model),
                Modifier.DEFAULT, null));
        result.add(new MenuEntry("Details", 200,
                LinkTarget.createFromController(ChannelController.class, "details").expand(model),
                Modifier.DEFAULT, null));

        result.add(new MenuEntry(null, -1, "Validation", 210,
                LinkTarget.createFromController(ChannelController.class, "viewValidation").expand(model),
                Modifier.DEFAULT, null).setBadge(channel.getState().getValidationErrorCount()));

        if (request.isUserInRole("MANAGER")) {
            result.add(new MenuEntry("Deploy Keys", 1000,
                    LinkTarget.createFromController(ChannelController.class, "deployKeys").expand(model),
                    Modifier.DEFAULT, null));
        }/*from w  w  w  .ja va  2s .c o  m*/

        if (request.isUserInRole("MANAGER") || request.isUserInRole("ADMIN")) {
            result.add(new MenuEntry("Internal", 400, "View Cache", 100,
                    LinkTarget.createFromController(ChannelController.class, "viewCache").expand(model),
                    Modifier.DEFAULT, null));
            result.add(new MenuEntry(
                    "Internal", 400, "Aspect Versions", 100, LinkTarget
                            .createFromController(ChannelController.class, "viewAspectVersions").expand(model),
                    Modifier.DEFAULT, null));
        }

        if (channel.hasAspect("p2.repo")) {
            result.add(new MenuEntry("Help", Integer.MAX_VALUE, "P2 Repository", 2_000,
                    LinkTarget.createFromController(ChannelController.class, "helpP2").expand(model),
                    Modifier.DEFAULT, "info-sign"));
        }

        result.add(new MenuEntry("Help", Integer.MAX_VALUE, "API Upload", 1_100,
                LinkTarget.createFromController(ChannelController.class, "helpApi").expand(model),
                Modifier.DEFAULT, "upload"));

        return result;
    }
    return null;
}

From source file:org.cerberus.servlet.crud.testdata.ReadTestDataLib.java

/**
 * Auxiliary method that retrieves a list of test data library entries with
 * basis on the GUI information (datatable)
 *
 * @param appContext - context object used to get the required beans
 * @param request - object that contains the search and sort filters used to
 * retrieve the information to be displayed in the GUI.
 * @return object containing the info to be displayed in the GUI
 * @throws IOException/*from ww  w. ja  v  a 2  s . c o  m*/
 * @throws BeansException
 * @throws NumberFormatException
 * @throws JSONException
 */
private AnswerItem findTestDataLibList(ApplicationContext appContext, HttpServletRequest request)
        throws IOException, BeansException, NumberFormatException, JSONException {
    AnswerItem item = new AnswerItem();
    JSONObject jsonResponse = new JSONObject();
    testDataLibService = appContext.getBean(ITestDataLibService.class);

    int startPosition = Integer
            .valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayStart"), "0"));
    int length = Integer
            .valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayLength"), "0"));
    /*int sEcho  = Integer.valueOf(request.getParameter("sEcho"));*/

    String searchParameter = ParameterParserUtil.parseStringParam(request.getParameter("sSearch"), "");
    int columnToSortParameter = Integer
            .parseInt(ParameterParserUtil.parseStringParam(request.getParameter("iSortCol_0"), "0"));
    String sColumns = ParameterParserUtil.parseStringParam(request.getParameter("sColumns"),
            "tdl.TestDataLibID,tdl.Name,tdl.System,tdl.Environment,tdl.Country,tdl.Group,tdl.Type,tdl.Database,tdl.Script,tdl.ServicePath,tdl.Method,tdl.Envelope,tdl.databaseCsv,tdl.Description");
    String columnToSort[] = sColumns.split(",");
    String columnName = columnToSort[columnToSortParameter];
    String sort = ParameterParserUtil.parseStringParam(request.getParameter("sSortDir_0"), "asc");

    Map<String, List<String>> individualSearch = new HashMap<String, List<String>>();
    for (int a = 0; a < columnToSort.length; a++) {
        if (null != request.getParameter("sSearch_" + a) && !request.getParameter("sSearch_" + a).isEmpty()) {
            List<String> search = new ArrayList(Arrays.asList(request.getParameter("sSearch_" + a).split(",")));
            individualSearch.put(columnToSort[a], search);
        }
    }

    AnswerList resp = testDataLibService.readByVariousByCriteria(null, null, null, null, null, startPosition,
            length, columnName, sort, searchParameter, individualSearch);

    JSONArray jsonArray = new JSONArray();
    boolean userHasPermissions = request.isUserInRole("TestDataManager");
    if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {//the service was able to perform the query, then we should get all values
        for (TestDataLib testDataLib : (List<TestDataLib>) resp.getDataList()) {
            jsonArray.put(convertTestDataLibToJSONObject(testDataLib, false));

        }
    }

    //recordsFiltered do lado do servidor    
    jsonResponse.put("hasPermissions", userHasPermissions);
    jsonResponse.put("contentTable", jsonArray);
    jsonResponse.put("iTotalRecords", resp.getTotalRows());
    jsonResponse.put("iTotalDisplayRecords", resp.getTotalRows());
    //recordsFiltered

    item.setItem(jsonResponse);
    item.setResultMessage(resp.getResultMessage());
    return item;
}

From source file:in.raster.oviyam.servlet.UserConfiguration.java

/** 
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request// w  w  w .j  av a  2 s  . c om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = null;
    try {
        String settings = request.getParameter("settings");
        String actionToDo = request.getParameter("todo");
        String settingsValue = request.getParameter("settingsValue");

        //Get user details
        /*InitialContext ctx = new InitialContext();
        Subject subject = (Subject) ctx.lookup("java:comp/env/security/subject");
        List<Principal> prinList = new ArrayList<Principal>(subject.getPrincipals());
        Principal p = prinList.get(0);
        String userName = p.getName();
        System.out.println("User name: " + userName);*/

        String userName = request.getUserPrincipal().getName();

        //File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
        UserHandler uh = new UserHandler();
        String str = null;
        out = response.getWriter();
        User user = uh.findUserByName(userName);

        if (user == null) {
            user = new User();
            user.setUserName(userName);
            Button btn = new Button();
            btn.setLabel("Today CT");
            btn.setDateCrit("t");
            btn.setModality("CT");
            btn.setAutoRefresh("0");
            uh.addNewUser(btn, userName);
        }

        if (user != null) {
            if (actionToDo.equalsIgnoreCase("READ")) {
                if (settings.equals("theme")) {
                    str = user.getTheme();
                } else if (settings.equals("sessTimeout")) {
                    str = user.getSessTimeout();
                } else if (settings.equals("userName")) {
                    str = user.getUserName();
                    String sessTimeout = user.getSessTimeout();
                    if (sessTimeout != null) {
                        HttpSession session = request.getSession(false);
                        session.setMaxInactiveInterval(Integer.parseInt(sessTimeout));
                    }
                } else if (settings.equals("viewerSlider")) {
                    str = user.getViewerSlider();
                } else if (settings.equals("roles")) {
                    //Principal pTmp = prinList.get(1);
                    //str = pTmp.toString();
                    if (request.isUserInRole("WebAdmin") || request.isUserInRole("admin")) {
                        str = "Admin";
                    } else {
                        str = "Other";
                    }
                } else if (settings.equals("buttons")) {
                    QueryParamHandler qph = new QueryParamHandler();
                    List<Button> butList = qph.getAllButtons(userName);
                    JSONArray jsonArray = new JSONArray(butList);
                    str = jsonArray.toString();
                }
                out.print(str);
            } else if (actionToDo.equalsIgnoreCase("UPDATE")) {
                if (settings.equals("theme")) {
                    user.setTheme(settingsValue);
                } else if (settings.equals("sessTimeout")) {
                    user.setSessTimeout(settingsValue);
                } else if (settings.equals("viewerSlider")) {
                    user.setViewerSlider(settingsValue);
                }
                uh.updateUser(user);
                out.println("Success");
            }
        }

    } catch (Exception ex) {
        log.error("Exception occured in User Configuration servlet", ex);
        //out.println("Failure");
    }
}

From source file:org.lamsfoundation.lams.admin.web.OrgManageAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    service = AdminServiceProxy.getService(getServlet().getServletContext());
    messageService = AdminServiceProxy.getMessageService(getServlet().getServletContext());

    // Get organisation whose child organisations we will populate the OrgManageForm with
    Integer orgId = WebUtil.readIntParam(request, "org", true);
    Organisation org = null;//from  www .  ja  va2  s  .  c o  m
    if (orgId == null) {
        orgId = (Integer) request.getAttribute("org");
    }
    if ((orgId != null) && (orgId > 0)) {
        org = (Organisation) service.findById(Organisation.class, orgId);
        if (org == null) {
            request.setAttribute("errorName", "OrgManageAction");
            request.setAttribute("errorMessage", messageService.getMessage("error.org.invalid"));
            return mapping.findForward("error");
        }
    }

    // get number of users figure
    // TODO use hql that does a count instead of getting whole objects
    Integer numUsers = (service.getRootOrganisation().equals(org) ? service.getCountUsers()
            : Integer.valueOf(service.getUsersFromOrganisation(orgId).size()));
    String key = (service.getRootOrganisation().getOrganisationId().equals(orgId) ? "label.users.in.system"
            : "label.users.in.group");
    String[] args = { numUsers.toString() };
    request.setAttribute("numUsers", messageService.getMessage(key, args));

    // get logged in user's id
    Integer userId = ((UserDTO) SessionManager.getSession().getAttribute(AttributeNames.USER)).getUserID();

    // Set OrgManageForm
    OrgManageForm orgManageForm = (OrgManageForm) form;
    if (orgManageForm == null) {
        orgManageForm = new OrgManageForm();
        orgManageForm.setStateId(OrganisationState.ACTIVE);
    } else if (orgManageForm.getStateId() == null) {
        orgManageForm.setStateId(OrganisationState.ACTIVE);
    }
    orgManageForm.setParentId(orgId);
    orgManageForm.setParentName(org.getName());
    orgManageForm.setType(org.getOrganisationType().getOrganisationTypeId());

    // Get list of child organisations depending on requestor's role and the organisation's type
    if (!orgManageForm.getType().equals(OrganisationType.CLASS_TYPE)) {
        List<OrgManageBean> orgManageBeans = new ArrayList<OrgManageBean>();
        if (request.isUserInRole(Role.SYSADMIN) || request.isUserInRole(Role.GROUP_ADMIN)
                || request.isUserInRole(Role.GROUP_MANAGER)) {
            // the organisation type of the children
            Integer typeId = (orgManageForm.getType().equals(OrganisationType.ROOT_TYPE)
                    ? OrganisationType.COURSE_TYPE
                    : OrganisationType.CLASS_TYPE);

            HashMap<String, Object> properties = new HashMap<String, Object>();
            properties.put("organisationType.organisationTypeId", typeId);
            properties.put("organisationState.organisationStateId", orgManageForm.getStateId());
            List organisations = service.findByProperties(Organisation.class, properties);

            for (int i = 0; i < organisations.size(); i++) {
                Organisation organisation = (Organisation) organisations.get(i);
                Organisation parentOrg = (typeId.equals(OrganisationType.CLASS_TYPE))
                        ? organisation.getParentOrganisation()
                        : organisation;
                // do not list this org as a child if requestor is not an admin or manager in the parent, or global admin
                if (!request.isUserInRole(Role.SYSADMIN)) {
                    if (!(service.isUserInRole(userId, parentOrg.getOrganisationId(), Role.GROUP_ADMIN)
                            || service.isUserInRole(userId, parentOrg.getOrganisationId(), Role.GROUP_MANAGER)
                            || service.isUserGlobalGroupAdmin()))
                        continue;
                }
                // do not list this org if it is not a child of the requested parent
                if (typeId.equals(OrganisationType.CLASS_TYPE)) {
                    if (!parentOrg.getOrganisationId().equals(orgId))
                        continue;
                }
                OrgManageBean orgManageBean = new OrgManageBean();
                BeanUtils.copyProperties(orgManageBean, organisation);
                orgManageBean.setStatus(organisation.getOrganisationState().getDescription());
                orgManageBean.setEditable(true);
                orgManageBeans.add(orgManageBean);
            }
        }
        Collections.sort(orgManageBeans);
        orgManageForm.setOrgManageBeans(orgManageBeans);
        request.setAttribute("OrgManageForm", orgManageForm);

        // display org info
        request.setAttribute("org", org);
    } else {
        // display class info, with parent group's 'courseAdminCan...' permissions.
        // note the org is not saved, properties set only for passing to view component.
        Organisation pOrg = org.getParentOrganisation();
        org.setCourseAdminCanAddNewUsers(pOrg.getCourseAdminCanAddNewUsers());
        org.setCourseAdminCanBrowseAllUsers(pOrg.getCourseAdminCanBrowseAllUsers());
        org.setCourseAdminCanChangeStatusOfCourse(pOrg.getCourseAdminCanChangeStatusOfCourse());
        request.setAttribute("org", org);

        // display parent org breadcrumb link
        request.setAttribute("parentGroupName", pOrg.getName());
        request.setAttribute("parentGroupId", pOrg.getOrganisationId());
    }

    // let the jsp know whether to display links
    request.setAttribute("createGroup",
            request.isUserInRole(Role.SYSADMIN) || service.isUserGlobalGroupAdmin());
    request.setAttribute("editGroup", service.canEditGroup(userId, orgId));
    request.setAttribute("manageGlobalRoles", request.isUserInRole(Role.SYSADMIN));
    return mapping.findForward("orglist");
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Enables a user to find a provider and request access to provider details.
 * /*from w ww  .j  a  v a  2s. co m*/
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView findDataProvider(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    List<KeyValueDTO> providerList = uddiUtils.getProviderListAsKeyValues();
    List<String> businessKeys = uddiUtils.getAssociatedBusinessKeys(request.getRemoteUser());
    List<KeyValueDTO> providerRegistrationLogins = new ArrayList<KeyValueDTO>();

    List<KeyValueDTO> toRemove = new ArrayList<KeyValueDTO>();
    for (KeyValueDTO providerKV : providerList) {
        if (businessKeys.contains(providerKV.getKey())) {
            providerRegistrationLogins.add(providerKV);
            toRemove.add(providerKV);
        }
    }

    // remove the ones already accessible
    providerList.removeAll(toRemove);

    // view this of providers
    ModelAndView mav = new ModelAndView("registrationProviderList");
    mav.addObject("providerList", providerList);
    mav.addObject("providerRegistrationLogins", providerRegistrationLogins);

    // if user is admin, not need to send requests
    if (request.isUserInRole(adminRole)) {
        mav.addObject("updateAction", "updateRegistrationLogins");
    } else {
        mav.addObject("updateAction", "sendRegistrationLoginsRequest");
    }
    return mav;
}

From source file:org.lamsfoundation.lams.admin.web.UserAction.java

public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    initServices();/*w w w  .ja v a 2 s.  com*/
    if (UserAction.locales == null) {
        UserAction.locales = service.findAll(SupportedLocale.class);
        Collections.sort(UserAction.locales);
    }
    if (UserAction.authenticationMethods == null) {
        UserAction.authenticationMethods = service.findAll(AuthenticationMethod.class);
    }

    DynaActionForm userForm = (DynaActionForm) form;
    Integer orgId = WebUtil.readIntParam(request, "orgId", true);
    Integer userId = WebUtil.readIntParam(request, "userId", true);

    // Get all the css and flash themes themes
    List<Theme> cssThemes = themeService.getAllCSSThemes();
    request.setAttribute("cssThemes", cssThemes);
    List<Theme> flashThemes = themeService.getAllFlashThemes();
    request.setAttribute("flashThemes", flashThemes);

    // Select the default themes by default
    Theme defaultCSSTheme = themeService.getDefaultCSSTheme();
    for (Theme theme : cssThemes) {
        if (theme.getThemeId().equals(defaultCSSTheme.getThemeId())) {
            userForm.set("userCSSTheme", theme.getThemeId());
            break;
        }
    }
    Theme defaultFlashTheme = themeService.getDefaultFlashTheme();
    for (Theme theme : flashThemes) {
        if (theme.getThemeId().equals(defaultFlashTheme.getThemeId())) {
            userForm.set("userFlashTheme", theme.getThemeId());
            break;
        }
    }

    // test requestor's permission
    Organisation org = null;
    Boolean canEdit = service.isUserGlobalGroupAdmin();
    if (orgId != null) {
        org = (Organisation) service.findById(Organisation.class, orgId);
        if (!canEdit) {
            OrganisationType orgType = org.getOrganisationType();
            Integer orgIdOfCourse = orgType.getOrganisationTypeId().equals(OrganisationType.CLASS_TYPE)
                    ? org.getParentOrganisation().getOrganisationId()
                    : orgId;
            User requestor = service.getUserByLogin(request.getRemoteUser());
            if (service.isUserInRole(requestor.getUserId(), orgIdOfCourse, Role.GROUP_ADMIN)
                    || service.isUserInRole(requestor.getUserId(), orgIdOfCourse, Role.GROUP_MANAGER)) {
                Organisation course = (Organisation) service.findById(Organisation.class, orgIdOfCourse);
                canEdit = course.getCourseAdminCanAddNewUsers();
            }
        }
    }

    if (!(canEdit || request.isUserInRole(Role.SYSADMIN))) {
        request.setAttribute("errorName", "UserAction");
        request.setAttribute("errorMessage", messageService.getMessage("error.authorisation"));
        return mapping.findForward("error");
    }

    // editing a user
    if (userId != null && userId != 0) {
        User user = (User) service.findById(User.class, userId);
        UserAction.log.debug("got userid to edit: " + userId);
        BeanUtils.copyProperties(userForm, user);
        userForm.set("password", null);
        SupportedLocale locale = user.getLocale();
        userForm.set("localeId", locale.getLocaleId());

        AuthenticationMethod authenticationMethod = user.getAuthenticationMethod();
        userForm.set("authenticationMethodId", authenticationMethod.getAuthenticationMethodId());
        // set user's organisations to display
        request.setAttribute("userOrgRoles", getUserOrgRoles(user));
        request.setAttribute("globalRoles", getGlobalRoles(user));

        // Check the user css theme is still installed
        Long userSelectedCSSTheme = null;
        if (user.getHtmlTheme() != null) {
            for (Theme theme : cssThemes) {
                if (theme.getThemeId() == user.getHtmlTheme().getThemeId()) {
                    userSelectedCSSTheme = theme.getThemeId();
                    break;
                }
            }
        }
        // if still null, use the default
        if (userSelectedCSSTheme == null) {
            userSelectedCSSTheme = themeService.getDefaultCSSTheme().getThemeId();
        }
        userForm.set("userCSSTheme", userSelectedCSSTheme);

        // Check the user flash theme is still installed
        Long userSelectedFlashTheme = null;
        if (user.getHtmlTheme() != null) {
            for (Theme theme : flashThemes) {
                if (theme.getThemeId() == user.getFlashTheme().getThemeId()) {
                    userSelectedFlashTheme = theme.getThemeId();
                    break;
                }
            }
        }
        // if still null, use the default
        if (userSelectedFlashTheme == null) {
            userSelectedFlashTheme = themeService.getDefaultFlashTheme().getThemeId();
        }
        userForm.set("userFlashTheme", userSelectedFlashTheme);

    } else { // create a user
        try {
            SupportedLocale locale = LanguageUtil.getDefaultLocale();
            userForm.set("localeId", locale.getLocaleId());
        } catch (Exception e) {
            UserAction.log.debug(e);
        }
    }
    userForm.set("orgId", (org == null ? null : org.getOrganisationId()));

    // Get all available time zones
    List<Timezone> availableTimeZones = timezoneService.getDefaultTimezones();
    TreeSet<TimezoneDTO> timezoneDtos = new TreeSet<TimezoneDTO>(new TimezoneDTOComparator());
    for (Timezone availableTimeZone : availableTimeZones) {
        String timezoneId = availableTimeZone.getTimezoneId();
        TimezoneDTO timezoneDto = new TimezoneDTO();
        timezoneDto.setTimeZoneId(timezoneId);
        timezoneDto.setDisplayName(TimeZone.getTimeZone(timezoneId).getDisplayName());
        timezoneDtos.add(timezoneDto);
    }
    request.setAttribute("timezoneDtos", timezoneDtos);

    // for breadcrumb links
    if (org != null) {
        request.setAttribute("orgName", org.getName());
        Organisation parentOrg = org.getParentOrganisation();
        if (parentOrg != null && !parentOrg.equals(service.getRootOrganisation())) {
            request.setAttribute("pOrgId", parentOrg.getOrganisationId());
            request.setAttribute("parentName", parentOrg.getName());
        }
    }

    request.setAttribute("locales", UserAction.locales);
    request.setAttribute("authenticationMethods", UserAction.authenticationMethods);

    return mapping.findForward("user");
}

From source file:org.cerberus.servlet.crud.testdata.ReadTestDataLib.java

protected void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    // Default message to unexpected error.
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    AnswerItem answer = new AnswerItem(msg);

    response.setContentType("application/json");
    response.setCharacterEncoding("utf8");

    /**/*from www .  ja va2s.c o  m*/
     * Parsing and securing all required parameters.
     */
    String name = policy.sanitize(request.getParameter("name"));
    String country = policy.sanitize(request.getParameter("country"));
    String columnName = ParameterParserUtil.parseStringParam(request.getParameter("columnName"), "");
    Integer testDataLibId = 0;

    Integer limit = -1;
    boolean hasError = true;
    try {
        if (request.getParameter("testdatalibid") != null && !request.getParameter("testdatalibid").isEmpty()) {
            testDataLibId = Integer.parseInt(request.getParameter("testdatalibid"));
            hasError = false;
        }
    } catch (NumberFormatException ex) {
        org.apache.log4j.Logger.getLogger(ReadTestDataLib.class.getName()).log(org.apache.log4j.Level.ERROR,
                null, ex);
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Test Data Library"));
        msg.setDescription(msg.getDescription().replace("%OPERATION%", "Read"));
        msg.setDescription(
                msg.getDescription().replace("%REASON%", "Test data library id must be an integer value."));
        answer.setResultMessage(msg);
        hasError = true;
    }
    try {
        //if the limit fails to be converted there is no problem because in the database we use the default value
        if (request.getParameter("limit") != null && !request.getParameter("limit").isEmpty()) {
            limit = Integer.parseInt(request.getParameter("limit"));
        }
    } catch (NumberFormatException ex) {
        org.apache.log4j.Logger.getLogger(ReadTestDataLib.class.getName()).log(org.apache.log4j.Level.WARN,
                null, ex);
    }

    // Global boolean on the servlet that define if the user has permition to edit and delete object.
    boolean userHasPermissions = request.isUserInRole("TestDataManager");

    try {
        JSONObject jsonResponse;

        if (request.getParameter("testdatalibid") != null && !hasError) {
            if (request.getParameter("name") != null && request.getParameter("country") != null) {
                //gets all test cases that use a library
                answer = getTestCasesUsingTestDataLib(testDataLibId, name, country, appContext,
                        userHasPermissions);
            } else {
                //gets a lib by id
                answer = findTestDataLibByID(testDataLibId, appContext, userHasPermissions);
            }
        } else if (request.getParameter("name") != null && request.getParameter("limit") != null) {
            answer = findTestDataLibNameList(name, limit, appContext);
        } else if (request.getParameter("groups") != null) {
            //gets the list of distinct groups
            answer = findDistinctGroups(appContext);
        } else if (!Strings.isNullOrEmpty(columnName)) {
            answer = findDistinctValuesOfColumn(appContext, request, columnName);
            jsonResponse = (JSONObject) answer.getItem();
        } else {
            //no parameters, then retrieves the full list
            answer = findTestDataLibList(appContext, request);
        }

        jsonResponse = (JSONObject) answer.getItem();

        jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
        jsonResponse.put("message", answer.getResultMessage().getDescription());

        response.getWriter().print(jsonResponse.toString());

    } catch (JSONException e) {
        org.apache.log4j.Logger.getLogger(ReadTestDataLib.class.getName()).log(org.apache.log4j.Level.ERROR,
                null, e);
        //returns a default error message with the json format that is able to be parsed by the client-side
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }
}