org.springframework.web.bind.annotation.RestController#org.springframework.core.io.Resource源码实例Demo

下面列出了org.springframework.web.bind.annotation.RestController#org.springframework.core.io.Resource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Bean(name = "graviteeProperties")
public static Properties graviteeProperties() throws IOException {
    LOGGER.info("Loading Gravitee Management configuration.");

    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();

    String yamlConfiguration = System.getProperty(GRAVITEE_CONFIGURATION);
    Resource yamlResource = new FileSystemResource(yamlConfiguration);

    LOGGER.info("\tGravitee Management configuration loaded from {}", yamlResource.getURL().getPath());

    yaml.setResources(yamlResource);
    Properties properties = yaml.getObject();
    LOGGER.info("Loading Gravitee Management configuration. DONE");

    return properties;
}
 
@Override
protected void deployResourcesInternal(String deploymentNameHint, Resource[] resources, ProcessEngine engine) {
    // Create a separate deployment for each resource using the resource name
    RepositoryService repositoryService = engine.getRepositoryService();

    for (final Resource resource : resources) {

        final String resourceName = determineResourceName(resource);
        final DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(resourceName);
        addResource(resource, resourceName, deploymentBuilder);
        try {
            deploymentBuilder.deploy();
        } catch (RuntimeException e) {
            if (isThrowExceptionOnDeploymentFailure()) {
                throw e;
            } else {
                LOGGER.warn(
                    "Exception while autodeploying process definitions for resource {}. This exception can be ignored if the root cause indicates a unique constraint violation, which is typically caused by two (or more) servers booting up at the exact same time and deploying the same definitions. ",
                    resource, e);
            }
        }
    }
}
 
源代码3 项目: scava   文件: CROSSRecSimilarityCalculatorTest.java
@Before
public void init(){
	artifactRepository.deleteAll();
	githubUserRepository.deleteAll();
	crossRecGraphRepository.deleteAll();
	try {
		ObjectMapper mapper = new ObjectMapper();
		Resource resource = new ClassPathResource("artifacts.json");
		InputStream resourceInputStream = resource.getInputStream();
		artifacts = mapper.readValue(resourceInputStream, new TypeReference<List<Artifact>>(){});
		artifactRepository.save(artifacts);
		for (Artifact artifact : artifacts) {
			ossmeterImporter.storeGithubUser(artifact.getStarred(), artifact.getFullName());
			ossmeterImporter.storeGithubUserCommitter(artifact.getCommitteers(), artifact.getFullName());
		}
		resourceInputStream.close();
	} catch (IOException e) {
		logger.error(e.getMessage());
	}
}
 
@Override
protected String getFileResourceName(Resource resource) {
  // only path relative to the root deployment directory as identifier to
  // prevent re-deployments when the path changes (e.g. distro is moved)
  try {
    String deploymentDir = env.getProperty(CamundaBpmRunDeploymentConfiguration.CAMUNDA_DEPLOYMENT_DIR_PROPERTY);
    if(File.separator.equals("\\")) {
      deploymentDir = deploymentDir.replace("\\", "/");
    }
    String resourceAbsolutePath = resource.getURI().toString();
    int startIndex = resourceAbsolutePath.indexOf(deploymentDir) + deploymentDir.length();
    return resourceAbsolutePath.substring(startIndex);
  } catch (IOException e) {
    throw new ProcessEngineException("Failed to locate resource " + resource.getFilename(), e);
  }
}
 
源代码5 项目: secure-data-service   文件: MockZisTest.java
@Test
public void shouldRegisterAgents() throws IOException {
    Resource xmlFile = new ClassPathResource("TestRegisterMessage.xml");

    StringWriter writer = new StringWriter();
    IOUtils.copy(xmlFile.getInputStream(), writer, "UTF-8");
    String sifString = writer.toString();

    mockZis.parseSIFMessage(sifString);

    //check that the correct URL has been added to the
    Set<String> agentUrls = mockZis.getAgentUrls();

    Assert.assertEquals("Should register one agent", 1, agentUrls.size());
    Assert.assertEquals("Registered agent URL incorrect",
            "http://10.81.1.35:25101/zone/TestZone/", agentUrls.iterator().next());
}
 
