springfox.documentation.service.ResponseMessage Java Examples

The following examples show how to use springfox.documentation.service.ResponseMessage. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiMethodReader.java    From swagger-more with Apache License 2.0 6 votes vote down vote up
private void readReturnDescription(OperationContext context, ApiMethod apiMethod) {
    ResolvedType returnType = context.alternateFor(context.getReturnType());
    String message = StringUtils.isEmpty(apiMethod.returnDescription()) ? "成功" : apiMethod.returnDescription();
    ModelReference modelRef = null;
    if (!isVoid(returnType)) {
        ModelContext modelContext = ModelContext.returnValue(
                context.getGroupName(), returnType,
                context.getDocumentationType(),
                context.getAlternateTypeProvider(),
                context.getGenericsNamingStrategy(),
                context.getIgnorableParameterTypes());
        modelRef = modelRefFactory(modelContext, typeNameExtractor).apply(returnType);
    }
    ResponseMessage built = new ResponseMessageBuilder()
            .code(HttpStatus.OK.value())
            .message(message)
            .responseModel(modelRef)
            .build();
    context.operationBuilder().responseMessages(newHashSet(built));
}
 
Example #2
Source File: SwaggerConfig.java    From swagger-more with Apache License 2.0 6 votes vote down vote up
@Bean
@Autowired
public Docket complete(ServletContext servletContext) {
    List<ResponseMessage> responseMessageList = newArrayList();
    return new Docket(SWAGGER_2)
            .pathProvider(new RelativePathProvider(servletContext) {
                @Override
                public String getApplicationBasePath() {
                    return "/dubbo";
                }
            })
            .apiInfo(apiInfo())
            .select()
            .apis(ExtendRequestHandlerSelectors.dubboApi())
            .paths(PathSelectors.any())
            .build()
            .groupName("dubbo")
            .produces(Sets.newHashSet("application/json", "text/plain"))
            .consumes(Collections.singleton("application/json"))
            .useDefaultResponseMessages(false)
            .globalResponseMessage(RequestMethod.GET, responseMessageList)
            .globalResponseMessage(RequestMethod.POST, responseMessageList);
}
 
Example #3
Source File: SwaggerConfig.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Bean
public Docket userApi() {

	List<ResponseMessage> list = new java.util.ArrayList<>();
	list.add(new ResponseMessageBuilder().code(500).message("500 message").responseModel(new ModelRef("Result"))
			.build());
	list.add(new ResponseMessageBuilder().code(401).message("Unauthorized").responseModel(new ModelRef("Result"))
			.build());
	list.add(new ResponseMessageBuilder().code(406).message("Not Acceptable").responseModel(new ModelRef("Result"))
			.build());

	return new Docket(DocumentationType.SWAGGER_2)
		.apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.tmobile.pacman"))
		.paths(PathSelectors.any()).build()
		.securitySchemes(chooseSecuritSchema())
		.securityContexts(chooseSecurityContext())
		.globalResponseMessage(RequestMethod.GET, list).globalResponseMessage(RequestMethod.POST, list);
}
 
Example #4
Source File: SwaggerManualApiPlugin.java    From java-starthere with MIT License 5 votes vote down vote up
private Set<ResponseMessage> responseMessages()
{
    return Set.of(new ResponseMessageBuilder().code(200)
                                              .message("OK")
                                              .responseModel(new ModelRef("TokenModel"))
                                              .build());
}
 
Example #5
Source File: JavadocBuilderPlugin.java    From springfox-javadoc with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(OperationContext context) {

    String notes = context.requestMappingPattern() + PERIOD + context.httpMethod().toString() + ".notes";
    if (StringUtils.hasText(notes) && StringUtils.hasText(environment.getProperty(notes))) {
        context.operationBuilder().notes("<b>" + context.getName() + "</b><br/>" + environment.getProperty(notes));
    }
    String returnDescription = context.requestMappingPattern() + PERIOD + context.httpMethod().toString()
      + ".return";
    if (StringUtils.hasText(returnDescription) && StringUtils.hasText(environment.getProperty(returnDescription))) {
        context.operationBuilder().summary("returns " + environment.getProperty(returnDescription));
    }
    String throwsDescription = context.requestMappingPattern() + PERIOD + context.httpMethod().toString()
      + ".throws.";
    int i = 0;
    Set<ResponseMessage> responseMessages = new HashSet<ResponseMessage>();
    while (StringUtils.hasText(throwsDescription + i)
      && StringUtils.hasText(environment.getProperty(throwsDescription + i))) {
        String[] throwsValues = StringUtils.split(environment.getProperty(throwsDescription + i), "-");
        if (throwsValues.length == 2) {
            // TODO[MN]: proper mapping once
            // https://github.com/springfox/springfox/issues/521 is solved
            String thrownExceptionName = throwsValues[0];
            String throwComment = throwsValues[1];
            ModelReference model = new ModelRef(thrownExceptionName);
            ResponseMessage message = new ResponseMessageBuilder().code(500).message(throwComment)
              .responseModel(model).build();
            responseMessages.add(message);
        }
        i++;
    }
    context.operationBuilder().responseMessages(responseMessages);

}
 
Example #6
Source File: SwaggerConfig.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
/**
 * 模型映射配置
 * @author Frodez
 * @date 2019-12-04
 */
