下面列出了怎么用org.springframework.web.bind.annotation.RequestHeader的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* DELETE /pet/{petId} : Deletes a pet
*
* @param petId Pet id to delete (required)
* @param apiKey (optional)
* @return successful operation (status code 200)
* or Invalid pet value (status code 400)
*/
@ApiOperation(value = "Deletes a pet", nickname = "deletePet", notes = "", 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"),
@ApiResponse(code = 400, message = "Invalid pet value") })
@RequestMapping(value = "/pet/{petId}",
method = RequestMethod.DELETE)
default ResponseEntity<Void> deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) Optional<String> apiKey) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
@RequestMapping(value = "token", method = { RequestMethod.POST, RequestMethod.GET })
public ResponseEntity<String> getAccessToken(@RequestParam("code") String authorizationCode,
@RequestParam("redirect_uri") String redirectUri,
@RequestHeader(value = "Authorization", required = false) String authz,
@RequestParam("client_id") String clientId, @RequestParam("client_secret") String clientSecret, Model model)
throws BadCredentialsException {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("code", authorizationCode);
parameters.put("redirect_uri", redirectUri);
String token;
try {
token = this.sessionManager.verify(authorizationCode, Pair.of(clientId, clientSecret));
} catch (OAuthAccessException e) {
return handleAccessException(e);
}
HttpHeaders headers = new HttpHeaders();
headers.set("Cache-Control", "no-store");
headers.setContentType(MediaType.APPLICATION_JSON);
String response = String.format("{\"access_token\":\"%s\"}", token);
return new ResponseEntity<String>(response, headers, HttpStatus.OK);
}
@PostMapping(produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE })
public ApplicationShutdown
shutdownFlowableJobExecutor(@RequestHeader(name = "x-cf-applicationid", required = false) String applicationId,
@RequestHeader(name = "x-cf-instanceid", required = false) String applicationInstanceId,
@RequestHeader(name = "x-cf-instanceindex", required = false) String applicationInstanceIndex) {
CompletableFuture.runAsync(() -> {
LOGGER.info(MessageFormat.format(Messages.APP_SHUTDOWN_REQUEST, applicationId, applicationInstanceId,
applicationInstanceIndex));
flowableFacade.shutdownJobExecutor();
})
.thenRun(() -> LOGGER.info(MessageFormat.format(Messages.APP_SHUTDOWNED, applicationId, applicationInstanceId,
applicationInstanceIndex)));
return ImmutableApplicationShutdown.builder()
.status(getShutdownStatus())
.applicationInstanceIndex(Integer.parseInt(applicationInstanceIndex))
.applicationId(applicationId)
.applicationInstanceId(applicationInstanceId)
.build();
}
@RequestMapping(value="/dj/simple/approvals", method = RequestMethod.PUT)
@ResponseBody
public List<CmsDpmtApproval> dpmtApprove(
@RequestBody CmsDpmtApproval[] approvals,
@RequestHeader(value="X-Cms-Scope", required = false) String scope,
@RequestHeader(value="X-Cms-User", required = true) String userId,
@RequestHeader(value="X-Approval-Token", required = false) String approvalToken
){
List<CmsDpmtApproval> toApprove = new ArrayList<>();
for (CmsDpmtApproval approval : approvals) {
approval.setUpdatedBy(userId);
toApprove.add(approval);
}
return djManager.updateApprovalList(toApprove, approvalToken);
}
@RequestMapping(value="/cm/relations/{relId}", method = RequestMethod.GET)
@ResponseBody
@ReadOnlyDataAccess
public CmsCIRelation getRelationById(
@PathVariable long relId,
@RequestHeader(value="X-Cms-Scope", required = false) String scope) {
CmsCIRelation rel = cmManager.getRelationById(relId);
if (rel == null) throw new CmsException(CmsError.CMS_NO_RELATION_WITH_GIVEN_ID_ERROR,
"There is no relation with this id");
scopeVerifier.verifyScope(scope, rel);
return rel;
}
/**
* <p>isApplicationExisting.</p>
*
* @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:.+}", method = RequestMethod.OPTIONS)
public ResponseEntity<Application> isApplicationExisting(
@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<Application>(HttpStatus.NOT_FOUND);
}
try {
ApplicationRepository.FILTER.findOne(this.appRepository.findByGAV(mvnGroup, artifact, version, s));
return new ResponseEntity<Application>(HttpStatus.OK);
}
catch(EntityNotFoundException enfe) {
return new ResponseEntity<Application>(HttpStatus.NOT_FOUND);
}
}
@RequestMapping(value = "/api/{projectId}/entities/{name}/{uuid}", method = RequestMethod.DELETE, headers = "Accept=application/json")
public @ResponseBody
StatusResponse deleteEntityData(@PathVariable("projectId") String projectId, @PathVariable("name") String entityName,
@PathVariable("uuid") String uuid,
@RequestHeader(value = "authToken", required = false) String authToken) {
StatusResponse res = new StatusResponse();
JSONObject authRes = authService.authorize(projectId,authToken,"USER");
if(!authRes.getBoolean(SUCCESS)){
res.setStatus("Unauthorized");
return res;
}
DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_"+entityName);
BasicDBObject queryObject = new BasicDBObject();
queryObject.append("_id", new ObjectId(uuid));
dbCollection.remove(queryObject);
res.setStatus("DELETED");
return res;
}
@RequestMapping(value="/dj/simple/deployments/count", method = RequestMethod.GET)
@ResponseBody
public Map<String, Long> countDeployment(
@RequestParam(value="nsPath", required = true) String nsPath,
@RequestParam(value="deploymentState", required = false) String state,
@RequestParam(value="recursive", required = false) Boolean recursive,
@RequestParam(value="groupBy", required = false) String groupBy,
@RequestHeader(value="X-Cms-Scope", required = false) String scope){
if (groupBy != null) {
return djManager.countDeploymentGroupByNsPath(nsPath, state);
} else{
long count = djManager.countDeployments(nsPath, state, recursive);
Map<String, Long> result = new HashMap<>();
result.put("Total", count);
return result;
}
}
@RequestMapping(method=RequestMethod.PUT, value="/dj/simple/cis/{ciId}")
@ResponseBody
public CmsRfcCISimple updateRfcCi(@PathVariable long ciId,
@RequestBody CmsRfcCISimple rfcSimple,
@RequestHeader(value="X-Cms-User", required = false) String userId,
@RequestHeader(value="X-Cms-Scope", required = false) String scope) throws DJException {
scopeVerifier.verifyScope(scope, rfcSimple);
rfcSimple.setCiId(ciId);
CmsRfcCI rfc = cmsUtil.custRfcCISimple2RfcCI(rfcSimple);
String[] attrProps = null;
if (rfcSimple.getCiAttrProps().size() >0) {
attrProps = rfcSimple.getCiAttrProps().keySet().toArray(new String[rfcSimple.getCiAttrProps().size()]);
}
rfc.setUpdatedBy(userId);
return cmsUtil.custRfcCI2RfcCISimple(cmdjManager.upsertCiRfc(rfc, userId), attrProps);
}
@PostMapping("/api/payment/webhook/stripe/payment")
public ResponseEntity<String> receivePaymentConfirmation(@RequestHeader(value = "Stripe-Signature") String stripeSignature,
HttpServletRequest request) {
return RequestUtils.readRequest(request)
.map(content -> {
var result = ticketReservationManager.processTransactionWebhook(content, stripeSignature, PaymentProxy.STRIPE, Map.of());
if(result.isSuccessful()) {
return ResponseEntity.ok("OK");
} else if(result.isError()) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result.getReason());
}
return ResponseEntity.ok(result.getReason());
})
.orElseGet(() -> ResponseEntity.badRequest().body("NOK"));
}
/**
* This operation updates the Network Service Descriptor (NSD)
*
* @param networkServiceDescriptor : the Network Service Descriptor to be updated
* @param id : the id of Network Service Descriptor
* @return networkServiceDescriptor: the Network Service Descriptor updated
*/
@ApiOperation(
value = "Update a Network Service Descriptor",
notes =
"Takes a Network Service Descriptor and updates the Descriptor with the id provided in the URL with the Descriptor from the request body")
@RequestMapping(
value = "{id}",
method = RequestMethod.PUT,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.ACCEPTED)
public NetworkServiceDescriptor update(
@RequestBody @Valid NetworkServiceDescriptor networkServiceDescriptor,
@PathVariable("id") String id,
@RequestHeader(value = "project-id") String projectId)
throws NotFoundException, BadRequestException {
return networkServiceDescriptorManagement.update(networkServiceDescriptor, projectId);
}
@ApiOperation(value = "Stop a VNFC instance", notes = "Stops the specified VNFC Instance")
@RequestMapping(
value = "{id}/vnfrecords/{idVnf}/vdunits/{idVdu}/vnfcinstances/{idVNFCI}/stop",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public void stopVNFCInstance(
@PathVariable("id") String id,
@PathVariable("idVnf") String idVnf,
@PathVariable("idVdu") String idVdu,
@PathVariable("idVNFCI") String idVNFCI,
@RequestHeader(value = "project-id") String projectId)
throws NotFoundException, BadFormatException, ExecutionException, InterruptedException {
log.debug("stop a VNF component instance");
networkServiceRecordManagement.stopVNFCInstance(id, idVnf, idVdu, idVNFCI, projectId);
}
/**
* 清除token(注销登录)
*/
@SysLog("登出")
@DeleteMapping("/logout")
@ApiOperation(value = "登出")
public ApiResponse logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
if (StringUtils.isBlank(authHeader)) {
return fail("退出失败,token 为空");
}
//注销当前用户
String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StringUtils.EMPTY).trim();
OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
tokenStore.removeAccessToken(accessToken);
OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
tokenStore.removeRefreshToken(refreshToken);
return success("注销成功");
}
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<AuthenticationResponse> login(
@RequestBody AuthenticationRequest request,
@RequestHeader(IndegoWebConstants.HEADER_AUTHORIZATION) String authorization)
throws IndegoServiceException
{
if ( authorization == null || !authorization.startsWith("Basic ") ) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
byte[] userPassBytes = Base64.getDecoder().decode(authorization.substring(6).trim());
String[] userPass = new String(userPassBytes).split(":");
String username = userPass.length > 0 ? userPass[0] : "";
String password = userPass.length > 1 ? userPass[1] : "";
String userId = srvAuthentication.authenticate(username, password);
if ( userId == null ) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
IndegoContext context = srvContextHandler.createContextForUser(userId);
AuthenticationResponse result = new AuthenticationResponse();
result.setAlmSn(context.getDeviceSerial());
result.setContextId(context.getContext());
result.setUserId(context.getUserId());
return new ResponseEntity<AuthenticationResponse>(result, HttpStatus.OK);
}
public ResponseEntity<String> getPipelineRunLog(@ApiParam(value = "Name of the organization",required=true ) @PathVariable("organization") String organization,
@ApiParam(value = "Name of the pipeline",required=true ) @PathVariable("pipeline") String pipeline,
@ApiParam(value = "Name of the run",required=true ) @PathVariable("run") String run,
@ApiParam(value = "Start position of the log") @RequestParam(value = "start", required = false) Integer start,
@ApiParam(value = "Set to true in order to download the file, otherwise it's passed as a response body") @RequestParam(value = "download", required = false) Boolean download,
@RequestHeader(value = "Accept", required = false) String accept) throws Exception {
// do some magic!
return new ResponseEntity<String>(HttpStatus.OK);
}
@RequestMapping( method = RequestMethod.POST, value = "{clientVersion}/orgUnits/{id}/updateDataSets" )
@ResponseBody
public DataSetList checkUpdatedDataSet( @PathVariable String clientVersion, @PathVariable int id,
@RequestBody DataSetList dataSetList, @RequestHeader( "accept-language" ) String locale )
{
DataSetList returnList = facilityReportingService.getUpdatedDataSet( dataSetList, getUnit( id ), locale );
returnList.setClientVersion( clientVersion );
return returnList;
}
@ApiOperation(value = "", notes = "Retrieve branch run details for an organization pipeline", response = PipelineRun.class, authorizations = {
@Authorization(value = "jenkins_auth")
}, tags={ "blueOcean", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved run details", response = PipelineRun.class),
@ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password"),
@ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password") })
@RequestMapping(value = "/blue/rest/organizations/{organization}/pipelines/{pipeline}/branches/{branch}/runs/{run}",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<PipelineRun> getPipelineBranchRun(@ApiParam(value = "Name of the organization",required=true ) @PathVariable("organization") String organization,@ApiParam(value = "Name of the pipeline",required=true ) @PathVariable("pipeline") String pipeline,@ApiParam(value = "Name of the branch",required=true ) @PathVariable("branch") String branch,@ApiParam(value = "Name of the run",required=true ) @PathVariable("run") String run, @RequestHeader(value = "Accept", required = false) String accept) throws Exception;
/**
* Standard file upload.
*/
@PostMapping
public Mono<ResponseEntity<UploadResult>> uploadHandler(@RequestHeader HttpHeaders headers, @RequestBody Flux<ByteBuffer> body) {
long length = headers.getContentLength();
if (length < 0) {
throw new UploadFailedException(HttpStatus.BAD_REQUEST.value(), Optional.of("required header missing: Content-Length"));
}
String fileKey = UUID.randomUUID().toString();
Map<String, String> metadata = new HashMap<String, String>();
MediaType mediaType = headers.getContentType();
if (mediaType == null) {
mediaType = MediaType.APPLICATION_OCTET_STREAM;
}
log.info("[I95] uploadHandler: mediaType{}, length={}", mediaType, length);
CompletableFuture<PutObjectResponse> future = s3client
.putObject(PutObjectRequest.builder()
.bucket(s3config.getBucket())
.contentLength(length)
.key(fileKey.toString())
.contentType(mediaType.toString())
.metadata(metadata)
.build(),
AsyncRequestBody.fromPublisher(body));
return Mono.fromFuture(future)
.map((response) -> {
checkResult(response);
return ResponseEntity
.status(HttpStatus.CREATED)
.body(new UploadResult(HttpStatus.CREATED, new String[] {fileKey}));
});
}
public ResponseEntity<MultibranchPipeline> getPipelineBranches(@ApiParam(value = "Name of the organization",required=true ) @PathVariable("organization") String organization,
@ApiParam(value = "Name of the pipeline",required=true ) @PathVariable("pipeline") String pipeline,
@RequestHeader(value = "Accept", required = false) String accept) throws Exception {
// do some magic!
if (accept != null && accept.contains("application/json")) {
return new ResponseEntity<MultibranchPipeline>(objectMapper.readValue("", MultibranchPipeline.class), HttpStatus.OK);
}
return new ResponseEntity<MultibranchPipeline>(HttpStatus.OK);
}
@ApiOperation(value = "", notes = "Retrieve user favorites details for an organization", response = UserFavorites.class, authorizations = {
@Authorization(value = "jenkins_auth")
}, tags={ "blueOcean", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved users favorites details", response = UserFavorites.class),
@ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password"),
@ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password") })
@RequestMapping(value = "/blue/rest/users/{user}/favorites",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<UserFavorites> getUserFavorites(@ApiParam(value = "Name of the user",required=true ) @PathVariable("user") String user, @RequestHeader(value = "Accept", required = false) String accept) throws Exception;
/**
* 退出
*
* @param access_token
*/
@GetMapping("/sys/logout")
public void logout(String access_token, @RequestHeader(required = false, value = "Authorization") String token) {
if (StringUtils.isBlank(access_token)) {
if (StringUtils.isNoneBlank(token)) {
access_token = token.substring(OAuth2AccessToken.BEARER_TYPE.length() + 1);
}
}
oauth2Client.removeToken(access_token);
}
@RequestMapping(value="/cm/simple/vars", method = RequestMethod.GET)
@ResponseBody
public String updateCmSimpleVar(@RequestParam(value = "name" , required = true) String varName,
@RequestParam(value = "value" , required = true) String varValue,
@RequestHeader(value="X-Cms-User", required = false) String user){
if (varName != null && varValue != null) {
cmManager.updateCmSimpleVar(varName, varValue, null, user!=null?user:"oneops-system");
return "cms var '"+ varName + "' updated";
}
return "";
}
public ResponseEntity<TruststoreInfo> getTruststoreInfo(@RequestHeader(value = "Accept", required = false) String accept) throws Exception {
// do some magic!
if (accept != null && accept.contains("application/json")) {
return new ResponseEntity<TruststoreInfo>(objectMapper.readValue("", TruststoreInfo.class), HttpStatus.OK);
}
return new ResponseEntity<TruststoreInfo>(HttpStatus.OK);
}
@RequestMapping( method = RequestMethod.POST, value = "{clientVersion}/orgUnits/{id}/activitiyplan" )
@ResponseBody
public MobileModel updatePrograms( @PathVariable String clientVersion, @PathVariable int id,
@RequestHeader( "accept-language" ) String locale, @RequestBody ModelList programsFromClient )
{
MobileModel model = new MobileModel();
model.setClientVersion( clientVersion );
model.setServerCurrentDate( new Date() );
return model;
}
@RequestMapping(path = "/{carId}/documents", consumes = "multipart/form-data", produces = "application/json", method = RequestMethod.POST)
public Car uploadCarDocuments(@RequestHeader("source") String source,
@PathVariable("carId") String carId,
@RequestParam(name = "documentFile") MultipartFile documentFile,
@RequestParam(name = "type") String type) {
return null;
}
@ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", })
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid user supplied"),
@ApiResponse(code = 404, message = "User not found") })
@RequestMapping(value = "/user/{username}",
method = RequestMethod.PUT)
ResponseEntity<Void> updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body, @RequestHeader(value = "Accept", required = false) String accept) throws Exception;
@GetMapping("/{id}/subpath/")
public ValidationDummy subpath(
@RequestHeader String headerA,
@RequestHeader("headerB") String headerB,
@PathVariable Integer id,
@RequestParam("requestParamA") @OpenApiExample(name = "customValidationDummy", description = "CustomDescription", key = "CUSTOM_EXAMPLE_KEY_1")
String requestParamA,
@RequestParam String requestParamB,
@RequestParam(name = "requestParamC", required = false) String requestParamC
) {
return null;
}
public ResponseEntity<PipelineRunNodes> getPipelineRunNodes(@ApiParam(value = "Name of the organization",required=true ) @PathVariable("organization") String organization,
@ApiParam(value = "Name of the pipeline",required=true ) @PathVariable("pipeline") String pipeline,
@ApiParam(value = "Name of the run",required=true ) @PathVariable("run") String run,
@RequestHeader(value = "Accept", required = false) String accept) throws Exception {
// do some magic!
if (accept != null && accept.contains("application/json")) {
return new ResponseEntity<PipelineRunNodes>(objectMapper.readValue("", PipelineRunNodes.class), HttpStatus.OK);
}
return new ResponseEntity<PipelineRunNodes>(HttpStatus.OK);
}
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(defaultValue = "Hello World!") String message,
@RequestHeader HttpHeaders headers) {
this.sender.send(message);
this.httpSpan = this.tracer.currentSpan();
// tag what was propagated
Tags.BAGGAGE_FIELD.tag(COUNTRY_CODE, httpSpan);
return new Greeting(message);
}
/**
* Deletes the Security with the id_s
*
* @param idNSD : The NSD id
* @param idS : The Security id @
*/
@ApiOperation(value = "", notes = "", hidden = true)
@RequestMapping(value = "{id}/security/{idS}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteSecurity(
@PathVariable("id") String idNSD,
@PathVariable("idS") String idS,
@RequestHeader(value = "project-id") String projectId)
throws NotFoundException {
networkServiceDescriptorManagement.deleteSecurty(idNSD, idS, projectId);
}