类org.springframework.web.bind.annotation.PathVariable源码实例Demo

下面列出了怎么用org.springframework.web.bind.annotation.PathVariable的API类实例代码及写法,或者点击链接到github查看源代码。

/**
 * Fetch users with the given id. <code>http://.../v1/users/{id}</code> will return user with
 * given id.
 *
 * @param id
 * @return A non-null, non-empty collection of users.
 */
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Entity> findById(@PathVariable("id") String id) throws Exception {
  logger.info(String
      .format("user-service findById() invoked:{} for {} ", userService.getClass().getName(),
          id));
  id = id.trim();
  Entity user;
  try {
    user = userService.findById(id);
  } catch (Exception ex) {
    logger.log(Level.WARNING, "Exception raised findById REST Call {0}", ex);
    throw ex;
  }
  return user != null ? new ResponseEntity<>(user, HttpStatus.OK)
      : new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
@ResponseBody
@RequestMapping(path = APPLICATION_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD,
		RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS })
public Flux<InstanceWebProxy.InstanceResponse> endpointProxy(
		@PathVariable("applicationName") String applicationName, HttpServletRequest servletRequest) {
	ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
	String endpointLocalPath = this.getEndpointLocalPath(this.adminContextPath + APPLICATION_MAPPED_PATH,
			servletRequest);
	URI uri = UriComponentsBuilder.fromPath(endpointLocalPath).query(request.getURI().getRawQuery()).build(true)
			.toUri();

	Flux<DataBuffer> cachedBody = DataBufferUtils.readInputStream(request::getBody, this.bufferFactory, 4096)
			.cache();

	return this.instanceWebProxy.forward(this.registry.getInstances(applicationName), uri, request.getMethod(),
			this.httpHeadersFilter.filterHeaders(request.getHeaders()), BodyInserters.fromDataBuffers(cachedBody));
}
 
源代码3 项目: activiti-in-action-codes   文件: TaskController.java
/**
 * 添加候选人
 */
@RequestMapping("task/candidate/add/{taskId}")
@ResponseBody
public String addCandidates(@PathVariable("taskId") String taskId, @RequestParam("userOrGroupIds[]") String[] userOrGroupIds,
                            @RequestParam("type[]") String[] types, HttpServletRequest request) {
    // 设置当前操作人,对于调用活动可以获取到当前操作人
    String currentUserId = UserUtil.getUserFromSession(request.getSession()).getId();
    identityService.setAuthenticatedUserId(currentUserId);

    for (int i = 0; i < userOrGroupIds.length; i++) {
        String type = types[i];
        if (StringUtils.equals("user", type)) {
            taskService.addCandidateUser(taskId, userOrGroupIds[i]);
        } else if (StringUtils.equals("group", type)) {
            taskService.addCandidateGroup(taskId, userOrGroupIds[i]);
        }
    }
    return "success";
}
 