private void modelConfig(Docket docket) {
	List<ResponseMessage> responseMessageList = getGlobalResponseMessage();
	docket.useDefaultResponseMessages(false);
	docket.enableUrlTemplating(false);
	docket.globalResponseMessage(RequestMethod.GET, responseMessageList);
	docket.globalResponseMessage(RequestMethod.POST, responseMessageList);
	docket.globalResponseMessage(RequestMethod.PUT, responseMessageList);
	docket.globalResponseMessage(RequestMethod.DELETE, responseMessageList);
}
 
Example #7
Source File: SwaggerConfig.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
/**
 * 全局返回信息
 * @author Frodez
 * @date 2019-06-06
 */
private List<ResponseMessage> getGlobalResponseMessage() {
	List<ResponseMessage> list = new ArrayList<>();
	Map<HttpStatus, List<Result.ResultEnum>> map = new HashMap<>();
	for (Result.ResultEnum item : Result.ResultEnum.values()) {
		if (item.getStatus() == HttpStatus.OK) {
			//成功的返回信息不设置默认
			continue;
		}
		if (map.containsKey(item.getStatus())) {
			map.get(item.getStatus()).add(item);
		} else {
			List<Result.ResultEnum> enumList = new ArrayList<>();
			enumList.add(item);
			map.put(item.getStatus(), enumList);
		}
	}
	for (Entry<HttpStatus, List<Result.ResultEnum>> entry : map.entrySet()) {
		String message = SwaggerUtil.statusDescription(entry.getValue());
		ResponseMessageBuilder messageBuilder = new ResponseMessageBuilder();
		messageBuilder.code(entry.getKey().value());
		messageBuilder.message(message);
		messageBuilder.responseModel(new ModelRef(SwaggerModel.class.getSimpleName()));
		list.add(messageBuilder.build());
	}
	return list;
}
 
Example #8
Source File: Swagger2.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
/** 
 * 自定义返回信息 
 * @param 
 * @return 
 */  
private List<ResponseMessage> customerResponseMessage(){  
    return Arrays.asList(  
            new ResponseMessageBuilder()//500  
                    .code(9999)  
                    .message("系统繁忙")  
                    .responseModel(new ModelRef("Error"))  
                    .build(),  
            new ResponseMessageBuilder()//401  
                    .code(401)  
                    .message("未授权访问")  
                    .build());  
}
 
Example #9
Source File: WatermarkController.java    From kbase-doc with Apache License 2.0 5 votes vote down vote up
/**
 * 输出文件demo https://o7planning.org/en/11765/spring-boot-file-download-example
 * @author eko.zhan at 2018年9月2日 下午4:26:10
 * @param file
 * @param text
 * @param color
 * @return
 * @throws IOException
 */
@ApiOperation(value="传入文件并返回水印文件", response=ResponseMessage.class)
@ApiImplicitParams({
        @ApiImplicitParam(name="file", value="待添加水印的文件", dataType="__file", required=true, paramType="form"),
        @ApiImplicitParam(name="text", value="水印内容", dataType="string", required=false, paramType="form"),
        @ApiImplicitParam(name="color", value="颜色码,以#开头", dataType="string", required=false, paramType="form")
})
@PostMapping("/handle")
public ResponseEntity<ByteArrayResource> handle(@RequestParam("file") MultipartFile file, @RequestParam(value="text", required=false) String text, @RequestParam(value="color", required=false) String color) throws IOException {
	if (!file.getOriginalFilename().toLowerCase().endsWith(".docx")) {
		log.error("上传的文件必须是 docx 类型");
	}
	File dir = ResourceUtils.getFile("classpath:static/DATAS");
	String pardir = DateFormatUtils.format(new Date(), "yyyyMMdd");
	String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "." + FilenameUtils.getExtension(file.getOriginalFilename());
	File originFile = new File(dir + "/" + pardir + "/" + filename);
	FileUtils.copyInputStreamToFile(file.getInputStream(), originFile);
	byte[] bytes = watermarkService.handle(originFile, text, color);
	ByteArrayResource resource = new ByteArrayResource(bytes);
	return ResponseEntity.ok()
			// Content-Disposition
			.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + originFile.getName())
			// Content-Type
			.contentType(getMediaType(originFile.getName()))
			// Contet-Length
			.contentLength(bytes.length)
			.body(resource);
}
 
Example #10
Source File: AbstractSwaggerConfig.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected Docket addGlobalResponseMessages(Docket docket){
	Map<List<RequestMethod>, List<ResponseMessage>> globalResponses = this.createGlobalResponseMessages();
	if(LangUtils.isNotEmpty(globalResponses)){
		globalResponses.forEach((methods, value)->{
			methods.forEach(method->{
    			docket.globalResponseMessage(method, value);
			});
		});
	}
	return docket;
}
 
Example #11
Source File: App.java    From cerebro with GNU Affero General Public License v3.0 4 votes vote down vote up
private List<ResponseMessage> responseMessageList() {
    return newArrayList(new ResponseMessageBuilder().code(500).message("Server Error").responseModel(new ModelRef("Error")).build(),
        new ResponseMessageBuilder().code(401).message("Unauthorized").build());
}
 
Example #12
Source File: AbstractSwaggerConfig.java    From onetwo with Apache License 2.0 4 votes vote down vote up
protected Map<List<RequestMethod>, List<ResponseMessage>> createGlobalResponseMessages(){
	return Collections.emptyMap();
}