下面列出了org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter#com.fasterxml.jackson.annotation.JsonView 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("deprecation")
private void addResponse(Operation operation, ApiResponse apiResponse, JsonView jsonView) {
Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders(), jsonView);
Map<String, Object> examples = parseExamples(apiResponse.examples());
Response response = new Response().description(apiResponse.message()).headers(responseHeaders);
response.setExamples(examples);
if (apiResponse.code() == 0) {
operation.defaultResponse(response);
} else {
operation.response(apiResponse.code(), response);
}
if (StringUtils.isNotEmpty(apiResponse.reference())) {
response.schema(new RefProperty(apiResponse.reference()));
} else if (!isVoid(apiResponse.response())) {
Type responseType = apiResponse.response();
final Property property = ModelConverters.getInstance().readAsProperty(responseType, jsonView);
if (property != null) {
response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
appendModels(responseType);
}
}
}
public Operation parseMethod(
Method method,
List<Parameter> globalParameters,
JsonView jsonViewAnnotation)
{
JavaType classType = TypeFactory.defaultInstance().constructType(method.getDeclaringClass());
return parseMethod(
classType.getClass(),
method,
globalParameters,
null,
null,
null,
null,
new ArrayList<>(),
Optional.empty(),
new HashSet<>(),
new ArrayList<>(),
false,
null,
null,
jsonViewAnnotation,
null);
}
/**
* Returns the {@link Bug} with the given external ID. This ID is provided by the user when creating a bug, e.g., a CVE identifier.
*
* @return 404 {@link HttpStatus#NOT_FOUND} if bug with given bug ID does not exist, 200 {@link HttpStatus#OK} if the bug is found
* @param bugid a {@link java.lang.String} object.
*/
@RequestMapping(value = "/{bugid}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@JsonView(Views.BugDetails.class)
public ResponseEntity<Bug> getBug(@PathVariable String bugid) {
final StopWatch sw = new StopWatch("GET bug [" + bugid + "]").start();
try {
final Bug b = BugRepository.FILTER.findOne(this.bugRepository.findByBugId(bugid));
this.bugRepository.updateCachedCveData(b, false);
sw.stop();
return new ResponseEntity<Bug>(b, HttpStatus.OK);
}
catch(EntityNotFoundException enfe) {
sw.stop(enfe);
return new ResponseEntity<Bug>(HttpStatus.NOT_FOUND);
}
catch(Exception e) {
sw.stop(e);
return new ResponseEntity<Bug>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
protected ResolvedParameter getParameters( Type type, List<Annotation> annotations, Operation operation, Consumes classConsumes,
Consumes methodConsumes, JsonView jsonViewAnnotation)
{
final Iterator<OpenAPIExtension> chain = OpenAPIExtensions.chain();
if (!chain.hasNext())
{
return new ResolvedParameter();
}
LOGGER.debug("getParameters for {}", type);
Set<Type> typesToSkip = new HashSet<>();
final OpenAPIExtension extension = chain.next();
LOGGER.debug("trying extension {}", extension);
final ResolvedParameter extractParametersResult = extension
.extractParameters(annotations, type, typesToSkip, components, classConsumes, methodConsumes, true, jsonViewAnnotation, chain);
return extractParametersResult;
}
@JsonView(View.BranchStatistic.class)
@RequestMapping(value = "/api/branchStatistics", method = RequestMethod.GET)
public Page<BranchStatistic> getBranchesOfRepository(
@RequestParam(value = "createdByUserName", required = false) String createdByUserName,
@RequestParam(value = "branchId", required = false) Long branchId,
@RequestParam(value = "branchName", required = false) String branchName,
@RequestParam(value = "search", required = false) String search,
@RequestParam(value = "deleted", required = false) Boolean deleted,
@RequestParam(value = "empty", required = false) Boolean empty,
@PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable pageable) {
Page<BranchStatistic> page = branchStatisticRepository.findAll(where(
ifParamNotNull(createdByUserNameEquals(createdByUserName))).and(
ifParamNotNull(branchEquals(branchId))).and(
ifParamNotNull(branchNameEquals(branchName))).and(
ifParamNotNull(search(search))).and(
ifParamNotNull(deletedEquals(deleted))).and(
ifParamNotNull(empty(empty))), pageable);
return new PageView<>(page);
}
@Override
@JsonView(Views.Info.class)
public List<SeverityLevel> getSupportedSeverities() {
List<SeverityLevel> severities;
if (targetReader != null) {
severities = new ArrayList<>(targetReader.getSupportedSeverities());
} else {
severities = new ArrayList<>();
}
if (filters != null) {
for (final FieldsFilter f : filters) {
if (f instanceof LogEntryFilter) {
((LogEntryFilter) f).filterSupportedSeverities(severities);
}
}
Collections.sort(severities);
}
return severities;
}
/**
* Gets the translation history for a given text unit for a particular locale.
*
* @param textUnitId required
* @param bcp47Tag required
*
* @return the translations that matches the search parameters
* @throws InvalidTextUnitSearchParameterException
*/
@RequestMapping(method = RequestMethod.GET, value = "/api/textunits/{textUnitId}/history")
@ResponseStatus(HttpStatus.OK)
@JsonView(View.TranslationHistorySummary.class)
public List<TMTextUnitVariant> getTextUnitHistory(
@PathVariable Long textUnitId,
@RequestParam(value = "bcp47Tag", required = true) String bcp47Tag) throws InvalidTextUnitSearchParameterException {
Locale locale = localeService.findByBcp47Tag(bcp47Tag);
return tmHistoryService.findHistory(textUnitId, locale.getId());
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter,
Type targetType, Class<? extends HttpMessageConverter<?>> selectedConverterType) throws IOException {
JsonView annotation = methodParameter.getParameterAnnotation(JsonView.class);
Class<?>[] classes = annotation.value();
if (classes.length != 1) {
throw new IllegalArgumentException(
"@JsonView only supported for request body advice with exactly 1 class argument: " + methodParameter);
}
return new MappingJacksonInputMessage(inputMessage.getBody(), inputMessage.getHeaders(), classes[0]);
}
/**
* <p>countReachableConstructTypes.</p>
*
* @return a {@link com.sap.psr.vulas.backend.model.ConstructIdFilter} object.
*/
@JsonProperty(value = "reachableConstructTypeCounters")
@JsonView(Views.DepDetails.class)
public ConstructIdFilter countReachableConstructTypes() {
if(this.reachableFilter==null)
this.reachableFilter = new ConstructIdFilter(this.getReachableConstructIds());
return this.reachableFilter;
}
@JsonView(Views.Public.class)
@RequestMapping(value = "/answer", method = RequestMethod.POST)
public AjaxResponseBody createQuestion(@RequestBody AnswerModel data, UriComponentsBuilder ucBuilder) {
logger.info("Creating Answer : {}", data);
AjaxResponseBody result = new AjaxResponseBody();
AuthService authService = new AuthService(data.getToken(), key);
if (authService.getUserName() == null) {
result.setCode("404");
result.setMsg(authService.getMessage());
return result;
}
//OK, we can trust this JWT
String userName = authService.getUserName();
User user = userService.getByUsername(userName);
Question question = questionService.getById(data.getQuestion_id());
// prevent error of two instance of one object
if (Objects.equals(question.getUser().getUsername(), user.getUsername())) {
user = question.getUser();
}
Answer answer = new Answer(data.getMessage(), user, question);
answer = answerService.addAnswer(answer);
result.setCode("201");
result.setMsg(Long.toString(answer.getId()));
return result;
}
@JsonView(MyJacksonView1.class)
public JacksonViewBean jsonViewResponse() {
JacksonViewBean bean = new JacksonViewBean();
bean.setWithView1("with");
bean.setWithView2("with");
bean.setWithoutView("with");
return bean;
}
/**
* Returns a collection of {@link Bug}s relevant for the {@link Application} with the given GAV.
*
* @return 404 {@link HttpStatus#NOT_FOUND} if application with given GAV does not exist, 200 {@link HttpStatus#OK} if the application is found
* @param mvnGroup a {@link java.lang.String} object.
* @param artifact a {@link java.lang.String} object.
* @param version a {@link java.lang.String} object.
* @param historical a {@link java.lang.Boolean} object.
* @param space a {@link java.lang.String} object.
*/
@RequestMapping(value = "/{mvnGroup:.+}/{artifact:.+}/{version:.+}/bugs", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@JsonView(Views.BugDetails.class)
public ResponseEntity<List<Bug>> getApplicationBugs(@PathVariable String mvnGroup, @PathVariable String artifact,
@PathVariable String version,
@RequestParam(value="historical", required=false, defaultValue="false") Boolean historical,
@ApiIgnore @RequestHeader(value=Constants.HTTP_SPACE_HEADER, required=false) String space) {
Space s = null;
try {
s = this.spaceRepository.getSpace(space);
} catch (Exception e){
log.error("Error retrieving space: " + e);
return new ResponseEntity<List<Bug>>(HttpStatus.NOT_FOUND);
}
try {
// To throw an exception if the entity is not found
ApplicationRepository.FILTER.findOne(this.appRepository.findByGAV(mvnGroup,artifact,version,s));
if (historical == true)
return new ResponseEntity<List<Bug>>(this.appRepository.findBugsByGAV(mvnGroup,artifact,version,s), HttpStatus.OK);
else {
List<Bug> bugs = new ArrayList<Bug>() ;
TreeSet<VulnerableDependency> vd_list = this.appRepository.findJPQLVulnerableDependenciesByGAV(mvnGroup,artifact,version,s);
this.affLibRepository.computeAffectedLib(vd_list);
for (VulnerableDependency vd : vd_list){
if(vd.getAffectedVersion()==1)
bugs.add(vd.getBug());
}
return new ResponseEntity<List<Bug>>(bugs, HttpStatus.OK);
}
}
catch(EntityNotFoundException enfe) {
return new ResponseEntity<List<Bug>>(HttpStatus.NOT_FOUND);
}
}
@JsonView(Views.Public.class)
@RequestMapping(value = "/answers", method = RequestMethod.GET)
public ResponseEntity<List<Answer>> listAllAnswers() {
List<Answer> answers = answerService.getAll();
if (answers.isEmpty()) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
// You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<Answer>>(answers, HttpStatus.OK);
}
private Class<?> extractViewClass(JsonView annotation, Object conversionHint) {
Class<?>[] classes = annotation.value();
if (classes.length != 1) {
throw new IllegalArgumentException(
"@JsonView only supported for handler methods with exactly 1 class argument: " + conversionHint);
}
return classes[0];
}
/**
* Returns a collection of {@link DependencyIntersection}s for the {@link Application} with the given GAV.
*
* @return 404 {@link HttpStatus#NOT_FOUND} if application with given GAV does not exist, 200 {@link HttpStatus#OK} if the application is found
* @param mvnGroup a {@link java.lang.String} object.
* @param artifact a {@link java.lang.String} object.
* @param version a {@link java.lang.String} object.
* @param space a {@link java.lang.String} object.
*/
@RequestMapping(value = "/{mvnGroup:.+}/{artifact:.+}/{version:.+}/deps/intersect", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@JsonView(Views.Default.class)
public ResponseEntity<List<DependencyIntersection>> findDependencyIntersections(@PathVariable String mvnGroup,
@PathVariable String artifact, @PathVariable String version,
@ApiIgnore @RequestHeader(value=Constants.HTTP_SPACE_HEADER, required=false) String space) {
Space s = null;
try {
s = this.spaceRepository.getSpace(space);
} catch (Exception e){
log.error("Error retrieving space: " + e);
return new ResponseEntity<List<DependencyIntersection>>(HttpStatus.NOT_FOUND);
}
try {
final StopWatch sw = new StopWatch("Find dependency intersections for application: " + mvnGroup + ":" + artifact + ":" + version).start();
// Throws an exception if the entity is not found
final Application a = ApplicationRepository.FILTER.findOne(this.appRepository.findByGAV(mvnGroup,artifact,version,s));
final List<DependencyIntersection> is = this.depRepository.findDepIntersections(a.getMvnGroup(), a.getArtifact(), a.getVersion(),s);
sw.stop();
return new ResponseEntity<List<DependencyIntersection>>(is, HttpStatus.OK);
}
catch(EntityNotFoundException enfe) {
return new ResponseEntity<List<DependencyIntersection>>(HttpStatus.NOT_FOUND);
}
}
/**
* Returns the {@link Application} with the given Group Artifact Version (GAV).
*
* @return 404 {@link HttpStatus#NOT_FOUND} if application with given GAV does not exist, 200 {@link HttpStatus#OK} if the application is found
* @param mvnGroup a {@link java.lang.String} object.
* @param artifact a {@link java.lang.String} object.
* @param version a {@link java.lang.String} object.
* @param inclTraces a {@link java.lang.Boolean} object.
* @param space a {@link java.lang.String} object.
*/
@RequestMapping(value = "/{mvnGroup:.+}/{artifact:.+}/{version:.+}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@JsonView(Views.CountDetails.class)
public ResponseEntity<Application> getApplication(@PathVariable String mvnGroup, @PathVariable String artifact,
@PathVariable String version,
@RequestParam(value="inclTraces", required=false, defaultValue="true") Boolean inclTraces,
@ApiIgnore @RequestHeader(value=Constants.HTTP_SPACE_HEADER, required=false) String space) {
Space s = null;
try {
s = this.spaceRepository.getSpace(space);
} catch (Exception e){
log.error("Error retrieving space: " + e);
return new ResponseEntity<Application>(HttpStatus.NOT_FOUND);
}
try {
final Application app = ApplicationRepository.FILTER.findOne(this.appRepository.findByGAV(mvnGroup,artifact,version,s));
//TODO: Not including the traces does not significantly improve the perf, what else?
if(inclTraces) {
final List<Trace> traces = this.traceRepository.findByApp(app);
if(!traces.isEmpty())
app.setTraces(traces);
for(Dependency dep: app.getDependencies()){
dep.setTraces(this.traceRepository.findTracesOfLibrary(app, dep.getLib()));
}
}
return new ResponseEntity<Application>(app, HttpStatus.OK);
}
catch(EntityNotFoundException enfe) {
return new ResponseEntity<Application>(HttpStatus.NOT_FOUND);
}
}
/**
* Returns the {@link Application} with dependencies on the given digest.
*
* @param digest a {@link java.lang.String} object.
* @return 404 {@link HttpStatus#NOT_FOUND} if no application depends on the given digest or digest does not exists, 200 {@link HttpStatus#OK} if the applications are found
*/
@RequestMapping(value = "/{digest}/apps", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@JsonView(Views.AppDepDetails.class)
public ResponseEntity<List<Application>> getLibraryApplications(@PathVariable String digest) {
try {
// To throw an exception if the entity is not found
Library l = LibraryRepository.FILTER.findOne(this.libRepository.findByDigest(digest));
return new ResponseEntity<List<Application>>( this.appRepository.findAppsWithDigest(digest), HttpStatus.OK);
}
catch(EntityNotFoundException enfe) {
return new ResponseEntity<List<Application>>(HttpStatus.NOT_FOUND);
}
}
/**
* Resolve schema from type schema.
*
* @param schemaImplementation the schema implementation
* @param components the components
* @param jsonView the json view
* @param annotations the annotations
* @return the schema
*/
public static Schema resolveSchemaFromType(Class<?> schemaImplementation, Components components,
JsonView jsonView, Annotation[] annotations) {
Schema schemaObject = extractSchema(components, schemaImplementation, jsonView, annotations);
if (schemaObject != null && StringUtils.isBlank(schemaObject.get$ref())
&& StringUtils.isBlank(schemaObject.getType()) && !(schemaObject instanceof ComposedSchema)) {
// default to string
schemaObject.setType("string");
}
return schemaObject;
}
@JsonView(Views.Public.class)
@RequestMapping(value = "/answer/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getAnswer(@PathVariable("id") long id) {
logger.info("Fetching Answer with id {}", id);
Answer answer = answerService.getById(id);
if (answer == null) {
logger.error("Answer with id {} not found.", id);
return new ResponseEntity(new CustomErrorType("Answer with id " + id
+ " not found"), HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Answer>(answer, HttpStatus.OK);
}
/**
* NOTE review, don't like to have business logic here... but overkill to move somewhere else
*
* Indicates if this task and all its sub tasks are finished.
*
* @return {@code true} if this task and all its subtasks are finished else {@code false}
*/
@JsonProperty
@JsonView(View.PollableSummary.class)
public boolean isAllFinished() {
boolean currentTaskFinished = (getFinishedDate() != null);
boolean allSubtasksFinished = true;
// If parent task is finished, check all its subtasks
if (currentTaskFinished) {
if (getSubTasks() != null) {
int numSubtasks = getSubTasks().size();
// if not all expected subtasks have run => not finished
if (numSubtasks < getExpectedSubTaskNumber()) {
allSubtasksFinished = false;
}
else {
// a task is finished only if all its subtasks are finished
for (PollableTask pollableTask : subTasks) {
if (!pollableTask.isAllFinished()) {
allSubtasksFinished = false;
break;
}
}
}
}
}
return currentTaskFinished && allSubtasksFinished;
}
/**
* Filter out undesired attributes from the given model.
* The return value can be either another {@link Map} or a single value object.
* <p>The default implementation removes {@link BindingResult} instances and entries
* not included in the {@link #setModelKeys renderedAttributes} property.
* @param model the model, as passed on to {@link #renderMergedOutputModel}
* @return the value to be rendered
*/
@Override
protected Object filterModel(Map<String, Object> model) {
Map<String, Object> result = new HashMap<String, Object>(model.size());
Set<String> modelKeys = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet());
for (Map.Entry<String, Object> entry : model.entrySet()) {
if (!(entry.getValue() instanceof BindingResult) && modelKeys.contains(entry.getKey()) &&
!entry.getKey().equals(JsonView.class.getName()) &&
!entry.getKey().equals(FilterProvider.class.getName())) {
result.put(entry.getKey(), entry.getValue());
}
}
return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
}
@JsonView(Views.Public.class)
@RequestMapping(value = "/tag/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getQuestion(@PathVariable("id") long id) {
logger.info("Fetching Tag with id {}", id);
Tag tag = tagService.getById(id);
if (tag == null) {
logger.error("Question with id {} not found.", id);
return new ResponseEntity(new CustomErrorType("Tag with id " + id
+ " not found"), HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Tag>(tag, HttpStatus.OK);
}
@Override
public Class[] getHbaseDependencyClasses() {
return new Class[] {
HConstants.class, org.apache.hadoop.hbase.protobuf.generated.ClientProtos.class,
org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.class, Put.class,
RpcServer.class, CompatibilityFactory.class, JobUtil.class, TableMapper.class, FastLongHistogram.class,
Snapshot.class, ZooKeeper.class, Channel.class, Message.class, UnsafeByteOperations.class, Lists.class,
Tracer.class, MetricRegistry.class, ArrayUtils.class, ObjectMapper.class, Versioned.class,
JsonView.class, ZKWatcher.class, CacheLoader.class
};
}
@JsonView(ViewFilters.BackupIgnore.class)
public List<EnabledEndpoint> getEnabledEndpoints() throws Exception {
if (enabledEndpoints == null) {
enabledEndpoints = OverrideService.getInstance().getEnabledEndpoints(this.getPathId(), clientUUID, this.filters);
}
return enabledEndpoints;
}
@JsonView(MyJacksonView1.class)
@SuppressWarnings("unused")
JacksonViewBean handleAndSendToJsonView() {
JacksonViewBean payload = new JacksonViewBean();
payload.setWithView1("with");
payload.setWithView2("with");
payload.setWithoutView("without");
return payload;
}
@JsonView(Views.Public.class)
@RequestMapping(value = "/tags", method = RequestMethod.GET)
public ResponseEntity<List<Tag>> listAllQuestions() {
List<Tag> tags = tagService.getAll();
if (tags.isEmpty()) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
// You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<Tag>>(tags, HttpStatus.OK);
}
private Class<?> extractViewClass(JsonView annotation, Object conversionHint) {
Class<?>[] classes = annotation.value();
if (classes.length != 1) {
throw new IllegalArgumentException(
"@JsonView only supported for handler methods with exactly 1 class argument: " + conversionHint);
}
return classes[0];
}
/**
* <p>getAllBugLibraries.</p>
*
* @param bugid a {@link java.lang.String} object.
* @return a {@link org.springframework.http.ResponseEntity} object.
*/
@RequestMapping(value = "/{bugid}/libraries", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@JsonView(Views.Default.class)
public ResponseEntity<List<Library>> getAllBugLibraries(@PathVariable String bugid) {
Bug bug = null;
try { bug = BugRepository.FILTER.findOne(this.bugRepository.findByBugId(bugid)); }
catch (EntityNotFoundException e) { return new ResponseEntity<List<Library>>(HttpStatus.NOT_FOUND); }
return new ResponseEntity<List<Library>>(this.libRepository.findJPQLVulnerableLibrariesByBug(bugid), HttpStatus.OK);
}
@Override
public Class[] getHbaseDependencyClasses() {
return new Class[] {
HConstants.class, org.apache.hadoop.hbase.protobuf.generated.ClientProtos.class,
org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.class, Put.class,
RpcServer.class, CompatibilityFactory.class, JobUtil.class, TableMapper.class, FastLongHistogram.class,
Snapshot.class, ZooKeeper.class, Channel.class, Message.class, UnsafeByteOperations.class, Lists.class,
Tracer.class, MetricRegistry.class, ArrayUtils.class, ObjectMapper.class, Versioned.class, JsonView.class,
ZKWatcher.class
};
}
/**
* Gets repository matching the given name
*
* @param repositoryName To filer on the name. Can be {@code null}
* @return List of {@link Repository}s
*/
@JsonView(View.Repository.class)
@RequestMapping(value = "/api/repositories", params = "name", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public List<Repository> getRepositories(@RequestParam(value = "name", required = true) String repositoryName) {
return repositoryService.findRepositoriesIsNotDeletedOrderByName(repositoryName);
}