@RequestMapping(value = "testService", method = RequestMethod.POST) public Object testService(@RequestParam(value = "ipPort", required = true) String ipPort, @RequestBody GrpcServiceTestModel model) throws Exception { String serviceUrl = "http://" + ipPort + "/service/test"; HttpPost request = new HttpPost(serviceUrl); request.addHeader("content-type", "application/json"); request.addHeader("Accept", "application/json"); try { StringEntity entity = new StringEntity(gson.toJson(model), "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); request.setEntity(entity); HttpResponse httpResponse = httpClient.execute(request); if (httpResponse.getStatusLine().getStatusCode() == 200) { String minitorJson = EntityUtils.toString(httpResponse.getEntity()); Object response = gson.fromJson(minitorJson, new TypeToken<Object>() {}.getType()); return response; } } catch (Exception e) { throw e; } return null; }
/** * Handle a POST method by creating a new Milkshake. * Queries appropriate fruit service to check for inventory and consume the fruit into the milkshake * * @param flavor to create * @return a newly created Milkshake */ @RequestMapping(method = RequestMethod.POST) public @ResponseBody Milkshake create(@RequestParam Flavor flavor) { try { FlavorProvider provider = getFlavorProvider(flavor); provider.getIngredients(); } catch (IngredientException e) { throw new HttpClientErrorException(HttpStatus.TOO_MANY_REQUESTS, e.getMessage()); } Milkshake milkshake = new Milkshake(); milkshake.setId(counter.incrementAndGet()); milkshake.setFlavor(flavor); return milkshake; }
@PostMapping("/api/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile multipartFile) { logger.debug("Single file upload!"); if (multipartFile.isEmpty()) { return new ResponseEntity("Please select a file!", HttpStatus.OK); } try { String randomPath = saveUploadedFiles(Arrays.asList(multipartFile)); return new ResponseEntity(serverAddress + "/leafer/" + randomPath, new HttpHeaders(), HttpStatus.OK); } catch (IOException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }
@GetMapping(value = "/login") public ModelAndView login( @RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { logger.info("******login(error): {} ***************************************", error); logger.info("******login(logout): {} ***************************************", logout); ModelAndView model = new ModelAndView(); if (error != null) { model.addObject("error", "Invalid username and password!"); } if (logout != null) { model.addObject("message", "You've been logged out successfully."); } model.setViewName("login"); return model; }
@RequestMapping("report-query-export") public void export(@ModelAttribute Page page, @RequestParam Map<String, Object> parameterMap, HttpServletRequest request, HttpServletResponse response) throws Exception { String userId = currentUserHolder.getUserId(); List<PropertyFilter> propertyFilters = PropertyFilter .buildFromMap(parameterMap); propertyFilters.add(new PropertyFilter("EQS_userId", userId)); page = reportQueryManager.pagedQuery(page, propertyFilters); List<ReportQuery> reportQuerys = (List<ReportQuery>) page.getResult(); TableModel tableModel = new TableModel(); tableModel.setName("report subject"); tableModel.addHeaders("id", "name"); tableModel.setData(reportQuerys); exportor.export(request, response, tableModel); }
@RequestMapping("user-status-remove") public String remove(@RequestParam("selectedItem") List<Long> selectedItem, RedirectAttributes redirectAttributes) { try { List<UserStatus> userStatuses = userStatusManager .findByIds(selectedItem); for (UserStatus userStatus : userStatuses) { userStatusChecker.check(userStatus); } userStatusManager.removeAll(userStatuses); messageHelper.addFlashMessage(redirectAttributes, "core.success.delete", "删除成功"); } catch (CheckUserStatusException ex) { logger.warn(ex.getMessage(), ex); messageHelper.addFlashMessage(redirectAttributes, ex.getMessage()); } return "redirect:/auth/user-status-list.do"; }
@RequestMapping(path = "/games") public Games searchGames(@RequestParam(value = "console") String console, @RequestParam(value = "name", required = false) String name, @RequestParam(value = "genre", required = false) String genre, @RequestParam(value = "developer", required = false) String developer, @RequestParam(value = "publisher", required = false) String publisher, @RequestParam(required = false, defaultValue = "0") int pageNumber, @RequestParam(required = false, defaultValue = "0") int pageSize) { List<SearchCriterion> searchCriteria = new ArrayList<>(); searchCriteria.add(new SearchCriterion("name", null, "like", name)); //TODO if GENRES required, a list of search criterion can be created searchCriteria.add(new SearchCriterion("genres", null, "contains", genre)); searchCriteria.add(new SearchCriterion("developer", null, "equal", developer)); searchCriteria.add(new SearchCriterion("publisher", null, "equal", publisher)); searchCriteria.add(new SearchCriterion("console", "shortName", "join", console)); return service.searchGames(searchCriteria, pageNumber, pageSize); }
@RequestMapping(value = "/activity/{id}", method = RequestMethod.PUT) public Activity update(@PathVariable Long id, @RequestBody Activity input, @RequestParam("username") String username, @RequestParam("password") String password) { validateAccountUserExists(username, password); final Activity activity = activityRepository.findOne(id); if (activity == null) { return null; } else { activity.setText(input.getText()); activity.setTitle(input.getTitle()); activity.setAuthor(input.getAuthor()); activity.setTag1(input.getTag1()); activity.setTag2(input.getTag2()); activity.setTag3(input.getTag3()); activity.setImgBase64(input.getImgBase64()); return activityRepository.save(activity); } }
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @RequestMapping(value = "/relations", method = RequestMethod.GET, params = { "toId", "toType", "relationType" }) @ResponseBody public List<EntityRelation> findByTo(@RequestParam("toId") String strToId, @RequestParam("toType") String strToType, @RequestParam("relationType") String strRelationType, @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws IoTPException { checkParameter("toId", strToId); checkParameter("toType", strToType); checkParameter("relationType", strRelationType); EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId); checkEntityId(entityId); RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); try { return checkNotNull(relationService.findByToAndType(entityId, strRelationType, typeGroup).get()); } catch (Exception e) { throw handleException(e); } }
@RequestMapping(value="/dj/simple/deployments/{dpmtId}/cis", method = RequestMethod.GET) @ResponseBody public List<CmsDpmtRecord> getDpmtRecordCis( @PathVariable long dpmtId, @RequestParam(value="updatedAfter", required = false) Long updatedAfter, @RequestParam(value="state", required = false) String state, @RequestParam(value="execorder", required = false) Integer execOrder, @RequestHeader(value="X-Cms-Scope", required = false) String scope){ if (scope != null) { CmsDeployment dpmt = djManager.getDeployment(dpmtId); scopeVerifier.verifyScope(scope, dpmt); } if (updatedAfter != null) { return djManager.getDpmtRecordCis(dpmtId, new Date(updatedAfter)); } else if (state == null && execOrder==null) { return djManager.getDpmtRecordCis(dpmtId); } else { return djManager.getDpmtRecordCis(dpmtId, state, execOrder); } }
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @RequestMapping(value = "/alarm/highestSeverity/{entityType}/{entityId}", method = RequestMethod.GET) @ResponseBody public AlarmSeverity getHighestAlarmSeverity( @PathVariable("entityType") String strEntityType, @PathVariable("entityId") String strEntityId, @RequestParam(required = false) String searchStatus, @RequestParam(required = false) String status ) throws IoTPException { checkParameter("EntityId", strEntityId); checkParameter("EntityType", strEntityType); EntityId entityId = EntityIdFactory.getByTypeAndId(strEntityType, strEntityId); AlarmSearchStatus alarmSearchStatus = StringUtils.isEmpty(searchStatus) ? null : AlarmSearchStatus.valueOf(searchStatus); AlarmStatus alarmStatus = StringUtils.isEmpty(status) ? null : AlarmStatus.valueOf(status); if (alarmSearchStatus != null && alarmStatus != null) { throw new IoTPException("Invalid alarms search query: Both parameters 'searchStatus' " + "and 'status' can't be specified at the same time!", IoTPErrorCode.BAD_REQUEST_PARAMS); } checkEntityId(entityId); try { return alarmService.findHighestAlarmSeverity(entityId, alarmSearchStatus, alarmStatus); } catch (Exception e) { throw handleException(e); } }
@RequestMapping("feedback-info-export") public void export(@ModelAttribute Page page, @RequestParam Map<String, Object> parameterMap, HttpServletRequest request, HttpServletResponse response) throws Exception { String tenantId = tenantHolder.getTenantId(); List<PropertyFilter> propertyFilters = PropertyFilter .buildFromMap(parameterMap); page = feedbackInfoManager.pagedQuery(page, propertyFilters); List<FeedbackInfo> feedbackInfos = (List<FeedbackInfo>) page .getResult(); TableModel tableModel = new TableModel(); tableModel.setName("feedbackInfo"); tableModel.addHeaders("id", "name"); tableModel.setData(feedbackInfos); exportor.export(request, response, tableModel); }
@ApiOperation(value = "Gets all foods, optionally return stats per food", notes = "Return a list of all foods", response = FoodWithStats.class, responseContainer = "List", authorizations = { @Authorization(value = "Bearer") }, tags={ "chef", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "A list of foods", response = FoodWithStats.class), @ApiResponse(code = 500, message = "An unexpected error occured.", response = FoodWithStats.class) }) @RequestMapping(value = "/foods", produces = { "application/json" }, method = RequestMethod.GET) @CrossOrigin ResponseEntity<FoodsPage> foodsGet( @ApiParam(value = "") @RequestParam(value = "stats", required = false) Boolean stats, @ApiParam(value = "Request pagination page") @RequestParam(value = "page", required = false) String page, @ApiParam(value = "Request pagination size / num of foods") @RequestParam(value = "size", required = false) String size, @ApiParam(value = "Request foodType filter") @RequestParam(value = "foodType", required = false) String foodType, @ApiParam(value = "Request archived filter") @RequestParam(value = "archived", required = false) String archived, @ApiParam(value = "Request orderBy filter") @RequestParam(value = "orderBy", required = false) String orderBy, @ApiParam(value = "Request foods version") @RequestParam(value = "foods_version", required = false) @Valid @Digits( integer=9, fraction=0 )Integer foods_version, @ApiParam(value = "Request orderBy filter") @RequestParam(value = "orderDirection", required = false) String orderDirection) throws ApiException, Exception;
@RequestMapping(value = "/project/{projectId}", method = RequestMethod.DELETE) @ResponseBody @ApiOperation( value = "Deletes a project, specified by project ID", notes = "Deletes a project with all it's items and bookmarks", produces = MediaType.APPLICATION_JSON_VALUE) @ApiResponses( value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION) }) public Result<Boolean> deleteProject(@PathVariable final long projectId, @RequestParam(name = "force", required = false, defaultValue = "false") Boolean force) throws IOException { Project deletedProject = projectManager.deleteProject(projectId, force); return Result.success(true, MessageHelper.getMessage(MessagesConstants.INFO_PROJECT_DELETED, deletedProject .getId(), deletedProject.getName())); }
@RequestMapping(value = "/generator/preview", method = RequestMethod.POST) public String preview(@RequestParam(value = "schema") String schema, @RequestParam(value = "targetpackage") String targetpackage, @RequestParam(value = "sourcetype", required = false) final String sourcetype, @RequestParam(value = "annotationstyle", required = false) final String annotationstyle, @RequestParam(value = "usedoublenumbers", required = false) final boolean usedoublenumbers, @RequestParam(value = "includeaccessors", required = false) final boolean includeaccessors, @RequestParam(value = "includeadditionalproperties", required = false) final boolean includeadditionalproperties, @RequestParam(value = "propertyworddelimiters", required = false) final String propertyworddelimiters, @RequestParam(value = "classname") String classname) throws IOException { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JCodeModel codegenModel = getCodegenModel(schema, targetpackage, sourcetype, annotationstyle, usedoublenumbers, includeaccessors, includeadditionalproperties, propertyworddelimiters, classname); codegenModel.build(new CodeWriter() { @Override public OutputStream openBinary(JPackage pkg, String fileName) throws IOException { return byteArrayOutputStream; } @Override public void close() throws IOException { byteArrayOutputStream.close(); } }); return byteArrayOutputStream.toString("utf-8"); }
/** * 详情. */ @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"; }
@GetMapping("/home") public ModelAndView home(@RequestParam("pageSize") Optional<Integer> pageSize, @RequestParam("page") Optional<Integer> page) { // Evaluate page size. If requested parameter is null, return initial // page size int evalPageSize = pageSize.orElse(INITIAL_PAGE_SIZE); // Evaluate page. If requested parameter is null or less than 0 (to // prevent exception), return initial size. Otherwise, return value of // param. decreased by 1. int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1; // Page<Post> posts = postService.findAllPageable(new PageRequest(evalPage, evalPageSize)); Page<Product> products = productService.findAllProductsPageable(new PageRequest(evalPage, evalPageSize)); Pager pager = new Pager(products.getTotalPages(), products.getNumber(), BUTTONS_TO_SHOW); ModelAndView modelAndView = new ModelAndView(); // Collection<Post> posts = postService.findNLatestPosts(5); modelAndView.addObject("products", products); modelAndView.addObject("selectedPageSize", evalPageSize); modelAndView.addObject("pageSizes", PAGE_SIZES); modelAndView.addObject("pager", pager); modelAndView.setViewName("home"); return modelAndView; }
/** * 服务于第一步,设置当前存储方式(保存) * @throws ConfigurationException */ @RequestMapping("/setAttachmentMode") public String setLocalAttachmentFile(HttpServletRequest request, Model model, @RequestParam(value = "mode", required = false, defaultValue="") String mode){ if(!Global.get("IW_AUTO_INSTALL_USE").equals("true")){ return error(model, "系统已禁止使用此!"); } String m = AttachmentFile.MODE_LOCAL_FILE; //默认使用服务器进行存储 if(mode.equals(AttachmentFile.MODE_ALIYUN_OSS)){ //使用阿里云OSS m = AttachmentFile.MODE_ALIYUN_OSS; } sqlService.executeSql("update system set value = '"+m+"' WHERE name = 'ATTACHMENT_FILE_MODE'"); //更新缓存 systemService.refreshSystemCache(); return redirect("install/systemSet.do"); }
/** * 上传发布流程定义. */ @RequestMapping("console-process-upload") public String processUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws Exception { String tenantId = tenantHolder.getTenantId(); String fileName = file.getOriginalFilename(); Deployment deployment = processEngine.getRepositoryService() .createDeployment() .addInputStream(fileName, file.getInputStream()) .tenantId(tenantId).deploy(); List<ProcessDefinition> processDefinitions = processEngine .getRepositoryService().createProcessDefinitionQuery() .deploymentId(deployment.getId()).list(); for (ProcessDefinition processDefinition : processDefinitions) { processEngine.getManagementService().executeCommand( new SyncProcessCmd(processDefinition.getId())); } return "redirect:/bpm/console-listProcessDefinitions.do"; }
/** * Fetch restaurants with the specified name. A partial case-insensitive * match is supported. So <code>http://.../restaurants/rest</code> will find * any restaurants with upper or lower case 'rest' in their name. * * @param name * @return A non-null, non-empty collection of restaurants. */ @RequestMapping(method = RequestMethod.GET) public ResponseEntity<Collection<Restaurant>> findByName(@RequestParam("name") String name) { logger.info(String.format("restaurant-service findByName() invoked:{} for {} ", restaurantService.getClass().getName(), name)); name = name.trim().toLowerCase(); Collection<Restaurant> restaurants; try { restaurants = restaurantService.findByName(name); } catch (Exception ex) { logger.log(Level.SEVERE, "Exception raised findByName REST Call", ex); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } return restaurants.size() > 0 ? new ResponseEntity<>(restaurants, HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NO_CONTENT); }
@RequestMapping("model-field-input") public String input( @RequestParam(value = "id", required = false) Long id, @RequestParam(value = "type", required = false) String whitelistTypeCode, Model model) { ModelField modelField = null; if (id != null) { modelField = modelFieldManager.get(id); model.addAttribute("model", modelField); } model.addAttribute("modelInfos", modelInfoManager.getAll()); return "model/model-field-input"; }
/** * 新增/修改全局变量,修改system表的单个变量 * @param id 要修改的变量的id */ @RequiresPermissions("adminSystemVariable") @RequestMapping("variable") public String variable( @RequestParam(value = "id", required = false, defaultValue="0") int id, Model model, HttpServletRequest request){ System system; if(id == 0){ //新增 system = new System(); ActionLogCache.insert(request, "进入新增系统变量页面"); }else{ //修改 system = sqlService.findById(System.class, id); if(system == null){ return error(model, "要修改的变量不存在"); } ActionLogCache.insert(request, id, "进入修改系统变量页面", system.getName()+"="+system.getValue()); } //编辑页面 model.addAttribute("system", system); return "/iw/admin/system/variable"; }
@RequestMapping(value = "/getSimilarMovies", method = RequestMethod.GET) public String getSimilarMovies(@RequestParam(value = "id") String id)throws Exception{ int numTopNRanks = 10; int itemIdx = rateDao.getItemId(id); String str = ""; List<Map.Entry<Integer, Double>> itemScores = new ArrayList<>(); List<Integer> rankedItems = new ArrayList<>(itemScores.size()); for (int u = 0,um = trainMatrix.numColumns();u<um;u++){ if(u!=itemIdx){ double score = Sims.jaccard(trainMatrix.getColumns(u),trainMatrix.getColumns(itemIdx)); itemScores.add(new AbstractMap.SimpleImmutableEntry<Integer,Double>(u,score)); } } itemScores = Lists.sortListTopK(itemScores, true, numTopNRanks); for (Map.Entry<Integer, Double> kv : itemScores) { Integer item = kv.getKey(); rankedItems.add(item); } int i; for (i = 0; i < rankedItems.size()-1 && i<9; i++) { str+=rateDao.getItemId(rankedItems.get(i))+","; } str+=rateDao.getItemId(rankedItems.get(i)); return str; }
/** * 获取最新App版本描述信息,同时也用于记录用户基本信息 * * @param request * @param userKey 用户认证KEY * @param brand 设备品牌 * @param model 设备型号 * @param sdk 系统版本 * @param appVerName App版本名 * @param appVerCode App版本号 * @return */ @RequestMapping("/appver") @ResponseBody public ResResBean<AppVerVo> checkAppUpdate(HttpServletRequest request, @RequestParam(value = "userkey", required = false) String userKey, @RequestParam(value = "devicebrand", required = false) String brand, @RequestParam(value = "devicemodel", required = false) String model, @RequestParam(value = "devicesdk", required = false) Integer sdk, @RequestParam(value = "appvername", required = false) String appVerName, @RequestParam(value = "appvercode", required = false) Integer appVerCode) { System.out.println("GET /misc/appver " + model); monitorService.addLog(userKey, ExtraUtil.getRemoteHost(request), brand, model, sdk, appVerName, appVerCode); // String dir = request.getServletContext().getRealPath("/"); // File versionFile = new File(dir + "/WEB-INF/config/appversion.json"); // return ExtraUtil.readFile(versionFile); return new ResResBean.Builder<AppVerVo>() .status(ResResBean.STATUS_SUCCESS) .result(appVerService.getLatestApp()) .build(); }
public ModelAndView login( @RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { logger.info("******login(error): {} ***************************************", error); logger.info("******login(logout): {} ***************************************", logout); ModelAndView model = new ModelAndView(); if (error != null) { model.addObject("error", "Invalid username and password!"); } if (logout != null) { model.addObject("message", "You've been logged out successfully."); } model.setViewName("login"); return model; }
@RequestMapping(value = SubscriptionPortalService.BASE_PATH, method = GET) public String listSubscriptions(Model model, @RequestParam String token) { log.info("Subscription list request"); Optional<_BridgeSubscription> subOpt = subMgr.getWithEmailKey(token); if (!subOpt.isPresent()) { throw new InvalidEmailKeyException(); } log.info("E-mail token is valid: {}", token); String email = subOpt.get().getEmailEndpoint().getIdentity(); log.info("E-mail user: {}", email); List<SubscriptionItem> subs = new ArrayList<>(); for (_BridgeSubscription sub : subMgr.listForEmail(email)) { subs.add(new SubscriptionItem(sub)); } log.info("Found {} subscription(s)", subs.size()); model.addAttribute("subList", subs); return "subscription/list"; }
@ApiOperation(value = "Start an existing workspace. Stop all other workspaces (only one workspace can be running at a time)") @PatchMapping("/workspace/{name}") public Workspace startExisting(@PathVariable String name, @RequestParam String masterUrl, @RequestParam String namespace, @ApiParam(value = "Keycloak token", required = true) @RequestHeader("Authorization") String keycloakToken) throws IOException, URISyntaxException, RouteNotFoundException, StackNotFoundException, GitHubOAthTokenException, ProjectCreationException, KeycloakException, WorkspaceNotFound { KeycloakTokenValidator.validate(keycloakToken); String openShiftToken = keycloakClient.getOpenShiftToken(keycloakToken); String gitHubToken = keycloakClient.getGitHubToken(keycloakToken); String cheServerURL = openShiftClientWrapper.getCheServerUrl(masterUrl, namespace, openShiftToken, keycloakToken); Workspace workspace = workspaceClient.startWorkspace(cheServerURL, name, masterUrl, namespace, openShiftToken, keycloakToken); setGitHubOAthTokenAndCommitterInfo(cheServerURL, gitHubToken, keycloakToken); return workspace; }
/** * get/suggest skills based on search query -> can be used for autocompletion when user started * typing */ @ApiOperation(value = "suggest skills", nickname = "suggest skills", notes = "suggest skills") @ApiResponses({ @ApiResponse(code = 200, message = "Success"), @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 = "/skills", method = RequestMethod.GET) public ResponseEntity<String> getSkills(@RequestParam(required = false) String search, @RequestParam(required = false, defaultValue = "true") boolean exclude_hidden, @RequestParam(required = false, defaultValue = "-1") int count) { JSONArray skillsArr = new JSONArray( skillService.getSkills(search, exclude_hidden, count) .stream() .map(KnownSkill::toJSON) .collect(Collectors.toList()) ); return new ResponseEntity<>(skillsArr.toString(), HttpStatus.OK); }
@RequestMapping("bpm-process-remove") public String remove(@RequestParam("selectedItem") List<Long> selectedItem, RedirectAttributes redirectAttributes) { List<BpmProcess> bpmCategories = bpmProcessManager .findByIds(selectedItem); bpmProcessManager.removeAll(bpmCategories); messageHelper.addFlashMessage(redirectAttributes, "core.success.delete", "删除成功"); return "redirect:/bpm/bpm-process-list.do"; }
/** * Processes input text and outputs the classification results. * @param text the input text * @return returns a HTML document with the analysis of the input */ @RequestMapping("/") String home(@RequestParam(value = "text", defaultValue = "") String text, @RequestParam(value="format", defaultValue ="html") String format) { Result result = analyzer.analyzeText(text); if (format.compareTo("json") == 0) { return generateJSONResponse(result); } else { return generateHTMLResponse(result); } }
@RequestMapping(value = "aggregated/{environmentName}", method = RequestMethod.GET) public ResponseEntity<List<AggregatedResourceStatus>> getStatus( @PathVariable("environmentName") String environmentName, @RequestParam(value = "resources", required = false) Set<String> resources, @RequestParam("startDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date startDate, @RequestParam("endDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date endDate) { AggregatedStatusDAO detailDAO = MongoConnector.getInstance().getAggregatedStatusDAO(); List<AggregatedResourceStatus> aggStatusses = detailDAO.getAggregatedStatuses(environmentName, resources, startDate, endDate); return ResponseEntity.ok(aggStatusses); }
@GetMapping("/list") @Cacheable(cacheNames = "product", key = "#sellerid", condition = "#sellerid.length()>10", unless = "#result.getCode() !=0") public ResultVO list(@RequestParam(value = "sellerid", required = false) String sellerid) { //查询上架的商品 List<ProductInfo> productInfoList = productService.findUpAll(); List<Integer> categoryTypeList = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList()); List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList); List<ProductVO> productVOList = new ArrayList<>(); for (ProductCategory productCategory : productCategoryList) { ProductVO productVO = new ProductVO(); productVO.setCategoryType(productCategory.getCategoryType()); productVO.setCategoryName(productCategory.getCategoryName()); List<ProductInfoVO> productInfoVOList = new ArrayList<>(); for (ProductInfo productInfo : productInfoList) { if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) { ProductInfoVO productInfoVO = new ProductInfoVO(); BeanUtils.copyProperties(productInfo, productInfoVO); productInfoVOList.add(productInfoVO); } } productVO.setProductInfoVOList(productInfoVOList); productVOList.add(productVO); } return ResultVOUtil.success(productVOList); }
/** * Create relation between {@link by.kraskovski.pms.domain.model.Stock} and {@link Store} */ @PutMapping("/stock-manage") @ResponseStatus(HttpStatus.NO_CONTENT) public void addStock(@RequestParam final String storeId, @RequestParam final String stockId) { log.info("Start add stock: {} to store: {}", stockId, storeId); storeService.addStock(storeId, stockId); }
@RequestMapping("job-user-input") public String input(@RequestParam(value = "id", required = false) Long id, Model model) { String tenantId = tenantHolder.getTenantId(); if (id != null) { JobUser jobUser = jobUserManager.get(id); model.addAttribute("model", jobUser); } model.addAttribute("jobInfos", jobInfoManager.findBy("tenantId", tenantId)); return "org/job-user-input"; }
@RequestMapping(method=RequestMethod.POST, value="/cm/simple/cis") @ResponseBody public CmsCISimple createCISimple( @RequestParam(value="value", required = false) String valueType, @RequestBody CmsCISimple ciSimple, @RequestHeader(value="X-Cms-Scope", required = false) String scope, @RequestHeader(value="X-Cms-User", required = false) String userId) throws CIValidationException { scopeVerifier.verifyScope(scope, ciSimple); CmsCI newCi = cmsUtil.custCISimple2CI(ciSimple, valueType); newCi.setCiId(0); newCi.setCiGoid(null); newCi.setCreatedBy(userId); try { CmsCI ci = cmManager.createCI(newCi); updateAltNs(ci.getCiId(), ciSimple); logger.debug(ci.getCiId()); CmsCISimple cmsCISimple = cmsUtil.custCI2CISimple(ci, valueType); cmsCISimple.setAltNs(ciSimple.getAltNs()); return cmsCISimple; } catch (DataIntegrityViolationException dive) { if (dive instanceof DuplicateKeyException) { throw new CIValidationException(CmsError.CMS_DUPCI_NAME_ERROR, dive.getMessage()); } else { throw new CmsException(CmsError.CMS_EXCEPTION, dive.getMessage()); } } }
/** * 市场主动护送数据,按下载URL去拉取一个文件 * 127.0.0.1:9080/sjk-market-collection/market/yingyongso * /gen.d?marketName=shoujikong_channel * &key=bzHqw2V1MhXXkUddQl77qFa5slxYKhYf& * download=http://www.yingyong.so/shoujikong * /ijinshan_shoujikongchannel_f855087b4eaf423fb7b2be5413825abb.csv * * @param c * @return */ @RequestMapping(value = "/yingyongso/gen.d", produces = "application/json;charset=UTF-8") @ResponseBody public String gen(@RequestParam final String marketName, @RequestParam String key, @RequestParam final String download) { logger.info("Someone requests gen a file!"); JSONObject output = new JSONObject(); JSONObject server = new JSONObject(); output.put("result", server); boolean login = marketSecurityService.allowAccess(marketName, key); if (login) { server.put("msg", "Login Ok! Handle in deamon..."); server.put("code", SvrResult.OK.getCode()); dblogger.info("URL of download: {}", download); new Thread(new Runnable() { @Override public void run() { ((NotifyDataServiceImpl) notifyDataServiceImpl).importByUrl(marketName, download); } }).start(); } else { dblogger.info("{} invalid login!", marketName); server.put("msg", SvrResult.CLIENT_ILLEGAL_LOGIN.getMsg()); server.put("code", SvrResult.CLIENT_ILLEGAL_LOGIN.getCode()); } return output.toJSONString(); }
/** * 网站详情 * @param id News.id * @param model * @return */ @RequiresPermissions("adminSiteView") @RequestMapping("view") public String view(@RequestParam(value = "id", required = true , defaultValue="") int id, Model model){ Site site = (Site) sqlService.findById(Site.class, id); model.addAttribute("site", site); return "admin/site/view"; }
@RequestMapping("/changeUserStatus") @ResponseBody public String changeUserStatus(@RequestParam("userId") int userId) { JsonObject json = new JsonObject(); if (adminService.changeUserRole(userId) == 1) { json.addProperty("result", "success"); } else { json.addProperty("result", "failed"); } return json.toString(); }
@RequestMapping ( KILL_URL ) public ObjectNode killServer ( @RequestParam ( CSAP.SERVICE_PORT_PARAM ) ArrayList<String> services, @RequestParam ( CSAP.HOST_PARAM ) ArrayList<String> hosts, @RequestParam ( required = false ) String clean, @RequestParam ( required = false ) String keepLogs, HttpServletRequest request ) throws IOException { String uiUser = securityConfig.getUserIdFromContext(); logger.info( "User: {}, hosts: {}, services: {} clean: {}, keepLogs: {} ", uiUser, hosts, services, clean, keepLogs ); ObjectNode resultsJson; if ( Application.isJvmInManagerMode() ) { resultsJson = serviceCommands.killRemoteRequests( uiUser, services, hosts, clean, keepLogs, csapApp.lifeCycleSettings().getAgentUser(), csapApp.lifeCycleSettings().getAgentPass() ); } else { resultsJson = serviceCommands.killRequest( uiUser, services, clean, keepLogs, null ); } return resultsJson; }
/** * 模版信息 * @param id * @return */ @RequestMapping("/info/{batchInfoId}") @RequiresPermissions("msg:batchInfo:info") //从路径中取变量@PathVariable 看上面的requestMapping,指的就是后面那个同名参数 public R info(@RequestParam Map<String,Object> params,@PathVariable("batchInfoId")String batchInfoId){ params.put("batchInfoId", batchInfoId); Query query = new Query(params); List<MsgEntity> msgList=msgService.queryList(query); int total = msgService.queryTotal(params); PageUtils pageUtil = new PageUtils(msgList,total,query.getLimit(),query.getPage()); return R.ok().put("page", pageUtil); }