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:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

@POST
@Produces(APPLICATION_JSON)/*from   w  w  w  .  java  2s  . c om*/
@Consumes(APPLICATION_JSON)
public Response createReport(@Context HttpServletRequest request, ReportDTO report,
        @DefaultValue("default") @QueryParam(value = "projection") String projection,
        @HeaderParam("scopeName") String scopeName) {
    Response result;
    String username = request.getRemoteUser();

    log.debug("{} is requesting createReport(...), with a ID={}, scopeName: {}, visibility: {}", username,
            report.getId(), scopeName, report.getVisibility());

    if (StringUtils.isBlank(scopeName)) {
        result = createErrorResponse(ErrorCodes.USER_SCOPE_MISSING);
    } else {
        if (isScopeAllowed(report.getVisibility(), request)) {
            report.setCreatedBy(username);
            report.setScopeName(scopeName);

            ReportFeatureEnum requiredFeature = AuthorizationCheckUtil.getRequiredFeatureToCreateReport(report,
                    username);
            ReportDTO reportDTO;
            if (requiredFeature == null || request.isUserInRole(requiredFeature.toString())) {
                try {
                    reportDTO = reportService.create(report, username);
                    switch (Projection.valueOf(projection.toUpperCase())) {

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

                    default:
                        result = createSuccessResponse(reportDTO.getId());
                    }
                } catch (Exception e) {
                    log.error("createReport failed.", e);
                    result = createErrorResponse(ErrorCodes.CREATE_ENTITY_ERROR);
                }
            } else {
                result = createErrorResponse(ErrorCodes.NOT_AUTHORIZED);
            }
        } else {
            result = createErrorResponse(ErrorCodes.NOT_AUTHORIZED);
        }
    }
    return result;
}

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

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

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

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

        if (request.isUserInRole("MANAGER")) {
            if (object instanceof ChannelInformation) {
                final ChannelInformation channelInformation = (ChannelInformation) object;

                if (!channelInformation.getState().isLocked()) {
                    result.add(new MenuEntry("Add Artifact", 100,
                            LinkTarget.createFromController(ChannelController.class, "add").expand(model),
                            Modifier.PRIMARY, null));
                    result.add(new MenuEntry("Delete Channel", 400,
                            LinkTarget.createFromController(ChannelController.class, "delete").expand(model),
                            Modifier.DANGER, "trash").makeModalMessage("Delete channel",
                                    "Are you sure you want to delete the whole channel?"));
                    result.add(new MenuEntry("Clear Channel", 500,
                            LinkTarget.createFromController(ChannelController.class, "clear").expand(model),
                            Modifier.WARNING, null).makeModalMessage("Clear channel",
                                    "Are you sure you want to delete all artifacts from this channel?"));

                    result.add(new MenuEntry("Lock Channel", 600,
                            LinkTarget.createFromController(ChannelController.class, "lock").expand(model),
                            Modifier.DEFAULT, null));
                } else {
                    result.add(new MenuEntry("Unlock Channel", 600,
                            LinkTarget.createFromController(ChannelController.class, "unlock").expand(model),
                            Modifier.DEFAULT, null));
                }/*w  ww  .j a v  a2 s  . com*/
            }

            result.add(new MenuEntry("Edit", EDIT.getPriority(), "Edit Channel", 200,
                    LinkTarget.createFromController(ChannelController.class, "edit").expand(model),
                    Modifier.DEFAULT, null));
            result.add(new MenuEntry("Maintenance", 160, "Refresh aspects", 100,
                    LinkTarget.createFromController(ChannelController.class, "refreshAllAspects").expand(model),
                    Modifier.SUCCESS, "refresh"));
        }

        if (request.getRemoteUser() != null) {
            result.add(new MenuEntry("Edit", EDIT.getPriority(), "Configure Aspects", 300,
                    LinkTarget.createFromController(ChannelController.class, "aspects").expand(model),
                    Modifier.DEFAULT, null));
        }

        return result;
    } else if (Tags.ACTION_TAG_CHANNELS.equals(object)) {
        final List<MenuEntry> result = new LinkedList<>();

        if (request.isUserInRole("MANAGER")) {
            // result.add ( new MenuEntry ( "Create Channel", 100, LinkTarget.createFromController ( ChannelController.class, "createDetailed" ), Modifier.PRIMARY, null ) );
            result.add(new MenuEntry("Create Channel", 120,
                    LinkTarget.createFromController(ChannelController.class, "createWithRecipe"),
                    Modifier.PRIMARY, null));
        }

        return result;
    } else if (object instanceof org.eclipse.packagedrone.repo.channel.ChannelArtifactInformation) {
        final ChannelArtifactInformation ai = (ChannelArtifactInformation) object;

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

        final Map<String, Object> model = new HashMap<>(2);
        model.put("channelId", ai.getChannelId().getId());
        model.put("artifactId", ai.getId());

        if (request.isUserInRole("MANAGER")) {
            if (ai.is("stored")) {
                result.add(new MenuEntry(
                        "Attach Artifact", 200, LinkTarget
                                .createFromController(ChannelController.class, "attachArtifact").expand(model),
                        Modifier.PRIMARY, null));
                result.add(new MenuEntry(
                        "Delete", 1000, LinkTarget
                                .createFromController(ChannelController.class, "deleteArtifact").expand(model),
                        Modifier.DANGER, "trash"));
            }
        }

        return result;
    }
    return null;
}

