Search in sources :

Example 21 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project cas by apereo.

the class OidcLogoutEndpointController method handleRequestInternal.

/**
 * Handle request.
 *
 * @param postLogoutRedirectUrl the post logout redirect url
 * @param state                 the state
 * @param idToken               the id token
 * @param request               the request
 * @param response              the response
 * @return the response entity
 * @throws Exception the exception
 */
@GetMapping(value = { '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.LOGOUT_URL, '/' + OidcConstants.BASE_OIDC_URL + "/logout", "/**/" + OidcConstants.LOGOUT_URL })
public ResponseEntity<HttpStatus> handleRequestInternal(@RequestParam(value = "post_logout_redirect_uri", required = false) final String postLogoutRedirectUrl, @RequestParam(value = "state", required = false) final String state, @RequestParam(value = "id_token_hint", required = false) final String idToken, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    val webContext = new JEEContext(request, response);
    if (!getConfigurationContext().getOidcRequestSupport().isValidIssuerForEndpoint(webContext, OidcConstants.LOGOUT_URL)) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    String clientId = null;
    if (StringUtils.isNotBlank(idToken)) {
        LOGGER.trace("Decoding logout id token [{}]", idToken);
        val configContext = getConfigurationContext();
        val claims = configContext.getIdTokenSigningAndEncryptionService().decode(idToken, Optional.empty());
        clientId = claims.getStringClaimValue(OAuth20Constants.CLIENT_ID);
        LOGGER.debug("Client id retrieved from id token is [{}]", clientId);
        val registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(configContext.getServicesManager(), clientId);
        LOGGER.debug("Located registered service [{}]", registeredService);
        val service = configContext.getWebApplicationServiceServiceFactory().createService(clientId);
        val audit = AuditableContext.builder().service(service).registeredService(registeredService).build();
        val accessResult = configContext.getRegisteredServiceAccessStrategyEnforcer().execute(audit);
        accessResult.throwExceptionIfNeeded();
        WebUtils.putRegisteredService(request, Objects.requireNonNull(registeredService));
        val urls = configContext.getSingleLogoutServiceLogoutUrlBuilder().determineLogoutUrl(registeredService, service, Optional.of(request)).stream().map(SingleLogoutUrl::getUrl).collect(Collectors.toList());
        LOGGER.debug("Logout urls assigned to registered service are [{}]", urls);
        if (StringUtils.isNotBlank(postLogoutRedirectUrl) && registeredService.getMatchingStrategy() != null) {
            val matchResult = registeredService.matches(postLogoutRedirectUrl) || urls.stream().anyMatch(url -> postLogoutRedirectUrlMatcher.matches(postLogoutRedirectUrl, url));
            if (matchResult) {
                LOGGER.debug("Requested logout URL [{}] is authorized for redirects", postLogoutRedirectUrl);
                return new ResponseEntity<>(executeLogoutRedirect(Optional.ofNullable(StringUtils.trimToNull(state)), Optional.of(postLogoutRedirectUrl), Optional.of(clientId), request, response));
            }
        }
        val validURL = urls.stream().filter(urlValidator::isValid).findFirst();
        if (validURL.isPresent()) {
            return new ResponseEntity<>(executeLogoutRedirect(Optional.ofNullable(StringUtils.trimToNull(state)), validURL, Optional.of(clientId), request, response));
        }
        LOGGER.debug("No logout urls could be determined for registered service [{}]", registeredService.getName());
    }
    return new ResponseEntity<>(executeLogoutRedirect(Optional.ofNullable(StringUtils.trimToNull(state)), Optional.empty(), Optional.ofNullable(clientId), request, response));
}
Also used : lombok.val(lombok.val) CasProtocolConstants(org.apereo.cas.CasProtocolConstants) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) RequestParam(org.springframework.web.bind.annotation.RequestParam) OAuth20Utils(org.apereo.cas.support.oauth.util.OAuth20Utils) AuditableContext(org.apereo.cas.audit.AuditableContext) OidcConstants(org.apereo.cas.oidc.OidcConstants) SingleLogoutUrl(org.apereo.cas.logout.slo.SingleLogoutUrl) UrlValidator(org.apereo.cas.web.UrlValidator) lombok.val(lombok.val) HttpServletResponse(javax.servlet.http.HttpServletResponse) StringUtils(org.apache.commons.lang3.StringUtils) Collectors(java.util.stream.Collectors) OidcConfigurationContext(org.apereo.cas.oidc.OidcConfigurationContext) Objects(java.util.Objects) HttpStatus(org.springframework.http.HttpStatus) Slf4j(lombok.extern.slf4j.Slf4j) HttpServletRequest(javax.servlet.http.HttpServletRequest) BaseOidcController(org.apereo.cas.oidc.web.controllers.BaseOidcController) GetMapping(org.springframework.web.bind.annotation.GetMapping) Optional(java.util.Optional) ResponseEntity(org.springframework.http.ResponseEntity) WebUtils(org.apereo.cas.web.support.WebUtils) JEEContext(org.pac4j.core.context.JEEContext) ResponseEntity(org.springframework.http.ResponseEntity) JEEContext(org.pac4j.core.context.JEEContext) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 22 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project disconf by knightliao.

the class MyExceptionHandler method getParamErrors.

/**
 * TypeMismatchException中获取到参数错误类型
 *
 * @param e
 */
private ModelAndView getParamErrors(TypeMismatchException e) {
    Throwable t = e.getCause();
    if (t instanceof ConversionFailedException) {
        ConversionFailedException x = (ConversionFailedException) t;
        TypeDescriptor type = x.getTargetType();
        Annotation[] annotations = type != null ? type.getAnnotations() : new Annotation[0];
        Map<String, String> errors = new HashMap<String, String>();
        for (Annotation a : annotations) {
            if (a instanceof RequestParam) {
                errors.put(((RequestParam) a).value(), "parameter type error!");
            }
        }
        if (errors.size() > 0) {
            return paramError(errors, ErrorCode.TYPE_MIS_MATCH);
        }
    }
    JsonObjectBase jsonObject = JsonObjectUtils.buildGlobalError("parameter type error!", ErrorCode.TYPE_MIS_MATCH);
    return JsonObjectUtils.JsonObjectError2ModelView((JsonObjectError) jsonObject);
}
Also used : RequestParam(org.springframework.web.bind.annotation.RequestParam) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) TypeDescriptor(org.springframework.core.convert.TypeDescriptor) HashMap(java.util.HashMap) JsonObjectBase(com.baidu.dsp.common.vo.JsonObjectBase) Annotation(java.lang.annotation.Annotation)