/**
 * 后台查看用户IP界面
 * 
 * @param id
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/admin/userips/{id}",method={RequestMethod.GET})
public ModelAndView UserIps(@PathVariable long id) throws Exception {
	ModelAndView mv = new ModelAndView("admin/userips");
	Subject currentUser = SecurityUtils.getSubject();
	CommonUtils.setControllerName(request, mv);
	CommonUtils.setUserInfo(currentUser, userServices, teamServices,submissionServices,mv);
	if (CommonUtils.CheckIpBanned(request, bannedIpServices)) {
		currentUser.logout();
		return new ModelAndView("redirect:/showinfo?err=-99");
	}
	
	
	Users userobj = userServices.getUserById(id);
	if (userobj == null) {
		return new ModelAndView("redirect:/showinfo?err=404");
	}
	mv.addObject("currentuser", userobj);
	List<IpLogs> ips = ipLogServices.getAllIpLogsByUserId(userobj.getId());
	
	mv.addObject("ipused", ips);
	mv.setViewName("admin/userips");
	return mv;
}
 
@RequestMapping(value = "{grouping}/studentGroupsEnrolledByStudent")
    public @ResponseBody ResponseEntity<String> getStudentGroupsEnrolledByStudent(@PathVariable Grouping grouping) {
        if (!groupingIsOpenForEnrollment(grouping)) {
//            throw new DomainException("error.grouping.notOpenToEnrollment");
            return new ResponseEntity<>(
                    createErrorJson((new DomainException("error.grouping.notOpenToEnrollment")).getLocalizedMessage()),
                    HttpStatus.FORBIDDEN);
        }
        if (!personInGroupingAttends(grouping, AccessControl.getPerson())) {
//            throw new DomainException("error.grouping.notEnroled");
            return new ResponseEntity<>(
                    createErrorJson((new DomainException("error.grouping.notEnroled")).getLocalizedMessage()),
                    HttpStatus.FORBIDDEN);
        }
        return new ResponseEntity<>(view(grouping
                .getStudentGroupsSet()
                .stream()
                .filter(studentGroup -> studentGroup.getAttendsSet().stream()
                        .anyMatch(attends -> attends.getRegistration().getPerson() == AccessControl.getPerson()))).toString(), HttpStatus.OK);
    }
 
源代码6 项目: NFVO   文件: RestUsers.java
@ApiOperation(
    value = "Changing a User's password",
    notes = "If you want to change another User's password, you have to be an admin")
@RequestMapping(
    value = "changepwd/{username}",
    method = RequestMethod.PUT,
    consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.ACCEPTED)
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public void changePasswordOf(
    @PathVariable("username") String username, @RequestBody /*@Valid*/ JsonObject newPwd)
    throws UnauthorizedUserException, PasswordWeakException, NotFoundException,
        NotAllowedException {
  log.debug("Changing password of user " + username);
  if (isAdmin()) {
    JsonObject jsonObject = gson.fromJson(newPwd, JsonObject.class);
    userManagement.changePasswordOf(username, jsonObject.get("new_pwd").getAsString());
  } else {
    throw new NotAllowedException(
        "Forbidden to change password of other users. Only admins can do this.");
  }
}
 
源代码7 项目: kylin   文件: CubeController.java
/**
 * Get SQL of a Cube segment
 *
 * @param cubeName    Cube Name
 * @param segmentName Segment Name
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/{cubeName}/segs/{segmentName}/sql", method = { RequestMethod.GET }, produces = {
        "application/json" })
@ResponseBody
public GeneralResponse getSql(@PathVariable String cubeName, @PathVariable String segmentName) {

    checkCubeExists(cubeName);
    CubeInstance cube = cubeService.getCubeManager().getCube(cubeName);

    CubeSegment segment = cube.getSegment(segmentName, null);
    if (segment == null) {
        throw new NotFoundException("Cannot find segment " + segmentName);
    }

    IJoinedFlatTableDesc flatTableDesc = new CubeJoinedFlatTableDesc(segment, true);
    String sql = JoinedFlatTable.generateSelectDataStatement(flatTableDesc);

    GeneralResponse response = new GeneralResponse();
    response.setProperty("sql", sql);

    return response;
}
 
/**
 * 处理查询商品的请求
 * @param product 封装了要查询的商品需要满足的条件
 * @param pageNum 第几页
 * @param pageSize 每页多少条
 * @return 封装有商品列表以及分页信息的map集合
 */
@RequestMapping(value="/listProduct/{pageNum}/{pageSize}")
public @ResponseBody Map<String, Object> listProduct(@RequestBody Product product,
	@PathVariable(value="pageNum") Integer pageNum, @PathVariable(value="pageSize") Integer pageSize) {
	Map<String, Object> map = new HashMap<String, Object>();
	
	PageParam pageParam = new PageParam(pageNum, pageSize);
	if (pageNum == null || pageSize == null) {
		pageParam = null;
	}
	
	PageInfo<ProductDTO> productInfo = this.productService.listProductPage(product, pageParam);
	// 1.获取商品列表
	List<ProductDTO> productList = productInfo.getList();
	// 2.获取分页条
	String pageBar = PageUtils.pageStr(productInfo, PRODUCT_QUERY_METHOD_PAGE);
	// 3.统计公有多少条记录
	Long listSize = productInfo.getTotal();
	
	map.put(FRONT_PRODUCTLIST_ATTR, productList);
	map.put(FRONT_LISTSIZE_ATTR, listSize);
	map.put(FRONT_PAGEBAR_ATTR, pageBar);
	
	return map;
}
 