源代码6 项目: mybatis.flying   文件: SqlSessionFactory2Config.java
@Bean(name = "sqlSessionFactory2")
@Primary
public SqlSessionFactoryBean createSqlSessionFactory2Bean() throws IOException {
	SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
	/** 设置datasource */
	sqlSessionFactoryBean.setDataSource(dataSource2);
	VFS.addImplClass(SpringBootVFS.class);
	/** 设置mybatis configuration 扫描路径 */
	sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("Configuration.xml"));
	/** 设置typeAlias 包扫描路径 */
	sqlSessionFactoryBean.setTypeAliasesPackage("indi.mybatis.flying");
	/** 添加mapper 扫描路径 */
	PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
	Resource[] ra1 = resolver.getResources("classpath*:indi/mybatis/flying/mapper*/*.xml");
	sqlSessionFactoryBean.setMapperLocations(ra1); // 扫描映射文件
	return sqlSessionFactoryBean;
}
 
@Bean
@ConditionalOnMissingBean(JwtAccessTokenConverter.class)
public JwtAccessTokenConverter accessTokenConverter() {
	Assert.notNull(this.resource.getJwt().getKeyStore(), "keyStore cannot be null");
	Assert.notNull(this.resource.getJwt().getKeyStorePassword(), "keyStorePassword cannot be null");
	Assert.notNull(this.resource.getJwt().getKeyAlias(), "keyAlias cannot be null");

	JwtAccessTokenConverter converter = new JwtAccessTokenConverter();

	Resource keyStore = this.context.getResource(this.resource.getJwt().getKeyStore());
	char[] keyStorePassword = this.resource.getJwt().getKeyStorePassword().toCharArray();
	KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(keyStore, keyStorePassword);

	String keyAlias = this.resource.getJwt().getKeyAlias();
	char[] keyPassword = Optional.ofNullable(this.resource.getJwt().getKeyPassword()).map(String::toCharArray)
			.orElse(keyStorePassword);
	converter.setKeyPair(keyStoreKeyFactory.getKeyPair(keyAlias, keyPassword));

	return converter;
}
 
源代码8 项目: istio-fleetman   文件: JourneySimulator.java
/**
 * Read the data from the resources directory - should work for an executable Jar as
 * well as through direct execution
 */
@PostConstruct
private void setUpData() 
{
	PathMatchingResourcePatternResolver path = new PathMatchingResourcePatternResolver();
	try
	{
		for (Resource nextFile : path.getResources("tracks/*"))
		{
			URL resource = nextFile.getURL();
			File f = new File(resource.getFile()); 
			String vehicleName = VehicleNameUtils.prettifyName(f.getName());				
			vehicleNames.add(vehicleName);
			populateReportQueueForVehicle(vehicleName);
		}
	}
	catch (IOException e)
	{
		throw new RuntimeException(e);
	}
	positionTracker.clearHistories();
}
 
/**
 * Check that user defined error codes take precedence.
 */
@Test
public void testFindUserDefinedCodes() {
	class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
		@Override
		protected Resource loadResource(String path) {
			if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) {
				return new ClassPathResource("test-error-codes.xml", SQLErrorCodesFactoryTests.class);
			}
			return null;
		}
	}

	// Should have loaded without error
	TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory();
	assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0);
	assertEquals(2, sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length);
	assertEquals("1", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[0]);
	assertEquals("2", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[1]);
}
 
@Test
public void testDeployResources() {
  final Resource[] resources = new Resource[] { resourceMock1, resourceMock2, resourceMock3, resourceMock4, resourceMock5 };
  classUnderTest.deployResources(deploymentNameHint, resources, repositoryServiceMock);

  verify(repositoryServiceMock, times(5)).createDeployment();
  verify(deploymentBuilderMock, times(5)).enableDuplicateFiltering();
  verify(deploymentBuilderMock, times(1)).name(resourceName1);
  verify(deploymentBuilderMock, times(1)).name(resourceName2);
  verify(deploymentBuilderMock, times(1)).name(resourceName3);
  verify(deploymentBuilderMock, times(1)).name(resourceName4);
  verify(deploymentBuilderMock, times(1)).name(resourceName5);
  verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName1), isA(InputStream.class));
  verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName2), isA(InputStream.class));
  verify(deploymentBuilderMock, times(3)).addZipInputStream(isA(ZipInputStream.class));
  verify(deploymentBuilderMock, times(5)).deploy();
}
 
