下面列出了怎么用org.springframework.web.bind.annotation.CrossOrigin的API类实例代码及写法,或者点击链接到github查看源代码。
@GetMapping(
path = "/api/{namespace}/{extension}/{version}",
produces = MediaType.APPLICATION_JSON_VALUE
)
@CrossOrigin
public ExtensionJson getExtension(@PathVariable String namespace,
@PathVariable String extension,
@PathVariable String version) {
for (var registry : getRegistries()) {
try {
return registry.getExtension(namespace, extension, version);
} catch (NotFoundException exc) {
// Try the next registry
}
}
return ExtensionJson.error("Extension not found: " + namespace + "." + extension + " version " + version);
}
@GetMapping(
path = "/api/{namespace}/{extension}/reviews",
produces = MediaType.APPLICATION_JSON_VALUE
)
@CrossOrigin
public ReviewListJson getReviews(@PathVariable String namespace,
@PathVariable String extension) {
for (var registry : getRegistries()) {
try {
return registry.getReviews(namespace, extension);
} catch (NotFoundException exc) {
// Try the next registry
}
}
return ReviewListJson.error("Extension not found: " + namespace + "." + extension);
}
@GetMapping("/vscode/asset/{namespace}/{extensionName}/{version}/{assetType:.+}")
@CrossOrigin
@Transactional
public ResponseEntity<byte[]> getFile(@PathVariable String namespace,
@PathVariable String extensionName,
@PathVariable String version,
@PathVariable String assetType) {
var extVersion = repositories.findVersion(version, extensionName, namespace);
if (extVersion == null)
throw new NotFoundException();
var fileNameAndResource = getFile(extVersion, assetType);
if (fileNameAndResource == null || fileNameAndResource.getSecond() == null)
throw new NotFoundException();
if (fileNameAndResource.getSecond().getType().equals(FileResource.DOWNLOAD)) {
var extension = extVersion.getExtension();
extension.setDownloadCount(extension.getDownloadCount() + 1);
search.updateSearchEntry(extension);
}
var content = fileNameAndResource.getSecond().getContent();
var headers = getFileResponseHeaders(fileNameAndResource.getFirst());
return new ResponseEntity<>(content, headers, HttpStatus.OK);
}
/**
* [get] receive source and cache it
*
* @param productName
* Product name
* @param component
* Component name of product
* @param key
* The unique identify for source in component's resource file
* @param version
* Product version
* @param source
* The english string which need translate
* @param commentForSource
* The comment for source
* @param req
* @return SourceAPIResponseDTO The object which represents response status
*/
@CrossOrigin
@RequestMapping(value = L10NAPIV1.CREATE_SOURCE_GET, produces = { API.API_CHARSET })
@ResponseStatus(HttpStatus.OK)
public SourceAPIResponseDTO addStringForTranslation(
@PathVariable(value = APIParamName.PRODUCT_NAME) String productName,
@PathVariable(value = APIParamName.COMPONENT) String component,
@PathVariable(value = APIParamName.KEY) String key,
@RequestParam(value = APIParamName.VERSION, required = true) String version,
@RequestParam(value = APIParamName.SOURCE, required = false) String source,
@RequestParam(value = APIParamName.COMMENT_SOURCE, required = false) String commentForSource,
@RequestParam(value = APIParamName.SOURCE_FORMAT, required = false) String sourceFormat,
HttpServletRequest req) throws Exception{
source = source == null ? "" : source;
LOGGER.info("The request url is: {}", req.getRequestURL());
LOGGER.info("The parameters are: version=" + version + ", key=" + key + ", source=" + source
+ ", commentForSource=" + commentForSource);
StringSourceDTO stringSourceDTO = createSourceDTO(productName, version, component, key, source, commentForSource, sourceFormat);
boolean isSourceCached = sourceService.cacheSource(stringSourceDTO);
SourceAPIResponseDTO sourceAPIResponseDTO = new SourceAPIResponseDTO();
setResponseStatus(sourceAPIResponseDTO, isSourceCached);
return sourceAPIResponseDTO;
}
@Override
protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
Class<?> beanType = handlerMethod.getBeanType();
CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);
if (typeAnnotation == null && methodAnnotation == null) {
return null;
}
CorsConfiguration config = new CorsConfiguration();
updateCorsConfig(config, typeAnnotation);
updateCorsConfig(config, methodAnnotation);
if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
config.addAllowedMethod(allowedMethod.name());
}
}
return config.applyPermitDefaultValues();
}
@GetMapping("/getTaskCalendar/{pid}/{uid}")
@CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<CalendarListResource> getTaskCalendar(@PathVariable("pid") Long pid, @PathVariable("uid") Long uid) {
// service call
TaskListResource tlr = service.getAllTaskOfUserAndProgram(uid, pid);
List<CalendarResource> cl = new ArrayList<CalendarResource>();
List<Task> tl = tlr.getTaskList();
for(Task t: tl) {
CalendarResource cr = new CalendarResource();
cr.setTitle(t.getName());
cr.setStart(t.getStartTime());
cr.setEnd(t.getDeadline());
cl.add(cr);
}
CalendarListResource clr = new CalendarListResource();
clr.setEvents(cl);
return new ResponseEntity<CalendarListResource>(clr, HttpStatus.OK);
}
@CrossOrigin
@RequestMapping(value = L10NAPIV1.SYNC_TRANSLATION_GIT_L10N, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public Response notifyCommit(@RequestBody SynchFile2GitReq synchFile2GitReq) {
try {
Send2GitSchedule.Send2GitQueue.put(synchFile2GitReq);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
Thread.currentThread().interrupt();
return APIResponseStatus.INTERNAL_SERVER_ERROR;
}
return APIResponseStatus.OK;
}
@CrossOrigin(origins = "*")
@GetMapping("/getSavedResource")
public ResponseEntity<byte[]> getSavedResource(@RequestParam(value = "path") String path) {
HttpStatus httpStatus = HttpStatus.OK;
byte[] media = new byte[0];
try (InputStream in =
new FileInputStream(Paths.get(URLDecoder.decode(path, "UTF-8")).toString())) {
media = ByteStreams.toByteArray(in);
} catch (IOException e) {
httpStatus = HttpStatus.NOT_FOUND;
logger.warning("Cannot fetch image: " + path);
}
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
headers.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<>(media, headers, httpStatus);
}
@CrossOrigin(origins = "*")
@RequestMapping(value = "/unzipAndImport", method = RequestMethod.POST)
public Callable<String> unzipAndImport(
@RequestParam("file") MultipartFile file,
@RequestParam("projectName") String projectName) {
return () -> {
ProjectResponse projectResponse =
projectManager.createProject(projectName);
if (projectResponse.isSuccess()) {
File tempFile = File.createTempFile(projectName, ".zip");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(file.getInputStream(), out);
}
ProjectRecord projectRecord = projectResponse.getProjectList().get(0);
testCasesImportExportManager.unzipAndImport(
tempFile, projectRecord.getProjectId());
}
return DONE;
};
}
@Override
protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
Class<?> beanType = handlerMethod.getBeanType();
CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);
if (typeAnnotation == null && methodAnnotation == null) {
return null;
}
CorsConfiguration config = new CorsConfiguration();
updateCorsConfig(config, typeAnnotation);
updateCorsConfig(config, methodAnnotation);
if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
config.addAllowedMethod(allowedMethod.name());
}
}
return config.applyPermitDefaultValues();
}
@CrossOrigin(origins = "*")
@RequestMapping("/selectedDeviceChanged")
public Callable<String> selectedDeviceChanged(@RequestParam(value = "deviceId") String deviceId) {
return () -> {
devicesDriverManager.setSelectedDeviceByDeviceId(deviceId);
return DONE;
};
}
@CrossOrigin(origins = "*")
@RequestMapping("/zoom")
public Callable<String> zoom(
@RequestParam(value = "x1") Integer x1,
@RequestParam(value = "y1") Integer y1,
@RequestParam(value = "x2") Integer x2,
@RequestParam(value = "y2") Integer y2,
@RequestParam(value = "isZoomIn") Boolean isZoomin) {
return () -> {
workflowManager.recordAndZoom(x1, y1, x2, y2, isZoomin);
return DONE;
};
}
@CrossOrigin(origins = "*")
@RequestMapping("/doubleclick")
public Callable<String> doubleClick(
@RequestParam(value = "x") Integer x, @RequestParam(value = "y") Integer y) {
return () -> {
workflowManager.recordAndClick(x, y, DOUBLE_CLICK);
return DONE;
};
}
@CrossOrigin(origins = "*")
@PostMapping(value = "/createzip", produces = "application/zip")
public void zipFiles(@RequestBody Map<String, String> request, HttpServletResponse response)
throws IOException {
// setting headers
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("Content-Disposition", "attachment; filename=\"starter.zip\"");
response.addHeader("Content-Type", "application/zip");
prepareFiles(request.get("engine"), request.get("commands"), response);
}
@CrossOrigin(origins = "*")
@RequestMapping("/initDevicesList")
public Callable<String> initDevicesList(@RequestParam(value = "deviceId") List<String> devices) {
return () -> {
// reset minicap
MinicapServerManager.getInstance().clearAll();
devicesDriverManager.initDevicesList(devices, false);
return DONE;
};
}
/**
* 请假列表
* @param qjsq
* @return
*/
@RequestMapping(value = "/getQjList")
@CrossOrigin
public JSONArray getQjList(Qjsq qjsq) {
List<Qjsq> list = qjsqService.getQjList(qjsq);
String jsonStr = JsonUtil.serializeDate(list);
return JSON.parseArray(jsonStr);
}
/**
* 请假详情
* @param qjsq
* @return
*/
@RequestMapping(value = "/getQjXx")
@CrossOrigin
public JSONObject getQjXx(Qjsq qjsq) {
Qjsq qjsq1 = qjsqService.getQj(qjsq);
String jsonStr = JsonUtil.serialize(qjsq1);
return JSON.parseObject(jsonStr);
}
/**
* 批准下级员工的请假申请;(权限)
* @param qjsq
* @return
*/
@RequestMapping(value = "/agreeQj")
@CrossOrigin
public JSONObject agreeQj(Qjsq qjsq) {
try{
qjsqService.agreeQj(qjsq);
}catch (Exception e){
return JSON.parseObject("{success:false,msg:\"审批失败!\"}");
}
return JSON.parseObject("{success:true,msg:\"审批成功!\"}");
}
/**
* 公告
* @return
*/
@RequestMapping(value = "/gsgg")
@ResponseBody
@CrossOrigin
public JSONArray getGgList() {
List<Gsgg> list = ggService.getGgList();
String jsonStr = JsonUtil.serializeDate(list);
return JSON.parseArray(jsonStr);
}
@CrossOrigin(origins = "*")
@RequestMapping("/initMiniCap")
public Callable<String> initMiniCap(@RequestParam(value = "deviceId") String deviceId) {
return () -> {
AndroidDeviceDriver driver = devicesDriverManager.getAndroidDriverByDeviceId(deviceId);
int rotation =
driver.getDevice().getOrientation().equals(DeviceOrientation.PORTRAIT) ? 0 : 90;
return MinicapUtil.startMinicap(driver, rotation);
};
}
@CrossOrigin(origins = "*")
@RequestMapping("/dragWithStartEndContext")
public Callable<String> dragWithStartEndContext(
@RequestParam(value = "startX") int startX,
@RequestParam(value = "startY") int startY,
@RequestParam(value = "endX") int endX,
@RequestParam(value = "endY") int endY) {
return () -> {
workflowManager.recordDragWithStartEndContext(
new Position(startX, startY), new Position(endX, endY));
return DONE;
};
}
@CrossOrigin(origins = "*")
@RequestMapping(value = "/setUserPresetGlobalVariable", method = RequestMethod.POST)
public Callable<String> setUserPresetGlobalVariable(@RequestBody String globalVariableStr) {
return () -> {
workflowManager.setGlobalVariableMapStringFormat(globalVariableStr);
return DONE;
};
}
@CrossOrigin(origins = "*")
@RequestMapping("/loadWorkflow")
public String loadWorkflow(@RequestParam(value = "uuidStr") String uuidStr) {
try {
return workflowManager.loadWorkflow(uuidStr);
} catch (UicdActionException e) {
UicdCoreDelegator.getInstance().logException(e);
}
return FAILED;
}
@CrossOrigin(origins = "*")
@RequestMapping("/initDevicesFromListV2")
public Callable<DevicesStatusResponse> initDevicesFromListV2(
@RequestParam(value = "devicesIdList") List<String> devicesIdList,
@RequestParam(value = "isCleanInit", defaultValue = "false") boolean isCleanInit) {
return () -> {
initDevicesInternal(devicesIdList, isCleanInit);
return DevicesStatusResponse.create(devicesDriverManager.getDevicesStatusDetails());
};
}
@CrossOrigin(origins = { "https://site1.com", "https://site2.com" },
allowedHeaders = { "header1", "header2" },
exposedHeaders = { "header3", "header4" },
methods = RequestMethod.DELETE,
maxAge = 123,
allowCredentials = "false")
@RequestMapping(path = "/customized", method = { RequestMethod.GET, RequestMethod.POST })
public void customized() {
}
@CrossOrigin(origins = "*")
@RequestMapping("/pressKey")
public Callable<String> pressKey(@RequestParam(value = "keyCode") int keyCode) {
return () -> {
workflowManager.recordAndInput(keyCode);
return DONE;
};
}
@CrossOrigin(origins = "*")
@RequestMapping("/turnOnOffScreen")
public Callable<String> turnOnOffScreen() {
return () -> {
workflowManager.recordAndInput(26);
return DONE;
};
}
@CrossOrigin(origins = "*")
@RequestMapping("/copyAction")
public String copyAction(@RequestParam(value = "uuidStr") String uuidStr) {
try {
return workflowManager.copyAction(uuidStr);
} catch (UicdActionException | CloneNotSupportedException e) {
UicdCoreDelegator.getInstance().logException(e);
}
return FAILED;
}
@CrossOrigin(origins = "*")
@RequestMapping(value = "/updateActionMetadata", method = RequestMethod.POST)
public Callable<String> updateActionMetadata(@RequestBody String actionMetadataJson) {
return () -> {
workflowManager.updateActionMetadata(actionMetadataJson);
return DONE;
};
}
@GetMapping("/getUser/{uid}")
@CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<UserResource> getUserById(@PathVariable("uid") Long uid) {
UserResource ur = new UserResource();
BeanUtils.copyProperties(service.getUser(uid), ur);
return new ResponseEntity<UserResource>(ur, HttpStatus.OK);
}
如果文章对你有帮助,欢迎点击上方按钮打赏作者