源代码9 项目: micro-ecommerce   文件: PaymentController.java
/**
 * Shows the {@link Receipt} for the given order.
 * 
 * @param order
 * @return
 */
@RequestMapping(value = PaymentLinks.RECEIPT, method = GET)
HttpEntity<Resource<Receipt>> showReceipt(@PathVariable("id") Order order) {

	if (order == null || !order.isPaid() || order.isTaken()) {
		return new ResponseEntity<Resource<Receipt>>(HttpStatus.NOT_FOUND);
	}

	Payment payment = paymentService.getPaymentFor(order);

	if (payment == null) {
		return new ResponseEntity<Resource<Receipt>>(HttpStatus.NOT_FOUND);
	}

	return createReceiptResponse(payment.getReceipt());
}
 
源代码10 项目: WebStack-Guns   文件: KaptchaController.java
/**
 * 返回图片
 *
 * @author stylefeng
 * @Date 2017/5/24 23:00
 */
@RequestMapping("/{pictureId}")
public void renderPicture(@PathVariable("pictureId") String pictureId, HttpServletResponse response) {
    String path = gunsProperties.getFileUploadPath() + pictureId;
    try {
        byte[] bytes = FileUtil.toByteArray(path);
        response.getOutputStream().write(bytes);
    } catch (Exception e) {
        //如果找不到图片就返回一个默认图片
        try {
            response.sendRedirect("/static/img/github.png");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
 
@PostMapping("/all_server/{app}")
public Result<ClusterAppAssignResultVO> apiAssignAllClusterServersOfApp(@PathVariable String app,
                                                                        @RequestBody
                                                                            ClusterAppFullAssignRequest assignRequest) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    if (assignRequest == null || assignRequest.getClusterMap() == null
        || assignRequest.getRemainingList() == null) {
        return Result.ofFail(-1, "bad request body");
    }
    try {
        return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, assignRequest.getClusterMap(),
            assignRequest.getRemainingList()));
    } catch (Throwable throwable) {
        logger.error("Error when assigning full cluster servers for app: " + app, throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
/**
 * Web service endpoint to fetch a single Greeting entity by primary key
 * identifier.
 * 
 * If found, the Greeting is returned as JSON with HTTP status 200.
 * 
 * If not found, the service returns an empty response body with HTTP status
 * 404.
 * 
 * @param id A Long URL path variable containing the Greeting primary key
 *        identifier.
 * @return A ResponseEntity containing a single Greeting object, if found,
 *         and a HTTP status code as described in the method comment.
 */
@RequestMapping(
        value = "/api/greetings/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Greeting> getGreeting(@PathVariable("id") Long id) {
    logger.info("> getGreeting id:{}", id);

    Greeting greeting = greetingService.findOne(id);
    if (greeting == null) {
        return new ResponseEntity<Greeting>(HttpStatus.NOT_FOUND);
    }

    logger.info("< getGreeting id:{}", id);
    return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
}
 
源代码13 项目: txle   文件: UserController.java
@PostMapping("/deductMoneyFromUserAuto/{userId}/{balance}")
public String deductMoneyFromUserAuto(@PathVariable long userId, @PathVariable double balance) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    System.err.println("[" + sdf.format(new Date()) + "] Executing method '" + this.getClass() + ".deductMoneyFromUserAuto'. \t\tParameters[userId = " + userId + ", balance = " + balance + "]");
    synchronized (userService) {
        // 防止并发场景同时更新数据库,避免负数情况
        return userService.updateBalanceByUserIdAuto(userId, balance) + "";
    }
}
 
源代码14 项目: spring-boot-tutorials   文件: UserController.java
@ApiOperation(value = "根据id查询用户信息", notes = "查询数据库中某个用户的信息")
@ApiImplicitParam(name = "id", value = "用户ID", paramType = "path", required = true, dataType = "java.lang.Long")
@GetMapping(value = "/{id}")
public ApiResult<User> getStudent(@PathVariable Long id) {
    logger.info("开始查询某个用户的信息");
    User user = userService.getUserById(id);
    return ApiResult.buildSuccessResult(user);
}
 
源代码15 项目: data-prep   文件: DataSetAPI.java
@RequestMapping(value = "/api/datasets/{id}/metadata", method = PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Update a data set metadata by id.", consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE, //
        notes = "Update a data set metadata based on content provided in PUT body with given id. For documentation purposes. Returns the id of the updated data set metadata.")
@Timed
public void updateMetadata(
        @ApiParam(value = "Id of the data set metadata to be updated") @PathVariable(value = "id") String id,
        @ApiParam(value = "content") InputStream dataSetContent) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating or updating dataset #{} (pool: {})...", id, getConnectionStats());
    }
    HystrixCommand<String> updateDataSetCommand = getCommand(UpdateDataSet.class, id, dataSetContent);
    updateDataSetCommand.execute();
    LOG.debug("Dataset creation or update for #{} done.", id);
}
 