源代码11 项目: java-technology-stack   文件: MockServletContext.java
@Override
@Nullable
public InputStream getResourceAsStream(String path) {
	Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
	if (!resource.exists()) {
		return null;
	}
	try {
		return resource.getInputStream();
	}
	catch (IOException ex) {
		if (logger.isWarnEnabled()) {
			logger.warn("Could not open InputStream for " + resource, ex);
		}
		return null;
	}
}
 
源代码12 项目: cuba   文件: WebJarResourceResolver.java
protected void scanResources(ApplicationContext applicationContext) throws IOException {
    // retrieve all resources from all JARs
    Resource[] resources = applicationContext.getResources("classpath*:META-INF/resources/webjars/**");

    for (Resource resource : resources) {
        URL url = resource.getURL();
        String urlString = url.toString();
        int classPathStartIndex = urlString.indexOf(CLASSPATH_WEBJAR_PREFIX);
        if (classPathStartIndex > 0) {
            String resourcePath = urlString.substring(classPathStartIndex + CLASSPATH_WEBJAR_PREFIX.length());
            if (!Strings.isNullOrEmpty(resourcePath)
                    && !resourcePath.endsWith("/")) {
                mapping.put(resourcePath, new UrlHolder(url));
            }
        } else {
            log.debug("Ignored WebJAR resource {} since it does not contain class path prefix {}",
                    urlString, CLASSPATH_WEBJAR_PREFIX);
        }
    }

    this.fullPathIndex = getFullPathIndex(mapping.keySet());
}
 
@Bean
JsonCacheDataImporterExporter exampleRegionDataImporter() {

	return new JsonCacheDataImporterExporter() {

		@Override @SuppressWarnings("rawtypes")
		protected Optional<Resource> getResource(@NonNull Region region, String resourcePrefix) {
			return Optional.ofNullable(resourceSupplier.get());
		}

		@NonNull @Override
		Writer newWriter(@NonNull Resource resource) {
			return writerSupplier.get();
		}
	};
}
 
源代码14 项目: sdn-rx   文件: PopulatorConfig.java
@Bean
public FactoryBean<ResourceReaderRepositoryPopulator> respositoryPopulator(
	ObjectMapper objectMapper, // <1>
	ResourceLoader resourceLoader) {

	Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
	factory.setMapper(objectMapper);
	factory.setResources(new Resource[] { resourceLoader.getResource("classpath:data.json") }); // <2>
	return factory;
}
 
源代码15 项目: spring-content   文件: StoreRestController.java
protected void handleUpdate(HttpHeaders headers, String store, String path, InputStream content)
		throws IOException {

	ContentStoreInfo info = ContentStoreUtils.findStore(storeService, store);
	if (info == null) {
		throw new IllegalArgumentException("Not a Store");
	}

	String pathToUse = path.substring(store.length() + 1);
	Resource r = ((Store) info.getImpementation()).getResource(pathToUse);
	if (r == null) {
		throw new ResourceNotFoundException();
	}
	if (r instanceof WritableResource == false) {
		throw new UnsupportedOperationException();
	}

	if (r.exists()) {
		HeaderUtils.evaluateHeaderConditions(headers, null, new Date(r.lastModified()));
	}

	InputStream in = content;
	OutputStream out = ((WritableResource) r).getOutputStream();
	IOUtils.copy(in, out);
	IOUtils.closeQuietly(out);
	IOUtils.closeQuietly(in);
}
 
源代码16 项目: yes-cart   文件: LanguageServiceImpl.java
/**
 * Construct language service.
 * @param config  property file with i18n configurations
 * @param shopService shop service
 */
public LanguageServiceImpl(final Resource config,
                           final ShopService shopService) throws IOException {

    final Properties properties = new Properties();
    properties.load(config.getInputStream());

    this.shopService = shopService;
    this.languageName = new TreeMap<>((o1, o2) -> o1.compareTo(o2));
    this.languageName.putAll(getLanguageNameFromConfig(properties));
    this.shopToLanguageMap = getShopToLanguageMapFromConfig(properties);
    this.supportedLanguages = this.shopToLanguageMap.get("DEFAULT");
}
 