From source file:src.servlets.ManagePropertys.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   w  w w  .j a  v a  2  s  .  co m
 * @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 {
    try (PrintWriter out = response.getWriter()) {
        String address = "";
        Map m = request.getParameterMap();

        Agents LoggedIn = null;
        try {
            LoggedIn = AgentsDB.getByUsername(request.getUserPrincipal().getName());
            //request.setAttribute("agent", agent);

        } //end try
        catch (Exception ex) {
            address = "/Error.jsp";
        }
        int agentId = 0;
        agentId = LoggedIn.getAgentId();

        if (request.getParameterMap().containsKey("del")) {

            Properties propertyDetails = PropertiesDB
                    .getPropertyByID(Integer.parseInt(request.getParameter("del")));
            if ((propertyDetails != null && propertyDetails.getAgentId().equals(agentId))
                    || request.isUserInRole("admin")) {
                PropertiesDB.deleteProperty(propertyDetails.getId());

                String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
                String filePath = uploadPath + File.separator + "large" + File.separator
                        + propertyDetails.getPhoto();
                String filePathThumbnail = uploadPath + File.separator + "thumbnails" + File.separator
                        + propertyDetails.getPhoto();

                File storeFileThumbnail = new File(filePathThumbnail);
                File storeFile = new File(filePath);

                storeFile.delete();
                storeFileThumbnail.delete();

                address = "ManagePropertys?GetProperties&Status=2";
            }
            response.sendRedirect("/RealtyWebsite/" + address);
            processRequest(request, response);
        } else {
            List<Styles> allStylesList = StylesDB.getAllStyles();
            List<Propertytypes> allPropertyTypesList = PropertytypeDB.getAllPropertytypes();
            List<Garagetypes> allGarageTypesList = GaragetypesDB.getAllGaragetypes();

            if (request.getParameterMap().containsKey("AddNewProperty"))//Add new property
            {
                address = "admin/addNewProperty.jsp";
                String status = "";
                if (request.isUserInRole("admin")) {
                    List<Agents> allAgents = null;
                    try {
                        allAgents = AgentsDB.getAllAgents();
                    } //end try
                    catch (Exception ex) {
                        address = "/Error.jsp";
                    } //end catch
                    address = "admin/addNewProperty.jsp";
                    request.setAttribute("allAgents", allAgents);
                } else {
                    address = "agent/addNewProperty.jsp";
                }
                request.setAttribute("Styles", allStylesList);
                request.setAttribute("Propertytypes", allPropertyTypesList);
                request.setAttribute("Garagetypes", allGarageTypesList);
            } else { //View properties by agent
                if (request.getParameterMap().containsKey("Status")) {
                    int status = Integer.parseInt(request.getParameter("Status"));
                    //String status=request.getParameter("Status");
                    if (status == 1) {
                        request.setAttribute("Status", "This Property Has Been Saved/Updated successfully!");
                    }
                    if (status == 2) {
                        request.setAttribute("Status", "The Property Has Been successfully Removed!");
                    }
                }

                List<Properties> propertyList = null;
                if (request.isUserInRole("admin")) {
                    propertyList = PropertiesDB.getAllProperties();
                    address = "admin/managePropertyList.jsp";
                } else {
                    propertyList = PropertiesDB.getAllPropertiesByAgent(agentId);

                    address = "/agent/managePropertyList.jsp";
                }
                request.setAttribute("propertyList", propertyList);
            }
            if (m.containsKey("propID") && (m.containsKey("agentId") || (request.isUserInRole("admin")))) {
                String StyleType = "";
                String PropType = "";
                String GarageType = "";

                try {
                    Properties propertyDetails = PropertiesDB
                            .getPropertyByID(Integer.parseInt(request.getParameter("propID")));

                    if (propertyDetails == null) {
                        address = "/propertyDetailssss.jsp";
                        request.setAttribute("NoProperties", null);
                    } else {
                        try {
                            PropType = PropertiesDB.getPropType(propertyDetails.getTypeId());
                        } //end try
                        catch (Exception ex) {
                            address = "/Error.jsp";
                        } //end catch
                        try {
                            StyleType = PropertiesDB.getStyleType(propertyDetails.getStyleId());
                        } //end try
                        catch (Exception ex) {
                            address = "/Error.jsp";
                        } //end catch
                        try {
                            GarageType = PropertiesDB.getGarageType(propertyDetails.getGarageId());
                        } //end try
                        catch (Exception ex) {
                            address = "/Error.jsp";
                        } //end catch
                        List<Agents> allAgents = null;
                        try {
                            allAgents = AgentsDB.getAllAgents();
                        } //end try
                        catch (Exception ex) {
                            address = "/Error.jsp";
                        } //end catch

                        //                                List<Styles> allStylesList  = StylesDB.getAllStyles();
                        //                                List<Propertytypes> allPropertyTypesList  = PropertytypeDB.getAllPropertytypes();
                        //                                List<Garagetypes> allGarageTypesList  = GaragetypesDB.getAllGaragetypes();
                        request.setAttribute("propertyDetails", propertyDetails);
                        request.setAttribute("Styles", allStylesList);
                        request.setAttribute("Propertytypes", allPropertyTypesList);
                        request.setAttribute("Garagetypes", allGarageTypesList);

                        if (request.isUserInRole("admin")) {
                            address = "admin/managePropertyDetails.jsp";
                            request.setAttribute("allAgents", allAgents);
                        } else {
                            address = "agent/managePropertyDetails.jsp";
                        }

                    }

                } //end try
                catch (Exception ex) {
                    address = "/Error.jsp";
                } //end catch

            }
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        }
        //            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        //                dispatcher.forward(request, response);
        //        response.sendRedirect("/RealtyWebsite/"+address);
        ////            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        ////            dispatcher.forward(request, response);
        //         
        processRequest(request, response);
    }
    //processRequest(request, response);
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "editFireEngine", method = RequestMethod.GET)
public String showEditFireEngine(Model model, @RequestParam int id, HttpServletRequest request) {
    List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
    model.addAttribute("fireBrigades", fireBrigades);
    List<FireEngineAbbreviationModel> fireEngineAbbreviations = fireEngineAbbreviationRepository.findAll();
    model.addAttribute("fireEngineAbbreviations", fireEngineAbbreviations);
    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        FireEngineModel fireEngine = fireEngineRepository.findById(id);
        if (fireEngine != null) {
            model.addAttribute("fireEngine", fireEngine);
            return "editFireEngine";
        } else {//w  w w  .ja v a 2  s .  co m
            model.addAttribute("errorMessage", "Feuerwehr " + id + " konnte nicht gefunden werden.");
            return "forward:fahrzeuge";
        }
    } else {
        FireEngineModel fireEngine = fireEngineRepository.findByFireBrigadeAndId(getSessionFireBrigade(), id);

        if (fireEngine != null) {
            model.addAttribute("fireEngine", fireEngine);
            return "editFireEngine";
        } else {
            model.addAttribute("errorMessage", "Fahrzeug " + id + " konnte nicht gefunden werden.");
            return "forward:fahrzeuge";
        }
    }
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "addFireFighter", method = RequestMethod.POST)
public String addFireFighter(@Valid @ModelAttribute FireFighterModel newFireFighter,
        BindingResult bindingResult, Model model, HttpServletRequest request) {

    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage = fieldError.getField() + " ist falsch";
        }/*from   www.j  a v  a 2 s. c  o  m*/
        model.addAttribute("errorMessage", errorMessage);
        return "forward:mitglieder";
    }
    if (!request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        newFireFighter.setFireBrigade(getSessionFireBrigade());
    }
    fireFighterRepository.save(newFireFighter);
    model.addAttribute("message",
            "Mitglied " + newFireFighter.getName() + " " + newFireFighter.getSurname() + " hinzugefgt.");

    return "forward:mitglieder";
}