Example 23 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project scoold by Erudika.

the class AdminController method restore.

@PostMapping("/import")
public String restore(@RequestParam("file") MultipartFile file, @RequestParam(required = false, defaultValue = "false") Boolean isso, HttpServletRequest req, HttpServletResponse res) {
    Profile authUser = utils.getAuthUser(req);
    if (!utils.isAdmin(authUser)) {
        res.setStatus(403);
        return null;
    }
    ObjectReader reader = ParaObjectUtils.getJsonMapper().readerFor(new TypeReference<List<Map<String, Object>>>() {
    });
    Map<String, String> comments2authors = new LinkedHashMap<>();
    int count = 0;
    int importBatchSize = Config.getConfigInt("import_batch_size", 100);
    String filename = file.getOriginalFilename();
    Sysprop s = new Sysprop();
    s.setType("scooldimport");
    try (InputStream inputStream = file.getInputStream()) {
        if (StringUtils.endsWithIgnoreCase(filename, ".zip")) {
            try (ZipInputStream zipIn = new ZipInputStream(inputStream)) {
                ZipEntry zipEntry;
                List<ParaObject> toCreate = new LinkedList<ParaObject>();
                while ((zipEntry = zipIn.getNextEntry()) != null) {
                    if (isso) {
                        count += importFromSOArchive(zipIn, zipEntry, reader, comments2authors).size();
                    } else if (zipEntry.getName().endsWith(".json")) {
                        List<Map<String, Object>> objects = reader.readValue(new FilterInputStream(zipIn) {

                            public void close() throws IOException {
                                zipIn.closeEntry();
                            }
                        });
                        objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
                        if (toCreate.size() >= importBatchSize) {
                            pc.createAll(toCreate);
                            toCreate.clear();
                        }
                        count += objects.size();
                    } else {
                        logger.error("Expected JSON but found unknown file type to import: {}", zipEntry.getName());
                    }
                }
                if (!toCreate.isEmpty()) {
                    pc.createAll(toCreate);
                }
                if (isso) {
                    updateSOCommentAuthors(comments2authors);
                }
            }
        } else if (StringUtils.endsWithIgnoreCase(filename, ".json")) {
            List<Map<String, Object>> objects = reader.readValue(inputStream);
            List<ParaObject> toCreate = new LinkedList<ParaObject>();
            objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
            count = objects.size();
            pc.createAll(toCreate);
        }
        s.setCreatorid(authUser.getCreatorid());
        s.setName(authUser.getName());
        s.addProperty("count", count);
        s.addProperty("file", filename);
        logger.info("Imported {} objects to {}. Executed by {}", count, Config.getConfigParam("access_key", "scoold"), authUser.getCreatorid() + " " + authUser.getName());
        if (count > 0) {
            pc.create(s);
        }
    } catch (Exception e) {
        logger.error("Failed to import " + filename, e);
        return "redirect:" + ADMINLINK + "?error=true&imported=" + count;
    }
    return "redirect:" + ADMINLINK + "?success=true&imported=" + count;
}
Also used : SIGNINLINK(com.erudika.scoold.ScooldServer.SIGNINLINK) Question(com.erudika.scoold.core.Question) RequestParam(org.springframework.web.bind.annotation.RequestParam) Arrays(java.util.Arrays) Webhook(com.erudika.para.core.Webhook) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) ParaClient(com.erudika.para.client.ParaClient) StringUtils(org.apache.commons.lang3.StringUtils) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) Model(org.springframework.ui.Model) Locale(java.util.Locale) Map(java.util.Map) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ParseException(java.text.ParseException) Config(com.erudika.para.core.utils.Config) ZipEntry(java.util.zip.ZipEntry) ScooldUtils(com.erudika.scoold.utils.ScooldUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) ParaObject(com.erudika.para.core.ParaObject) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ConfigValue(com.typesafe.config.ConfigValue) MediaType(org.springframework.http.MediaType) Set(java.util.Set) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) UUID(java.util.UUID) JsonMapper(com.fasterxml.jackson.databind.json.JsonMapper) SignedJWT(com.nimbusds.jwt.SignedJWT) Collectors(java.util.stream.Collectors) Comment(com.erudika.scoold.core.Comment) List(java.util.List) Tag(com.erudika.para.core.Tag) Optional(java.util.Optional) ADMINLINK(com.erudika.scoold.ScooldServer.ADMINLINK) App(com.erudika.para.core.App) Sysprop(com.erudika.para.core.Sysprop) ZipOutputStream(java.util.zip.ZipOutputStream) ParaObjectUtils(com.erudika.para.core.utils.ParaObjectUtils) ZipInputStream(java.util.zip.ZipInputStream) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) Pager(com.erudika.para.core.utils.Pager) Controller(org.springframework.stereotype.Controller) ArrayList(java.util.ArrayList) HOMEPAGE(com.erudika.scoold.ScooldServer.HOMEPAGE) Inject(javax.inject.Inject) LinkedHashMap(java.util.LinkedHashMap) MapperFeature(com.fasterxml.jackson.databind.MapperFeature) HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterInputStream(java.io.FilterInputStream) GetMapping(org.springframework.web.bind.annotation.GetMapping) LinkedList(java.util.LinkedList) Logger(org.slf4j.Logger) Post(com.erudika.scoold.core.Post) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) User(com.erudika.para.core.User) Utils(com.erudika.para.core.utils.Utils) DateUtils(org.apache.commons.lang3.time.DateUtils) TimeUnit(java.util.concurrent.TimeUnit) HttpStatus(org.springframework.http.HttpStatus) Reply(com.erudika.scoold.core.Reply) MultipartFile(org.springframework.web.multipart.MultipartFile) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) InputStream(java.io.InputStream) FilterInputStream(java.io.FilterInputStream) ZipInputStream(java.util.zip.ZipInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) Profile(com.erudika.scoold.core.Profile) LinkedList(java.util.LinkedList) ParseException(java.text.ParseException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) ZipInputStream(java.util.zip.ZipInputStream) ParaObject(com.erudika.para.core.ParaObject) Sysprop(com.erudika.para.core.Sysprop) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ParaObject(com.erudika.para.core.ParaObject) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 24 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project zhcet-web by zhcet-amu.