@Override
protected void testDecodeError(Publisher<DataBuffer> input, ResolvableType outputType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	input = Flux.concat(
			Flux.from(input).take(1),
			Flux.error(new InputException()));

	Flux<Resource> result = this.decoder.decode(input, outputType, mimeType, hints);

	StepVerifier.create(result)
			.expectError(InputException.class)
			.verify();
}
 
源代码18 项目: zfile   文件: Sys.java
public Sys() {
    this.osName = System.getProperty("os.name");
    this.osArch = System.getProperty("os.arch");
    this.osVersion = System.getProperty("os.version");
    Resource resource = new ClassPathResource("");
    try {
        this.projectDir = resource.getFile().getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
    }

    long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
    this.upTime = DateUtil.formatBetween(uptime, BetweenFormater.Level.SECOND);
}
 
@Override
protected IDataSet createDataSet(Resource resource) throws Exception {
    FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
    builder.setColumnSensing(true);
    InputStream inputStream = resource.getInputStream();
    try {
        return builder.build(inputStream);
    } finally {
        inputStream.close();
    }
}
 
@Test
public void testGraduationPlan() throws Throwable {
    Resource schema = new ClassPathResource("edfiXsd-SLI/SLI-Interchange-StudentEnrollment.xsd");
    Resource inputXml = new ClassPathResource("parser/InterchangeStudentEnrollment/GraduationPlan.xml");
    Resource expectedJson = new ClassPathResource("parser/InterchangeStudentEnrollment/GraduationPlan.json");

    EntityTestHelper.parseAndVerify(schema, inputXml, expectedJson);
}
 
@Test
public void testDeployResources() {
    final Resource[] resources = new Resource[] { resourceMock1, resourceMock2, resourceMock3 };
    classUnderTest.deployResources(deploymentNameHint, resources, formEngineMock);

    verify(repositoryServiceMock, times(3)).createDeployment();
    verify(deploymentBuilderMock, times(3)).enableDuplicateFiltering();
    verify(deploymentBuilderMock, times(1)).name(resourceName1);
    verify(deploymentBuilderMock, times(1)).name(resourceName2);
    verify(deploymentBuilderMock, times(1)).name(resourceName3);
    verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName1), isA(InputStream.class));
    verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName2), isA(InputStream.class));
    verify(deploymentBuilderMock, times(3)).deploy();
}
 
源代码22 项目: onetwo   文件: SpringUtils.java
public static PropertiesFactoryBean createPropertiesBySptring(JFishProperties properties, String...classpaths) {
//		PropertiesFactoryBean pfb = new PropertiesFactoryBean();
		PropertiesFactoryBean pfb = new JFishPropertiesFactoryBean(properties);
		pfb.setIgnoreResourceNotFound(true);
		org.springframework.core.io.Resource[] resources = new org.springframework.core.io.Resource[classpaths.length];
		int index = 0;
		for(String classpath : classpaths){
			resources[index++] = classpath(classpath);
		}
		pfb.setLocations(resources);
		return pfb;
	}
 
源代码23 项目: XS2A-Sandbox   文件: TppAccountsControllerTest.java
@Test
void downloadAccountTemplate() {
    // Given
    when(downloadResourceService.getResourceByTemplate(any())).thenReturn(null);

    // When
    ResponseEntity<Resource> response = accountsController.downloadAccountTemplate();

    // Then
    assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
}
 
源代码24 项目: attic-rave   文件: ConfigurablePropertiesModule.java
/**
 * Returns a Resource that contains property key-value pairs.
 * If no system property is set for the resource location, the default location is used
 *
 * @return the {@link Resource} with the
 */
private Resource getPropertyResource() {
    final String overrideProperty = System.getProperty(SHINDIG_OVERRIDE_PROPERTIES);
    if (StringUtils.isBlank(overrideProperty)) {
        return new ClassPathResource(DEFAULT_PROPERTIES);
    } else if (overrideProperty.startsWith(CLASSPATH)) {
        return new ClassPathResource(overrideProperty.trim().substring(CLASSPATH.length()));
    } else {
        return new FileSystemResource(overrideProperty.trim());
    }
}
 
