org.springframework.web.bind.annotation.CrossOrigin Java Examples

The following examples show how to use org.springframework.web.bind.annotation.CrossOrigin. 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: TranslationCommitGitController.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
@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;
  
 }
 
Example #2
Source File: RegistryAPI.java    From openvsx with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: RegistryAPI.java    From openvsx with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: VSCodeAdapter.java    From openvsx with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: TaskController.java    From TASK-Management-System with MIT License 6 votes vote down vote up
@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);
}
 
Example #6
Source File: TestCaseController.java    From android-uiconductor with Apache License 2.0 6 votes vote down vote up
@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;
  };
}
 
Example #7
Source File: RequestMappingHandlerMapping.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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();
}
 
Example #8
Source File: SourceController.java    From singleton with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * [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;
}
 
Example #9
Source File: RequestMappingHandlerMapping.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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();
}
 
Example #10
Source File: TestCaseController.java    From android-uiconductor with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: ProgramController.java    From TASK-Management-System with MIT License 5 votes vote down vote up
@GetMapping("/getAllProgramByUser/{uid}")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
@CrossOrigin(origins = clientUrl)
public ResponseEntity<ProgramListResource> getAllProgramByUser(@PathVariable("uid") Long uid) {
  
  ProgramListResource dto = new ProgramListResource();
  dto.setProgramList(userService.getAllProgramByUser(uid));
  return new ResponseEntity<ProgramListResource>(dto, HttpStatus.OK);
}
 
Example #12
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping("/addActionByUUID")
public Callable<String> addActionByUUID(@RequestParam(value = "uuidStr") String uuidStr) {
  return () -> {
    workflowManager.addAction(uuidStr);
    return DONE;
  };
}
 
Example #13
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping(value = "/updateValidationAction", method = RequestMethod.POST)
public Callable<String> updateValidationAction(
    @RequestBody String validationReqDetailsJson,
    @RequestParam(value = "uuidStr") String uuidStr) {
  return () -> {
    ValidationReqDetails validationReqDetails =
        ValidationReqDetails.fromJson(validationReqDetailsJson);
    workflowManager.updateValidationAction(uuidStr, validationReqDetails);
    return DONE;
  };
}
 
Example #14
Source File: TaskController.java    From TASK-Management-System with MIT License 5 votes vote down vote up
@GetMapping("/getAllTaskRecordByUser/{pid}/{uid}")
@CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<TaskRecordListResource> getAllTaskRecordByUser(@PathVariable("pid") Long pid, @PathVariable("uid") Long uid) {
  // service call
  TaskRecordListResource trlr = service.getAllTaskRecordOfUserAndProgram(uid, pid);
  return new ResponseEntity<TaskRecordListResource>(trlr, HttpStatus.OK);
}
 
Example #15
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping("/dragStop")
public Callable<String> dragStop(
    @RequestParam(value = "x") Integer x, @RequestParam(value = "y") Integer y) {
  return () -> {
    workflowManager.dragStop(x, y);
    return DONE;
  };
}
 
Example #16
Source File: UserController.java    From TASK-Management-System with MIT License 5 votes vote down vote up
@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);
}
 
Example #17
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #18
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping(value = "/updateActionMetadata", method = RequestMethod.POST)
public Callable<String> updateActionMetadata(@RequestBody String actionMetadataJson) {
  return () -> {
    workflowManager.updateActionMetadata(actionMetadataJson);
    return DONE;
  };
}
 
Example #19
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping(value = "/addActionToWorkflow", method = RequestMethod.POST)
public Callable<String> addActionToWorkflow(@RequestBody String actionMetadataJson) {
  return () -> {
    workflowManager.addActionToWorkflow(actionMetadataJson);
    return DONE;
  };
}
 
Example #20
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #21
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping(value = "/getScaledScreenDimensions", method = RequestMethod.GET)
public Callable<ScreenDimensionsResponse> getScaledScreenDimensions() {
  return () ->
      ScreenDimensionsResponse.create(
          workflowManager.getScaledScreenWidth(), workflowManager.getScaledScreenHeight());
}
 
Example #22
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping(value = "/playAction", method = RequestMethod.POST)
public Callable<String> playAction(@RequestBody PlayActionRequest playActionRequest) {
  return () ->
      workflowManager.playAction(
          playActionRequest.getActionId(), playActionRequest.getPlaySpeedFactor());
}
 
Example #23
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping(value = "/setPlaySpeedFactor", method = RequestMethod.POST)
public Callable<String> setPlaySpeedFactor(@RequestBody double playSpeedFactor) {
  return () -> {
    workflowManager.setPlaySpeedFactor(playSpeedFactor);
    return DONE;
  };
}
 
Example #24
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping("/turnOnOffScreen")
public Callable<String> turnOnOffScreen() {
  return () -> {
    workflowManager.recordAndInput(26);
    return DONE;
  };
}
 
Example #25
Source File: SophiaResourceServerConfig.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
@Override
@CrossOrigin
public void configure(ResourceServerSecurityConfigurer resources) {
    // String resourceIds = publicMapper.getResourceIdsByClientId(clientId);
    // //设置客户端所能访问的资源id集合(默认取第一个是本服务的资源)
    // resources.resourceId(resourceIds.split(",")[0]).stateless(true);
    // resources.resourceId("admin").stateless(true);
    resources
            .tokenStore(tokenStore())
            //自定义Token异常信息,用于token校验失败返回信息
            .authenticationEntryPoint(new MyAuthExceptionEntryPoint())
            //授权异常处理
            .accessDeniedHandler(new MyAccessDeniedHandler());
}
 
Example #26
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping("/pressKey")
public Callable<String> pressKey(@RequestParam(value = "keyCode") int keyCode) {
  return () -> {
    workflowManager.recordAndInput(keyCode);
    return DONE;
  };
}
 
Example #27
Source File: CrossOriginTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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() {
}
 
Example #28
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping(value = "/playCurrentWorkflowFromAction", method = RequestMethod.POST)
public Callable<String> playCurrentWorkflowFromAction(
    @RequestBody PlayActionRequest playActionRequest) {
  return () ->
      workflowManager.playCurrentWorkflowFromAction(
          playActionRequest.getActionId(), playActionRequest.getPlaySpeedFactor());
}
 
Example #29
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@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());
  };
}
 
Example #30
Source File: MainController.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@CrossOrigin(origins = "*")
@RequestMapping("/selectedDeviceChanged")
public Callable<String> selectedDeviceChanged(@RequestParam(value = "deviceId") String deviceId) {
  return () -> {
    devicesDriverManager.setSelectedDeviceByDeviceId(deviceId);
    return DONE;
  };
}