源代码16 项目: openemm   文件: MailinglistController.java
@GetMapping("/{id:\\d+}/usersDeleteSettings.action")
public String recipientsDeleteSettings(ComAdmin admin, @PathVariable("id") int mailinglistId, @ModelAttribute("deleteForm") MailinglistRecipientDeleteForm form) {
	form.setMailinglistId(mailinglistId);
	String shortname = mailinglistService.getMailinglistName(mailinglistId, admin.getCompanyID());
	form.setMailinglistShortname(shortname);
	form.setOnlyActiveUsers(false);
	form.setNoAdminAndTestUsers(false);
	return "mailinglist_recipients_delete_settings";
}
 
源代码17 项目: openapi-generator   文件: PetApi.java
/**
 * POST /pet/{petId}/uploadImage : uploads an image
 *
 * @param petId ID of pet to update (required)
 * @param additionalMetadata Additional data to pass to server (optional)
 * @param file file to upload (optional)
 * @return successful operation (status code 200)
 */
@ApiOperation(value = "uploads an image", nickname = "uploadFile", notes = "", response = ModelApiResponse.class, authorizations = {
    @Authorization(value = "petstore_auth", scopes = {
        @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
        @AuthorizationScope(scope = "read:pets", description = "read your pets")
        })
}, tags={ "pet", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) })
@ApiImplicitParams({
})
@RequestMapping(value = "/pet/{petId}/uploadImage",
    produces = { "application/json" }, 
    consumes = { "multipart/form-data" },
    method = RequestMethod.POST)
default ResponseEntity<ModelApiResponse> uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false)  String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file) {
    getRequest().ifPresent(request -> {
        for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
            if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
                String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }";
                ApiUtil.setExampleResponse(request, "application/json", exampleString);
                break;
            }
        }
    });
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

}
 
源代码18 项目: jeecg-boot   文件: ThirdLoginController.java
@RequestMapping("/render/{source}")
public void render(@PathVariable("source") String source, HttpServletResponse response) throws IOException {
    log.info("第三方登录进入render:" + source);
    AuthRequest authRequest = factory.get(source);
    String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
    log.info("第三方登录认证地址:" + authorizeUrl);
    response.sendRedirect(authorizeUrl);
}
 
源代码19 项目: activiti-in-action-codes   文件: TaskController.java
/**
 * 查看已结束任务
 */