From source file:ejportal.webapp.filter.LocaleFilter.java

/**
 * This method looks for a "locale" request parameter. If it finds one, it
 * sets it as the preferred locale and also configures it to work with JSTL.
 * //from  ww  w. j a v a2 s  .  com
 * @param request
 *            the current request
 * @param response
 *            the current response
 * @param chain
 *            the chain
 * @throws IOException
 *             when something goes wrong
 * @throws ServletException
 *             when a communication failure happens
 */
@Override
@SuppressWarnings("unchecked")
public void doFilterInternal(HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {

    final String locale = request.getParameter("locale");
    Locale preferredLocale = null;

    if (locale != null) {
        final int indexOfUnderscore = locale.indexOf('_');
        if (indexOfUnderscore != -1) {
            final String language = locale.substring(0, indexOfUnderscore);
            final String country = locale.substring(indexOfUnderscore + 1);
            preferredLocale = new Locale(language, country);
        } else {
            preferredLocale = new Locale(locale);
        }
    }

    final HttpSession session = request.getSession(false);

    if (session != null) {
        if (preferredLocale == null) {
            preferredLocale = (Locale) session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
        } else {
            session.setAttribute(Constants.PREFERRED_LOCALE_KEY, preferredLocale);
            Config.set(session, Config.FMT_LOCALE, preferredLocale);
        }

        if ((preferredLocale != null) && !(request instanceof LocaleRequestWrapper)) {
            request = new LocaleRequestWrapper(request, preferredLocale);
            LocaleContextHolder.setLocale(preferredLocale);
        }
    }

    final String theme = request.getParameter("theme");
    // if (theme != null && request.isUserInRole(Constants.ADMIN_ROLE)) {
    // TOD hartkodiert
    if ((theme != null) && request.isUserInRole("ROLE_SYSTEMADMIN")) {
        final Map<String, Object> config = (Map) this.getServletContext().getAttribute(Constants.CONFIG);
        config.put(Constants.CSS_THEME, theme);
    }

    chain.doFilter(request, response);

    // Reset thread-bound LocaleContext.
    LocaleContextHolder.setLocaleContext(null);
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "editFireFighter", method = RequestMethod.GET)
public String showEditFireFighter(Model model, @RequestParam int id, HttpServletRequest request) {
    List<RankModel> ranks = rankRepository.findAll();
    model.addAttribute("ranks", ranks);
    List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
    model.addAttribute("fireBrigades", fireBrigades);
    List<FireFighterStatusModel> status = statusRepository.findAll();
    model.addAttribute("status", status);
    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        FireFighterModel fireFighter = fireFighterRepository.findById(id);
        if (fireFighter != null) {
            model.addAttribute("fireFighter", fireFighter);
            return "editFireFighter";
        } else {/*from   w ww  . j a  v  a2s . com*/
            model.addAttribute("errorMessage", "Mitglied " + id + " konnte nicht gefunden werden.");
            return "forward:mitglieder";
        }
    } else {
        FireFighterModel fireFighter = fireFighterRepository.findByFireBrigadeAndId(getSessionFireBrigade(),
                id);

        if (fireFighter != null) {
            model.addAttribute("fireFighter", fireFighter);
            return "editFireFighter";
        } else {
            model.addAttribute("errorMessage", "Mitglied " + id + " konnte nicht gefunden werden.");
            return "forward:mitglieder";
        }
    }
}

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