the class CoursesController method getCourses.

@GetMapping
public String getCourses(Model model, @PathVariable Department department, @RequestParam(value = "all", required = false) Boolean all) {
    ErrorUtils.requireNonNullDepartment(department);
    // Determine if only active courses have to be should
    boolean active = !(all != null && all);
    model.addAttribute("page_description", "View and manage courses for the Department");
    model.addAttribute("department", department);
    model.addAttribute("page_title", "Courses : " + department.getName() + " Department");
    model.addAttribute("page_subtitle", "Course Management");
    model.addAttribute("page_path", getPath(department));
    model.addAttribute("all", !active);
    List<FloatedCourse> floatedCourses = floatedCourseService.getCurrentFloatedCourses(department);
    List<Course> courses = courseService.getAllActiveCourse(department, active);
    // Add meta tag and no of registrations to each course
    for (FloatedCourse floatedCourse : floatedCourses) {
        Stream.of(floatedCourse).map(FloatedCourse::getCourse).map(courses::indexOf).filter(index -> index != -1).map(courses::get).findFirst().ifPresent(course -> {
            course.setMeta("Floated");
            course.setRegistrations(floatedCourse.getCourseRegistrations().size());
        });
    }
    SortUtils.sortCourses(courses);
    model.addAttribute("courses", courses);
    return "department/courses";
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) PathChain(amu.zhcet.common.page.PathChain) Department(amu.zhcet.data.department.Department) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Controller(org.springframework.stereotype.Controller) CourseService(amu.zhcet.data.course.CourseService) Course(amu.zhcet.data.course.Course) ErrorUtils(amu.zhcet.core.error.ErrorUtils) Slf4j(lombok.extern.slf4j.Slf4j) Model(org.springframework.ui.Model) List(java.util.List) FloatedCourse(amu.zhcet.data.course.floated.FloatedCourse) Stream(java.util.stream.Stream) Path(amu.zhcet.common.page.Path) SortUtils(amu.zhcet.common.utils.SortUtils) GetMapping(org.springframework.web.bind.annotation.GetMapping) DepartmentController(amu.zhcet.core.admin.department.DepartmentController) Comparator(java.util.Comparator) FloatedCourseService(amu.zhcet.data.course.floated.FloatedCourseService) FloatedCourse(amu.zhcet.data.course.floated.FloatedCourse) Course(amu.zhcet.data.course.Course) FloatedCourse(amu.zhcet.data.course.floated.FloatedCourse) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 25 with RequestParam