@RequestMapping(value = "task/archived/{taskId}")
public ModelAndView viewHistoryTask(@PathVariable("taskId") String taskId) throws Exception {
    String viewName = "chapter6/task-form-archived";
    ModelAndView mav = new ModelAndView(viewName);
    HistoricTaskInstance task = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
    if (task.getParentTaskId() != null) {
        HistoricTaskInstance parentTask = historyService.createHistoricTaskInstanceQuery().taskId(task.getParentTaskId()).singleResult();
        mav.addObject("parentTask", parentTask);
    }
    mav.addObject("task", task);

    // 读取子任务
    List<HistoricTaskInstance> subTasks = historyService.createHistoricTaskInstanceQuery().taskParentTaskId(taskId).list();
    mav.addObject("subTasks", subTasks);

    // 读取附件
    List<Attachment> attachments = null;
    if (task.getTaskDefinitionKey() != null) {
        attachments = taskService.getTaskAttachments(taskId);
    } else {
        attachments = taskService.getProcessInstanceAttachments(task.getProcessInstanceId());
    }
    mav.addObject("attachments", attachments);

    return mav;
}
 
源代码20 项目: onboard   文件: StatsApiController.java
@RequestMapping(value = "/discussions", method = RequestMethod.GET)
@Interceptors({ CompanyMemberRequired.class })
@ResponseBody
public List<DiscussionDTO> getCompanyDiscussions(@PathVariable int companyId, @RequestParam(value = "start") long start,
        @RequestParam(value = "end") long end) {
    Date since = new Date(start);
    Date until = new Date(end);
    List<Discussion> discussions = discussionService.getDiscussionsByCompanyIdBetweenDates(companyId, since, until);
    return Lists.transform(discussions, DiscussionTransform.DISCUSSION_DTO_FUNCTION);
}
 
源代码21 项目: ACManager   文件: RatingController.java
@RequestMapping(value = "/updateTrainingTeam/{trainingId}", produces = "text/html;charset=UTF-8")
@ResponseBody
public String updateTrainingTeam(@PathVariable Integer trainingId) {
    Training training = trainingService.getTrainingById(trainingId);
    ratingService.flushTrainingTeamRating(training);
    return "更新完毕~";
}
 
源代码22 项目: pmq   文件: ViewController.java
@RequestMapping("/topic/expand/{topicId}/{topicName}")
public String topicExpand(@PathVariable Long topicId, @PathVariable String topicName, Model model) {
    model.addAttribute("timeStamp", System.currentTimeMillis());
    model.addAttribute("topicId", topicId);
    model.addAttribute("topicName", topicName);
    model.addAttribute("role", roleService.getRole(userInfoHolder.getUserId()));
    return "topic/topicExpand";
}
 
@RequestMapping(value = "/rest/activiti/process-instances/{processInstanceId}/variables/{variableName}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public void deleteVariable(@PathVariable String processInstanceId, @PathVariable String variableName) throws BadRequestException {
    ServerConfig serverConfig = retrieveServerConfig();
    try {
        clientService.deleteVariable(serverConfig, processInstanceId, variableName);
    } catch (ActivitiServiceException e) {
        throw new BadRequestException(e.getMessage());
    }
}
 
源代码24 项目: find   文件: CustomizationAdminController.java
@RequestMapping(value = TYPED_ASSETS_PATH, method = RequestMethod.POST)
public ResponseEntity<Status> postLogo(
    @PathVariable("type") final AssetType assetType,
    @RequestPart("file") final MultipartFile file
) throws CustomizationException {
    return saveLogo(assetType, file, false);
}
 
源代码25 项目: dhis2-core   文件: MessageConversationController.java
@RequestMapping( value = "/{uid}/read", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE,
    MediaType.APPLICATION_XML_VALUE } )
public @ResponseBody RootNode markMessageConversationRead(
    @PathVariable String uid, @RequestParam( required = false ) String userUid, HttpServletResponse response )
{
    return modifyMessageConversationRead( userUid, Lists.newArrayList( uid ), response, true );
}
 
