@RequestMapping(path = "/oauthmock", method = RequestMethod.GET) public ResponseEntity<String> getOAuthMock(@CookieValue("_oauth2_proxy") String oAuthToken) { if (StringUtils.isEmpty(mockOAuth) || !mockOAuth.equals("true")) { return new ResponseEntity<>(new StatusJSON("mocking disabled").getJSON().toString(), HttpStatus.LOCKED); } if (userRepository.findByMail(sessionService.extractMail(oAuthToken)) != null) { return new ResponseEntity<>(new StatusJSON("ok").getJSON().toString(), HttpStatus.ACCEPTED); } return new ResponseEntity<>(new StatusJSON("forbidden").getJSON().toString(), HttpStatus.FORBIDDEN); }
@Override @RequestMapping(value = ApiConfig.PROVIDERS_BASE + "/schema", method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public String getRelationships( @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchProviderException, NoSuchSessionException { GenerateSchema drawer = new GenerateSchema(); List<Class<? extends Item>> items = new ArrayList<>(); if (rateLimiter.tryAcquire()) { Reflections reflections = new Reflections("com"); Set<Class<? extends Item>> subTypes = reflections.getSubTypesOf(Item.class); for (Class<? extends Item> class1 : subTypes) { items.add(class1); } } Session session = modelValidator.validateSession(sessionId, response); return drawer.process(stitcher, items, session.getProviders().keySet()); }
@GetMapping("/signup") public RedirectView signUp(WebRequest webRequest, @CookieValue(name = "NG_TRANSLATE_LANG_KEY", required = false, defaultValue = "\"en\"") String langKey) { String providerId = null; try { Connection<?> connection = providerSignInUtils.getConnectionFromSession(webRequest); providerId = connection.getKey().getProviderId(); socialService.createSocialUser(connection, langKey.replace("\"", "")); return redirect(URIBuilder .fromUri(TenantUtil.getApplicationUrl() + "/social-register/" + connection.getKey().getProviderId()) .queryParam("success", "true").build().toString()); } catch (Exception e) { log.error("Exception creating social user: ", e); return redirectOnError(providerId); } }
/** * 详情. */ @RequestMapping("disk-view") public String view( @RequestParam("id") Long id, @CookieValue(value = "share", required = false) String sharePassword, Model model) { DiskShare diskShare = diskShareManager.get(id); if ("private".equals(diskShare.getShareType())) { if (!diskShare.getSharePassword().equals(sharePassword)) { return "disk/disk-code"; } } model.addAttribute("diskShare", diskShare); return "disk/disk-view"; }
@ApiOperation(value = "session/user", nickname = "get session user", notes = "get session user") @ApiResponses({ @ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 500, message = "Failure") }) @ApiImplicitParams({ @ApiImplicitParam(name = "search", value = "Name to search", paramType = "query"), @ApiImplicitParam(name = "exclude_hidden", value = "Do not return hidden skills", paramType = "query", defaultValue = "true"), @ApiImplicitParam(name = "count", value = "Limit the number of skills to find", paramType = "query"), }) @RequestMapping(path = "/session/user", method = RequestMethod.GET) public ResponseEntity<String> getCurrentUser(@CookieValue("_oauth2_proxy") String oAuthToken) { logger.debug("Getting user from session {}", oAuthToken); User user = sessionService.getUserByToken(oAuthToken); if (user == null) { return new ResponseEntity<>(new StatusJSON("no current session").toString(), HttpStatus.UNAUTHORIZED); } return new ResponseEntity<>(user.toJSON().toString(), HttpStatus.OK); }
@RequestMapping(value = "/admin/printSecrets", method = RequestMethod.GET) public String doGetPrintSecrets(@CookieValue(value = "auth", defaultValue = "notset") String auth, HttpServletResponse response, HttpServletRequest request) throws Exception { if (request.getSession().getAttribute("auth") == null) { return fail; } String authToken = request.getSession().getAttribute("auth").toString(); if(!isAdmin(authToken)) { return fail; } ClassPathResource cpr = new ClassPathResource("static/calculations.csv"); try { byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream()); response.getOutputStream().println(new String(bdata, StandardCharsets.UTF_8)); return null; } catch (IOException ex) { ex.printStackTrace(); // redirect to / return fail; } }
@Override @RequestMapping(value = ApiConfig.PROVIDERS_BASE, method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public ProviderList getProviders( @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) { if (rateLimiter.tryAcquire()) { sessionManager.getSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Get all providers"); } ProviderList providerList = new ProviderList(); providerList.getProviders().addAll(adapterManager.getProviders()); return providerList; } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.PROVIDERS_BASE + "/{providerType}", method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public ProviderList getProviders(@PathVariable final String providerType, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) { if (rateLimiter.tryAcquire()) { if (providerType == null || StringUtils.isBlank(providerType) || providerType.equals("null")) { throw new BadRequestException("Empty provider type parameter"); } sessionManager.getSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Get all providers for type " + providerType); } ProviderList providerList = new ProviderList(); providerList.getProviders().addAll(adapterManager.getProviders(providerType)); return providerList; } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.PROVIDERS_BASE + "/{providerType}/{providerId}", method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public Provider getProvider(@PathVariable final String providerType, @PathVariable final String providerId, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchProviderException { if (rateLimiter.tryAcquire()) { sessionManager.getSession(sessionId, response); modelValidator.validateProviderType(providerType); modelValidator.validateProviderId(providerId); if (LOG.isDebugEnabled()) { LOG.debug("Get provider " + providerType + Provider.PROV_SEPARATOR + providerId); } return getProvider(providerType, providerId); } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.PATTERNS_BASE, method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public PatternDefinitionList getPatterns( @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchSessionException { if (rateLimiter.tryAcquire()) { Session session = modelValidator.validateSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Get all patterns for all providers"); } synchronized (session) { PatternDefinitionList patternDefinitionList = new PatternDefinitionList(); List<PatternDefinition> patterns = patternDefinitionList.getPatterns(); patterns.addAll(tapestryManager.getAllPatterns()); return patternDefinitionList; } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.PATTERNS_BASE + "/{patternId}", method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public PatternDefinition getPattern(@PathVariable final String patternId, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws InterruptedException, NoSuchSessionException, NoSuchPatternException { if (rateLimiter.tryAcquire()) { if (StringUtils.isBlank(patternId)) { throw new BadRequestException("Empty pattern id parameter"); } Session session = modelValidator.validateSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Get pattern with id: " + patternId); } synchronized (session) { PatternDefinition patternDefinition = tapestryManager.getPattern(patternId); return patternDefinition; } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.TAPESTRY_BASE + "/{tapestryId}", method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public TapestryDefinition getTapestryDefinition(@PathVariable final String tapestryId, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchSessionException, NoSuchTapestryDefinitionException { if (rateLimiter.tryAcquire()) { Session session = modelValidator.validateSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Get tapestry definition with id: " + tapestryId); } synchronized (session) { modelValidator.validateTapestryDefinition(tapestryId); TapestryDefinition tapestryDefinition = tapestryManager.getTapestryDefinition(session); // querying with any tapestryId would work as well as the tapestryManager works // based on session, not id. return tapestryDefinition; } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.TAPESTRY_BASE, method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public TapestryDefinitionList getTapestryDefinitions( @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchSessionException { if (rateLimiter.tryAcquire()) { Session session = modelValidator.validateSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Get all tapestry definitions"); } synchronized (session) { // Ultimately, this needs to be changed based on user rather than session. TapestryDefinition tapestryDefinition = tapestryManager.getTapestryDefinition(session); ArrayList<TapestryDefinition> tapestryDefinitions = new ArrayList<>(1); if (tapestryDefinition != null) { tapestryDefinitions.add(tapestryDefinition); } return new TapestryDefinitionList(tapestryDefinitions); } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.TAPESTRY_BASE + "/{tapestryId}", method = RequestMethod.DELETE, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public void deleteTapestryDefinition(@PathVariable final String tapestryId, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchSessionException, NoSuchTapestryDefinitionException { if (rateLimiter.tryAcquire()) { Session session = modelValidator.validateSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Delete tapestry definition with id: " + tapestryId); } synchronized (session) { modelValidator.validateTapestryDefinition(tapestryId); // Ultimately, this needs to be a specific tapestry not based on sesssion. tapestryManager.clearTapestryDefinition(session); } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.TAPESTRY_BASE, method = RequestMethod.DELETE, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public void deleteTapestryDefinitions( @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchSessionException { if (rateLimiter.tryAcquire()) { Session session = modelValidator.validateSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Delete all tapestry definitions"); } synchronized (session) { // Ultimately, this needs to invoke a method in tapestry manager to remove all // tapestries rather than the only one bound with a session. tapestryManager.clearTapestryDefinition(session); } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.ACTION_RESULTS_BASE + "/{actionResultId}", method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public ActionResult getActionResult(@PathVariable final String actionResultId, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws InvalidActionSpecificationException, NoSuchProviderException, NoSuchSessionException, NoSuchItemTypeException { if (rateLimiter.tryAcquire()) { if (actionResultId == null) { throw new BadRequestException("actionResultId cannot be null"); } UUID uuid = UUID.fromString(actionResultId); Session session = modelValidator.validateSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Lookup action result " + actionResultId + " for session " + sessionId); } synchronized (session) { if (LOG.isDebugEnabled()) { LOG.debug("Assigned session " + session.getId()); } ActionResult actionResult = actionManager.getActionResult(session, uuid); return actionResult; } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.ITEM_TYPE + "/{providerType}/{providerId}", method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public ItemTypeList getItemTypes(@PathVariable final String providerType, @PathVariable final String providerId, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchProviderException { if (rateLimiter.tryAcquire()) { sessionManager.getSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Get all itemTypes for a provider"); } modelValidator.validateProviderType(providerType); modelValidator.validateProviderId(providerId); Provider provider = getProvider(providerType, providerId); return new ItemTypeList(new HashSet<>(itemTypeManager.getItemTypes(provider))); } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.ITEM_TYPE + "/{providerType}", method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public ItemTypeList getItemTypes(@PathVariable final String providerType, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) { if (rateLimiter.tryAcquire()) { modelValidator.validateProviderType(providerType); sessionManager.getSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Get all itemTypes for a provider type"); } return new ItemTypeList(new HashSet<>(itemTypeManager.getItemTypes(providerType))); } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
/** * 用户注册接口,根据实体传入参数 * * @param auth * @return */ @RequestMapping("/register.do") @CrossOrigin public FrontEndResponse register(@CookieValue(value = "token", defaultValue = "empty") String token, AuthenticationEntity auth, HttpServletResponse response, HttpServletRequest request) { /*新增用户,新增token,返回用户名*/ Map map = authService.register(auth); if ((boolean) map.get("success")) { Cookie responseCookie = new Cookie("token", (String) map.get("token")); responseCookie.setPath("/"); responseCookie.setMaxAge(20 * 60); response.addCookie(responseCookie); AuthenticationEntity authenticationEntityDB = (AuthenticationEntity) map.get("auth"); return new FrontEndResponse(true, authenticationEntityDB.getUserName()); } else { return new FrontEndResponse(false, "Email已存在"); } }
@RequestMapping({ "/", "/login", "repositories", "project-requests", "workbench", "settings" }) @ResponseBody ModelAndView getIndex(HttpServletRequest httpServletRequest, @CookieValue(value = "locale", required = false, defaultValue = "en") String localeCookieValue) throws MalformedURLException, IOException { ModelAndView index = new ModelAndView("index"); index.addObject("locale", getValidLocaleFromCookie(localeCookieValue)); index.addObject("csrfToken", csrfTokenController.getCsrfToken(httpServletRequest)); index.addObject("username", getUsername()); index.addObject("contextPath", contextPath); return index; }
@PostMapping(value = "/polls/vote/{slug}") public String voteOptions(@CookieValue(value = "pollistics-voted", defaultValue = "") String originalCookie, @PathVariable String slug, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttrs) throws UnsupportedEncodingException { String encodedSlug = URLEncoder.encode(slug, "UTF-8"); Poll p = pollService.getPoll(slug); // already voted if (originalCookie.contains(slug)) { redirectAttrs.addFlashAttribute("message", "You already voted for this poll"); redirectAttrs.addFlashAttribute("message_type", "error"); response.setStatus(403); return "redirect:/" + encodedSlug + "/results"; } else { response.addCookie(CookieBuilder.getVotedCookie(originalCookie, slug)); String option = request.getParameter("option"); pollService.voteOption(p, option); return "redirect:/" + encodedSlug + "/results"; } }
/** * Admin Home Page. * * NOTE: THIS FUNCTION IS A TEMPORARY FUNCTION TO DISPLAY THE ADMIN HOME PAGE * IT MUST BE MODIFIED BEFORE IT IS INTEGREATED WITH THE BACK-END CODE * * @param model the model * @param request the request * @param recentVisits the recent visits * @return the string */ @RequestMapping(value = "adminHome.html") public String adminHome(Model model, HttpServletRequest request, @CookieValue(value = "recent_visit", required = false) List<String> recentVisits) { List<RecentPatientDto> recentPatientDtos=new ArrayList<RecentPatientDto>(); if(recentVisits!=null) recentPatientDtos=patientService.findRecentPatientDtosById(recentVisits); String notify = request.getParameter("notify"); BasicPatientAccountDto basicPatientAccountDto = new BasicPatientAccountDto(); model.addAttribute("notifyevent", notify); model.addAttribute(basicPatientAccountDto); model.addAttribute("recentVisits", recentPatientDtos); return "views/Administrator/adminHome"; }
/** * Admin Patient View Page. * * NOTE: THIS FUNCTION IS A TEMPORARY FUNCTION TO DISPLAY THE ADMIN PATIENT VIEW PAGE. * IT MUST BE MODIFIED BEFORE IT IS INTEGREATED WITH THE BACK-END CODE * * @param model the model * @param request the request * @param response the response * @param recentVisits the recent visits * @return the string */ @RequestMapping(value = "adminPatientView.html") public String adminPatientView(Model model, HttpServletRequest request, HttpServletResponse response, @CookieValue(value = "recent_visit", required = false) List<String> recentVisits) { if(request.getParameter("id")!=null){ response.addCookie(new Cookie("recent_visit", buildRecentPatientsCookie(recentVisits,request.getParameter("id")))); long patientId=Long.parseLong(request.getParameter("id")); PatientProfileDto patientProfileDto=patientService.findPatient((long) patientId); List<ConsentListDto> consentListDto=consentService.findAllConsentsDtoByPatient((long) patientId); model.addAttribute("patientProfileDto", patientProfileDto); model.addAttribute("consentListDto", consentListDto); populateLookupCodes(model); return "views/Administrator/adminPatientView"; }else{ return "redirect:/Administrator/adminHome.html"; } }
@RequestMapping(value = RequestMappings.SEND_DINNERROUTES_MAIL, method = RequestMethod.GET) public String showSendDinnerRoutesForm( HttpServletRequest request, @PathVariable(RequestMappings.ADMIN_URL_UUID_MARKER) String uuid, @CookieValue(value = MailServerSettingsTransformer.MAILSERVER_SETTINGS_COOKIE_NAME, required = false) String mailServerSettings, Model model, RedirectAttributes redirectAttributes, Locale locale) { adminValidator.validateUuid(uuid); SendDinnerRoutesModel sendDinnerRoutesModel = SendDinnerRoutesModel.createWithDefaultMessageTemplate(messages, locale); mailServerSettingsTransformer.enrichModelWithMailServerSettings(uuid, sendDinnerRoutesModel, mailServerSettings); bindCommonMailAttributesAndLoadTeamDisplayMap(model, sendDinnerRoutesModel, uuid, communicationService.findLastDinnerRouteMailReport(uuid)); Map<String, String> teamDisplayMap = sendDinnerRoutesModel.getEntityDisplayMap(); if (teamDisplayMap.size() == 0) { LOGGER.warn("Tried to call send dinner route mails for dinner {} without any existing teams", uuid); return generateStatusPageRedirect(RequestMappings.ADMIN_OVERVIEW, uuid, redirectAttributes, new SimpleStatusMessage( SimpleStatusMessage.WARN_STATUS, messages.getMessage("error.no.teams", null, locale))); } // Select all Teams: sendDinnerRoutesModel.setSelectedEntities(new ArrayList<String>(teamDisplayMap.keySet())); return getFullViewName("sendDinnerRoutesForm"); }
@RequestMapping(value = RequestMappings.SEND_PARTICIPANT_MAILS, method = RequestMethod.GET) public String showSendParticipantsForm( HttpServletRequest request, @PathVariable(RequestMappings.ADMIN_URL_UUID_MARKER) String uuid, @CookieValue(value = MailServerSettingsTransformer.MAILSERVER_SETTINGS_COOKIE_NAME, required = false) String mailServerSettings, Model model, RedirectAttributes redirectAttributes, Locale locale) { adminValidator.validateUuid(uuid); BaseSendMailsModel sendMailsModel = new BaseSendMailsModel(); mailServerSettingsTransformer.enrichModelWithMailServerSettings(uuid, sendMailsModel, mailServerSettings); sendMailsModel.setMessage(messages.getMessage("message.template.participants", null, locale)); bindAndSetupParticipantMailAttributes(model, sendMailsModel, uuid, locale); Map<String, String> participantDisplayMap = sendMailsModel.getEntityDisplayMap(); if (participantDisplayMap.size() == 0) { LOGGER.warn("Tried to call send participant mails for dinner {} without any existing participants", uuid); return generateStatusPageRedirect(RequestMappings.ADMIN_OVERVIEW, uuid, redirectAttributes, new SimpleStatusMessage( SimpleStatusMessage.WARN_STATUS, messages.getMessage("error.no.participants", null, locale))); } // Select all participants: sendMailsModel.setSelectedEntities(new ArrayList<String>(participantDisplayMap.keySet())); return getFullViewName("sendParticipantsForm"); }
@ResponseBody @RequestMapping("/add") public Object createOrder(@CookieValue(value="cart", required= false, defaultValue="") String cart , @RequestParam("addressId") Long addressId , @RequestParam("deliverTime") String deliverTime) throws Exception { Result<Object> result = new Result<Object>(); RequestData data = requestContextHolder.getRequestData(); @SuppressWarnings("unchecked") Map<Long, Integer> map = new ObjectMapper().readValue(cart, Map.class); if(map == null || map.size() == 0) throw new ServiceException(ConstantsError.InvalidArguemnt); List<ProductVO> list = productService.getProductList(data.getUserId(), new ArrayList<Long>(map.keySet())); if(list == null || list.size() == 0) throw new ServiceException(ConstantsError.InvalidArguemnt); StringBuilder sb = new StringBuilder(); Long totalPrice = 0L; for(int i = 0 ; i < list.size() ; i++) { ProductVO p = list.get(i); int num = map.get(String.valueOf(p.getId())); totalPrice += (p.getPrice()*num); sb.append(p.getTitle()).append("(").append(num).append(p.getUnit()).append(")").append(","); } sb.deleteCharAt(sb.length()-1); orderService.addOrder(data.getUserId() , data.getOpenId() , addressId , sb.toString(), deliverTime , totalPrice); return result; }
@RequestMapping(value = "/change-definition", method = { RequestMethod.GET, RequestMethod.POST }) public String changeDefinition(@Nonnull final HttpServletResponse response, @Nullable @CookieValue(required = false, value = TEST_DEFINITION_URL_COOKIE) String testDefnUrlCookie, @Nullable @RequestParam(required = false, value = TEST_DEFINITION_URL_PARAM) String testDefnUrlParam) { final String definitionUrl; if (!Strings.isNullOrEmpty(testDefnUrlParam)) { definitionUrl = testDefnUrlParam; response.addCookie(createCookie(TEST_DEFINITION_URL_COOKIE, definitionUrl, Integer.MAX_VALUE)); } else { definitionUrl = DefinitionManager.DEFAULT_DEFINITION; if (testDefnUrlCookie != null) { // clear cookie response.addCookie(createCookie(TEST_DEFINITION_URL_COOKIE, "", -1)); } } definitionManager.load(definitionUrl, true); return "redirect:/"; }
@Override protected void initParameterAnnotationMgr() { super.initParameterAnnotationMgr(); parameterAnnotationMgr.register(CookieValue.class, new CookieValueAnnotationProcessor()); parameterAnnotationMgr.register(PathVariable.class, new PathVariableAnnotationProcessor()); parameterAnnotationMgr.register(RequestBody.class, new RequestBodyAnnotationProcessor()); parameterAnnotationMgr.register(RequestHeader.class, new RequestHeaderAnnotationProcessor()); parameterAnnotationMgr.register(RequestParam.class, new RequestParamAnnotationProcessor()); parameterAnnotationMgr.register(RequestAttribute.class, new RequestAttributeAnnotationProcessor()); parameterAnnotationMgr.register(RequestPart.class, new RequestPartAnnotationProcessor()); }
@GetMapping("/{token:.+}") public ResponseEntity validateToken(@CookieValue("time") String time, @RequestHeader("Authorization") String[] authorization, @PathVariable String token, @RequestParam String url) { String temp = tokens.get(token); String auth = authorization[0]; if (auth.equals("dummy")) { auth = authorization[1]; } if (temp.equals(time) && auth.equals(token + time + url)) { return ResponseEntity.ok().build(); } else { return ResponseEntity.badRequest().build(); } }
@RequestMapping(value={"", "/", "tasks"}) public String index(@CookieValue(value = "host", defaultValue = "") String host, @CookieValue(value = "slacktoken", defaultValue = "") String slacktoken, Model model) throws SchedulerException { ecs.storeFromCoockies(host, slacktoken); if (ecs.getConfiguration().getHost() == null) { model.addAttribute("message", "The receiving endpoint needs to be configured."); } else { model.addAttribute("message", null); } model.addAttribute("tasks", jobUtility.getTasks()); return "tasks"; }
@Override @RequestMapping(value = ApiConfig.PROVIDERS_BASE + "/{providerType}/{providerId}", method = RequestMethod.POST, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public PatternDefinitionList logProvider(@PathVariable final String providerType, @PathVariable final String providerId, @RequestParam final String operation, @RequestBody(required = false) final Credentials creds, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchProviderException, SessionAlreadyExistsException, NoSuchSessionException, UserAlreadyConnectedException, NoSuchUserException { if (rateLimiter.tryAcquire()) { if (StringUtils.isBlank(providerType)) { throw new BadRequestException("Empty provider type parameter"); } if (StringUtils.isBlank(providerId)) { throw new BadRequestException("Empty provider id parameter"); } if (StringUtils.isBlank(operation)) { throw new BadRequestException("Empty operation parameter"); } Provider provider = getProvider(providerType, providerId); if (provider == null) { throw new NoSuchProviderException(providerType, providerId); } Session session = sessionManager.getSessionWithSessionId(sessionId, response); synchronized (session) { return handleLogOperation(provider, session, operation, creds, response); } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.TAPESTRY_BASE, method = RequestMethod.POST, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public TapestryDefinition createTapestryDefinition(@RequestBody final TapestryDefinition tapestryDefinition, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchSessionException, NoSuchTapestryDefinitionException, NoSuchAggregationException, NoSuchQueryDefinitionException, LogicalIdAlreadyExistsException, OperationException, NoSuchThreadDefinitionException, InvalidQueryInputException, InvalidQueryParametersException, NoSuchItemTypeException, ItemPropertyNotFound, RelationPropertyNotFound, ThreadDeletedByDynAdapterUnload { if (rateLimiter.tryAcquire()) { Session session = modelValidator.validateSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Create tapestry definition " + tapestryDefinition + " with session " + sessionId); } synchronized (session) { modelValidator.validateTapestryDefinition(tapestryDefinition, true); return setOrUpdateTapestryDefinition(session, tapestryDefinition); } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.TAPESTRY_BASE + "/{tapestryId}/threads/{threadId}/results", method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public QueryResult getQueryResult(@PathVariable final String tapestryId, @PathVariable final String threadId, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchSessionException, NoSuchThreadDefinitionException, NoSuchTapestryDefinitionException, NoSuchQueryDefinitionException, NoSuchAggregationException, LogicalIdAlreadyExistsException, InvalidQueryInputException, OperationException, ItemPropertyNotFound, RelationPropertyNotFound, ThreadDeletedByDynAdapterUnload, NoSuchItemTypeException, InvalidQueryParametersException, AccessExpiredException, JsonProcessingException, NoSuchProviderException { if (rateLimiter.tryAcquire()) { Session session = modelValidator.validateSessionAndAccess(sessionId, response, tapestryId, threadId); if (LOG.isDebugEnabled()) { LOG.debug("Query a thread with tapestryId: " + tapestryId + " and threadId: " + threadId + " with session ID " + sessionId); } synchronized (session) { modelValidator.validateTapestryDefinition(tapestryId); modelValidator.validateThreadDefinition(threadId); return queryManager.getThread(session, threadId, false); } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.TAPESTRY_BASE + "/{tapestryId}/threads/results", method = RequestMethod.POST, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public QueryResultList getQueryResults(@PathVariable final String tapestryId, @RequestBody final List<String> threadIds, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws NoSuchSessionException, NoSuchThreadDefinitionException, NoSuchTapestryDefinitionException, NoSuchQueryDefinitionException, NoSuchAggregationException, LogicalIdAlreadyExistsException, InvalidQueryInputException, OperationException, ItemPropertyNotFound, RelationPropertyNotFound, ThreadDeletedByDynAdapterUnload, AccessExpiredException, JsonProcessingException, NoSuchProviderException { if (rateLimiter.tryAcquire()) { Session session = modelValidator.validateSessionAndAccess(sessionId, response, tapestryId); if (LOG.isDebugEnabled()) { LOG.debug("Query a set of threads with tapestryId " + tapestryId + " and threadIds in: " + threadIds.toString() + " with session ID " + sessionId); } synchronized (session) { modelValidator.validateTapestryDefinition(tapestryId); List<QueryResult> queryResults = new ArrayList<>(threadIds.size()); for (String threadId : threadIds) { queryResults.add(queryManager.getThread(session, threadId, false)); } return new QueryResultList(queryResults); } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.ACTIONS_BASE, method = RequestMethod.POST, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public ActionResult doAction(@RequestBody final Action action, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) throws InvalidActionSpecificationException, NoSuchProviderException, NoSuchSessionException, NoSuchItemTypeException { if (rateLimiter.tryAcquire()) { if (action == null) { throw new BadRequestException("Action object cannot be null"); } Session session = modelValidator.validateSession(sessionId, response); if (LOG.isDebugEnabled()) { LOG.debug("Execute action " + action + " for session " + sessionId); } synchronized (session) { if (LOG.isDebugEnabled()) { LOG.debug("Assigned session " + session.getId()); } ActionResult actionResult = actionManager.doAction(session, action); return actionResult; } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.ITEM_TYPE, method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public ItemTypeList getItemTypes( @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, @RequestParam(value = "current", required = false) final boolean current, final HttpServletResponse response) throws NoSuchSessionException { if (rateLimiter.tryAcquire()) { if (LOG.isDebugEnabled()) { LOG.debug("Get all itemTypes for all provider types"); } Set<ItemType> itemTypes = new HashSet<>(); ItemTypeList itemTypeList = new ItemTypeList(); Session session = modelValidator.validateSession(sessionId, response); synchronized (session) { if (current) { for (Provider provider : session.getProviders().keySet()) { try { itemTypes.addAll(itemTypeManager.getItemTypes(provider)); } catch (NoSuchProviderException e) { } } } else { itemTypes.addAll(itemTypeManager.getItemTypes()); } itemTypeList.setItemTypes(itemTypes); return itemTypeList; } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
@Override @RequestMapping(value = ApiConfig.OPERATION, method = RequestMethod.GET, headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES}) @ResponseBody public OperationList getOperations(@RequestParam(value = "itemType", required = false) final String itemType, @RequestParam(value = "providerType", required = false) final String providerType, @RequestParam(value = "declaredBy", required = false) final String declaredBy, @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId, final HttpServletResponse response) { if (rateLimiter.tryAcquire()) { sessionManager.getSession(sessionId, response); if (!StringUtils.isBlank(providerType) && declaredBy == null && itemType == null) { return getOperationsOperateOn(providerType); } else if (providerType == null && !StringUtils.isBlank(declaredBy) && itemType == null) { return getOperationsDeclaredBy(declaredBy); } else if (!StringUtils.isBlank(itemType) && providerType == null && declaredBy == null) { return getOperationsByItemType(itemType); } else if (itemType == null && providerType == null && declaredBy == null) { return getOperationsOperateOn(PROVIDER_ANY); } else { throw new BadRequestException( "A request parameter required, either providerType or declaredBy or itemType"); } } else { throw new ApiThrottlingException("Exceeded max number of requests per second"); } }
/** * Logout common result. * 注意一、修改、删除Cookie时,新建的Cookie除value、maxAge之外的所有属性 * 例如name、path、domain等,都要与原Cookie完全一样。否则,浏览器将视为两个不同的Cookie不予覆盖,导致修改、删除失败。 * * @param cookie the cookie * @param session the session * @param response the response * @return the common result */ @ResponseBody @RequestMapping("/logout.do") public CommonResult logout(@CookieValue("JSESSIONID") Cookie cookie, HttpSession session, HttpServletResponse response) { if (!isEmpty(cookie)) { cookie.setValue(null); cookie.setMaxAge(0); cookie.setPath("/"); response.addCookie(cookie); } session.invalidate(); return new CommonResult("注销成功",true); }
/** * 验证用户是否登录,获取用户权限; * * @param token * @param account * @param password * @param response * @return */ @RequestMapping("/loginWithToken.do") @CrossOrigin public FrontEndResponse authentication(@CookieValue(value = "token", defaultValue = "empty") String token, String account, String password, HttpServletResponse response) { TokenEntity tokenEntity = authService.isTokenValid(token); if (!token.equals("empty") && tokenEntity != null) { AuthenticationEntity authenticationEntity = authService.findOne(tokenEntity.getUserId()); authService.updateTokenValidTime(tokenEntity); return new FrontEndResponse(true, authenticationEntity.getUserName()); } else { return new FrontEndResponse(false, "token 不存在或已超期,请使用账户密码登录"); } }
@RequestMapping("EDIT") @RenderMapping public void myHandle(@RequestParam("param1") String p1, @RequestParam("param2") int p2, @RequestHeader("header1") long h1, @CookieValue("cookie1") Cookie c1, RenderResponse response) throws IOException { response.getWriter().write("test-" + p1 + "-" + p2 + "-" + h1 + "-" + c1.getValue()); }