/**
 * On submit.//  w w w .j  a  va 2s. c  o  m
 * 
 * @param user
 *            the user
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @param response
 *            the response
 * @param model
 *            the model
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final User user, final BindingResult errors, final HttpServletRequest request,
        final HttpServletResponse response, final Model model) throws Exception {
    if (request.getParameter("cancel") != null) {
        if (!StringUtils.equals(request.getParameter("from"), "list"))
            return this.getCancelView();
        else
            return this.getSuccessView();
    }

    if (this.validator != null) { // validator is null during testing
        this.validator.validate(user, errors);

        if (errors.hasErrors() && (request.getParameter("delete") == null)) {
            model.addAttribute("contributorRoles", this.contributorRoleManager.getAll());
            return "userform";
        }
    }

    this.log.debug("entering 'onSubmit' method...");

    final Locale locale = request.getLocale();

    if (request.getParameter("delete") != null) {
        this.getUserManager().removeUser(user.getId().toString());
        this.saveMessage(request, this.getText("user.deleted", user.getFullName(), locale));

        return this.getSuccessView();
    } else {

        // only attempt to change roles if user is admin for other users,
        // showForm() method will handle populating
        if (request.isUserInRole(Constants.ADMIN_ROLE)) {
            final String[] userRoles = request.getParameterValues("userRoles");

            if (userRoles != null) {
                user.getRoles().clear();
                for (final String roleName : userRoles) {
                    user.addRole(this.roleManager.getRole(roleName));
                }
            }
        }

        final Integer originalVersion = user.getVersion();

        try {
            this.getUserManager().saveUser(user);
        } catch (final AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor
            // userManagerSecurity
            this.log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (final UserExistsException e) {
            errors.rejectValue("username", "errors.existing.user",
                    new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            // reset the version # to what was passed in
            user.setVersion(originalVersion);

            model.addAttribute("contributorRoles", this.contributorRoleManager.getAll());
            return "userform";
        }

        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            this.saveMessage(request, this.getText("user.saved", user.getFullName(), locale));

            // return to main Menu
            return this.getCancelView();
        } else {
            if (StringUtils.isBlank(request.getParameter("version"))) {
                this.saveMessage(request, this.getText("user.added", user.getFullName(), locale));

                // Send an account information e-mail
                this.message.setSubject(this.getText("signup.email.subject", locale));

                try {
                    this.sendUserMessage(user,
                            this.getText("newuser.email.message", user.getFullName(), locale),
                            RequestUtil.getAppURL(request));
                } catch (final MailException me) {
                    this.saveError(request, me.getCause().getLocalizedMessage());
                }

                return this.getSuccessView();
            } else {
                this.saveMessage(request, this.getText("user.updated.byAdmin", user.getFullName(), locale));
            }
        }
    }

    return "redirect:/mainMenu";
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "editStatus", method = RequestMethod.POST)
public String editStatus(@Valid @ModelAttribute FireFighterStatusModel changedStatus,
        BindingResult bindingResult, Model model, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage += fieldError.getField() + " ist ungltig!";
        }//  w w  w .java2  s .c o m
        model.addAttribute("errorMessage", errorMessage);
        return "forward:status";
    }

    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        FireFighterStatusModel status = statusRepository.findById(changedStatus.getId());

        if (status == null) {
            model.addAttribute("errorMessage", "Diese Feuerwehr kann nicht bearbeitet werden!");
        } else {
            status.setDescription(changedStatus.getDescription());
            statusRepository.save(status);
            model.addAttribute("message",
                    "Mitgliederstatus " + changedStatus.getDescription() + " wurde erfolgreich gendert.");
        }
        return "forward:status";

    } else {
        FireFighterStatusModel status = statusRepository.findById(changedStatus.getId());

        if (status == null) {
            model.addAttribute("errorMessage", "Dieser Mitgliederstatus kann nicht bearbeitet werden!");
            System.out.println("Falscher Mitgliederstatus!");
        } else {
            status.setDescription(changedStatus.getDescription());
            statusRepository.save(status);
            model.addAttribute("message",
                    "Mitgliederstatus " + changedStatus.getDescription() + " wurde erfolgreich gendert!");
        }
        return "forward:status";
    }
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "editRank", method = RequestMethod.POST)
public String editRank(@Valid @ModelAttribute RankModel changedRank, BindingResult bindingResult, Model model,
        HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage += fieldError.getField() + " ist ungltig!";
        }// w ww .  j  av a 2  s  .co m
        model.addAttribute("errorMessage", errorMessage);
        return "forward:dienstgrade";
    }

    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        RankModel rank = rankRepository.findById(changedRank.getId());

        if (rank == null) {
            model.addAttribute("errorMessage", "Dieser Dienstgrad kann nicht bearbeitet werden!");
        } else {
            rank.setDescription(changedRank.getDescription());
            rank.setAbbreviation(changedRank.getAbbreviation());
            rankRepository.save(rank);
            model.addAttribute("message",
                    "Dienstgrad " + changedRank.getDescription() + " wurde erfolgreich gendert.");
        }
        return "forward:dienstgrade";

    } else {
        RankModel rank = rankRepository.findById(changedRank.getId());

        if (rank == null) {
            model.addAttribute("errorMessage", "Dieser Dienstgrad kann nicht bearbeitet werden!");
            System.out.println("Falscher Dienstgrad!");
        } else {
            rank.setDescription(changedRank.getDescription());
            rank.setAbbreviation(changedRank.getAbbreviation());
            rankRepository.save(rank);
            model.addAttribute("message",
                    "Dienstgrad " + changedRank.getDescription() + " wurde erfolgreich gendert!");
        }
        return "forward:dienstgrade";
    }
}