源代码26 项目: alf.io   文件: AdminConfigurationController.java
@GetMapping("/admin/configuration/payment/{provider}/connect/{orgId}")
public String oAuthRedirectToAuthorizationURL(Principal principal,
                                              @PathVariable("orgId") Integer orgId,
                                              @PathVariable("provider") String provider,
                                              HttpSession session) {
    if(CONNECT_PROVIDERS.contains(provider) && userManager.isOwnerOfOrganization(userManager.findUserByUsername(principal.getName()), orgId)) {
        var connectURL = getConnector(provider).getConnectURL(orgId);
        session.setAttribute(provider+CONNECT_STATE_PREFIX +orgId, connectURL.getState());
        session.setAttribute(provider+CONNECT_ORG, orgId);
        return "redirect:" + connectURL.getAuthorizationUrl();
    }
    return REDIRECT_ADMIN;
}
 
源代码27 项目: boubei-tss   文件: _Recorder.java
@RequestMapping(value = "/batch/{record}", method = RequestMethod.DELETE)
public void deleteBatch(HttpServletRequest request, HttpServletResponse response, @PathVariable("record") Object record, String ids) {

	Long recordId = recordService.getRecordID(record, false);
	Map<String, String> requestMap = prepareParams(request, recordId);

	String[] idArray = ids.split(",");
	for (String id : idArray) {
		exeDelete(recordId, EasyUtils.obj2Long(id), requestMap);
	}
	printSuccessMessage();
}
 
源代码28 项目: dhis2-core   文件: MessageConversationController.java
@RequestMapping( value = "/{mcUid}/{msgUid}/attachments/{fileUid}", method = RequestMethod.GET )
public void getAttachment(
    @PathVariable( value = "mcUid" ) String mcUid,
    @PathVariable( value = "msgUid" ) String msgUid,
    @PathVariable( value = "fileUid" ) String fileUid,
    HttpServletResponse response )
    throws WebMessageException
{
    User user = currentUserService.getCurrentUser();

    Message message = getMessage( mcUid, msgUid, user );

    FileResource fr = fileResourceService.getFileResource( fileUid );

    if ( message == null )
    {
        throw new WebMessageException( WebMessageUtils.notFound( "No message found with id '" + msgUid + "' for message conversation with id '" + mcUid + "'" ) );
    }

    boolean attachmentExists = message.getAttachments().stream().filter( att -> att.getUid().equals( fileUid ) ).count() == 1;

    if ( fr == null || !attachmentExists )
    {
        throw new WebMessageException( WebMessageUtils.notFound( "No messageattachment found with id '" + fileUid + "'" ) );
    }

    if ( !fr.getDomain().equals( FileResourceDomain.MESSAGE_ATTACHMENT ))
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Invalid messageattachment." ) );
    }

    fileResourceUtils.configureFileResourceResponse( response, fr );
}
 
源代码29 项目: Kafdrop   文件: ConsumerController.java
@ApiOperation(value = "getConsumer", notes = "Get topic and partition details for a consumer group")
@ApiResponses(value = {
      @ApiResponse(code = 200, message = "Success", response = ConsumerVO.class),
      @ApiResponse(code = 404, message = "Invalid consumer group")
})
@RequestMapping(path = "{groupId:.+}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public @ResponseBody ConsumerVO getConsumer(@PathVariable("groupId") String groupId) throws Exception
{
   final ConsumerVO consumer = kafkaMonitor.getConsumer(groupId)
         .orElseThrow(() -> new ConsumerNotFoundException(groupId));

   return consumer;
}
 
源代码30 项目: lemon   文件: AvatarApiController.java
@RequestMapping(value = "{username}", produces = MediaType.IMAGE_PNG_VALUE)
public void avatar(
        @PathVariable("username") String username,
        @RequestParam(value = "width", required = false, defaultValue = "16") int width,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String tenantId = tenantHolder.getTenantId();

    InputStream is = userAvatarService.viewAvatarByUsername(username,
            width, tenantId).getInputStream();

    response.setContentType("image/png");
    IOUtils.copy(is, response.getOutputStream());
}