use of org.springframework.web.bind.annotation.RequestParam in project mica2 by obiba.

the class SignController method signup.

@GetMapping("/signup")
public ModelAndView signup(HttpServletRequest request, @RequestParam(value = "redirect", required = false) String redirect, @CookieValue(value = "NG_TRANSLATE_LANG_KEY", required = false, defaultValue = "en") String locale, @RequestParam(value = "language", required = false) String language) {
    if (!micaConfigService.getConfig().isSignupEnabled())
        return new ModelAndView("redirect:" + micaConfigService.getContextPath() + "/");
    ModelAndView mv = new ModelAndView("signup");
    String lang = getLang(locale, language);
    List<OidcProvider> providers = getOidcProviders(lang, true).stream().map(o -> new OidcProvider(o, getOidcSignupUrl(o.getName(), request, redirect))).collect(Collectors.toList());
    mv.getModel().put("oidcProviders", providers);
    mv.getModel().put("authConfig", getAuthConfiguration());
    return mv;
}
Also used : RequestParam(org.springframework.web.bind.annotation.RequestParam) OidcProvider(org.obiba.mica.web.controller.domain.OidcProvider) Controller(org.springframework.stereotype.Controller) Collectors(java.util.stream.Collectors) UserAuthService(org.obiba.mica.core.service.UserAuthService) CookieValue(org.springframework.web.bind.annotation.CookieValue) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) ModelAndView(org.springframework.web.servlet.ModelAndView) JSONException(org.json.JSONException) HttpServletRequest(javax.servlet.http.HttpServletRequest) URLEncoder(java.net.URLEncoder) List(java.util.List) Lists(com.google.common.collect.Lists) JSONObject(org.json.JSONObject) OIDCAuthProviderSummary(org.obiba.oidc.OIDCAuthProviderSummary) MicaConfigService(org.obiba.mica.micaConfig.service.MicaConfigService) AgateServerConfigService(org.obiba.mica.core.service.AgateServerConfigService) GetMapping(org.springframework.web.bind.annotation.GetMapping) AuthConfiguration(org.obiba.mica.web.controller.domain.AuthConfiguration) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ModelAndView(org.springframework.web.servlet.ModelAndView) OidcProvider(org.obiba.mica.web.controller.domain.OidcProvider) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

RequestParam (org.springframework.web.bind.annotation.RequestParam)72 List (java.util.List)56 PathVariable (org.springframework.web.bind.annotation.PathVariable)52 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)49 Collectors (java.util.stream.Collectors)47 IOException (java.io.IOException)37 HttpServletRequest (javax.servlet.http.HttpServletRequest)35 HttpServletResponse (javax.servlet.http.HttpServletResponse)35 Autowired (org.springframework.beans.factory.annotation.Autowired)34 HttpStatus (org.springframework.http.HttpStatus)31 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)31 Map (java.util.Map)30 GetMapping (org.springframework.web.bind.annotation.GetMapping)30 MediaType (org.springframework.http.MediaType)28 Controller (org.springframework.stereotype.Controller)28 RestController (org.springframework.web.bind.annotation.RestController)28 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)27 Set (java.util.Set)21 RequestBody (org.springframework.web.bind.annotation.RequestBody)21 ArrayList (java.util.ArrayList)20