源代码25 项目: spring4-understanding   文件: EncodedResource.java
private EncodedResource(Resource resource, String encoding, Charset charset) {
	super();
	Assert.notNull(resource, "Resource must not be null");
	this.resource = resource;
	this.encoding = encoding;
	this.charset = charset;
}
 
@Test
public void resolveFromClasspath() throws IOException {
	Resource location = new ClassPathResource("test/", PathResourceResolver.class);
	String path = "bar.css";
	List<Resource> locations = singletonList(location);
	Resource actual = this.resolver.resolveResource(null, path, locations, null).block(TIMEOUT);

	assertEquals(location.createRelative(path), actual);
}
 
源代码27 项目: spring4-understanding   文件: ResourceTests.java
private void doTestResource(Resource resource) throws IOException {
	assertEquals("Resource.class", resource.getFilename());
	assertTrue(resource.getURL().getFile().endsWith("Resource.class"));

	Resource relative1 = resource.createRelative("ClassPathResource.class");
	assertEquals("ClassPathResource.class", relative1.getFilename());
	assertTrue(relative1.getURL().getFile().endsWith("ClassPathResource.class"));
	assertTrue(relative1.exists());

	Resource relative2 = resource.createRelative("support/ResourcePatternResolver.class");
	assertEquals("ResourcePatternResolver.class", relative2.getFilename());
	assertTrue(relative2.getURL().getFile().endsWith("ResourcePatternResolver.class"));
	assertTrue(relative2.exists());
}
 
源代码28 项目: spring-cloud-skipper   文件: ManifestUtilsTest.java
@Test
public void testCreateManifest() throws IOException {
	Resource resource = new ClassPathResource("/repositories/sources/test/ticktock/ticktock-1.0.1");
	PackageReader packageReader = new DefaultPackageReader();

	Package pkg = packageReader.read(resource.getFile());
	assertThat(pkg).isNotNull();

	Date date = new Date(666);
	Map<String, Object> log = new HashMap<>();
	log.put("version", "666");
	log.put("adate", new Date(666));
	log.put("bool", true);
	log.put("array", "[a, b, c]");

	Map<String, String> time = new HashMap<>();
	time.put("version", "666");

	Map<String, Object> map = new HashMap<>();
	map.put("log", log);
	map.put("time", time);

	String manifest = ManifestUtils.createManifest(pkg, map);

	String dateAsStringWithQuotes = "\"" + date.toString() + "\"";

	assertThat(manifest).contains("\"version\": \"666\"").describedAs("Handle Integer");
	assertThat(manifest).contains("\"bool\": \"true\"").describedAs("Handle Boolean");
	assertThat(manifest).contains("\"adate\": " + dateAsStringWithQuotes).describedAs("Handle Date");
	assertThat(manifest).contains("\"array\":\n  - \"a\"\n  - \"b\"\n  - \"c\"").describedAs("Handle Array");
	assertThat(manifest).contains("\"deploymentProperties\": !!null \"null\"").describedAs("Handle Null");
}
 
@Test
public void readByteArrayResourcePositionAndTakeUntil() throws Exception {
	Resource resource = new ByteArrayResource("foobarbazqux" .getBytes());
	Flux<DataBuffer> flux = DataBufferUtils.read(resource, 3, this.bufferFactory, 3);

	flux = DataBufferUtils.takeUntilByteCount(flux, 5);


	StepVerifier.create(flux)
			.consumeNextWith(stringConsumer("bar"))
			.consumeNextWith(stringConsumer("ba"))
			.expectComplete()
			.verify(Duration.ofSeconds(5));
}
 
源代码30 项目: spring-analysis-note   文件: ResourceTests.java
@Test
public void testServletContextResourceWithRelativePath() throws IOException {
	MockServletContext sc = new MockServletContext();
	Resource resource = new ServletContextResource(sc, "dir/");
	Resource relative = resource.createRelative("subdir");
	assertEquals(new ServletContextResource(sc, "dir/subdir"), relative);
}