当前位置: 首页>>代码示例>>Java>>正文


Java ClassPathResource类代码示例

本文整理汇总了Java中org.springframework.core.io.ClassPathResource的典型用法代码示例。如果您正苦于以下问题:Java ClassPathResource类的具体用法?Java ClassPathResource怎么用?Java ClassPathResource使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ClassPathResource类属于org.springframework.core.io包,在下文中一共展示了ClassPathResource类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createGoogleAppsPrivateKey

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
/**
 * Create the private key.
 *
 * @throws Exception if key creation ran into an error
 */
protected void createGoogleAppsPrivateKey() throws Exception {
    if (!isValidConfiguration()) {
        LOGGER.debug("Google Apps private key bean will not be created, because it's not configured");
        return;
    }

    final PrivateKeyFactoryBean bean = new PrivateKeyFactoryBean();

    if (this.privateKeyLocation.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
        bean.setLocation(new ClassPathResource(StringUtils.removeStart(this.privateKeyLocation, ResourceUtils.CLASSPATH_URL_PREFIX)));
    } else if (this.privateKeyLocation.startsWith(ResourceUtils.FILE_URL_PREFIX)) {
        bean.setLocation(new FileSystemResource(StringUtils.removeStart(this.privateKeyLocation, ResourceUtils.FILE_URL_PREFIX)));
    } else {
        bean.setLocation(new FileSystemResource(this.privateKeyLocation));
    }

    bean.setAlgorithm(this.keyAlgorithm);
    LOGGER.debug("Loading Google Apps private key from [{}] with key algorithm [{}]",
            bean.getLocation(), bean.getAlgorithm());
    bean.afterPropertiesSet();
    LOGGER.debug("Creating Google Apps private key instance via [{}]", this.privateKeyLocation);
    this.privateKey = bean.getObject();
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:29,代码来源:GoogleAccountsServiceResponseBuilder.java

示例2: testProjectTrivialDiffProjectFiles

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
/**
 * Open and close of a project file changes certain header properties.
 * Test File 1 has been opened and closed.
 * @throws Exception
 */
public void testProjectTrivialDiffProjectFiles() throws Exception
{
    CIFSContentComparator contentComparator = new CIFSContentComparator();
    contentComparator.init();
    
    ClassPathResource file0Resource = new ClassPathResource("filesys/ContentComparatorTest0.mpp");
    assertNotNull("unable to find test resource filesys/ContentComparatorTest0.mpp", file0Resource);
    
    ClassPathResource file1Resource = new ClassPathResource("filesys/ContentComparatorTest1.mpp");
    assertNotNull("unable to find test resource filesys/ContentComparatorTest1.mpp", file1Resource);
            
    /**
     * Compare trivially different project files, should ignore trivial differences and be equal 
     */
    {
        File file0 = file0Resource.getFile();
        File file1 = file1Resource.getFile();

        ContentReader reader = new FileContentReader(file0);
        reader.setMimetype("application/vnd.ms-project");
        reader.setEncoding("UTF-8");
        boolean result = contentComparator.isContentEqual(reader, file1);
        assertTrue("compare trivially different project file, should be equal", result);
    }
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:31,代码来源:CIFSContentComparatorTest.java

示例3: testInvalidVersions

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
@Test
public void testInvalidVersions() throws IOException {
	UploadRequest uploadRequest = new UploadRequest();
	uploadRequest.setRepoName("local");
	uploadRequest.setName("log");
	uploadRequest.setVersion("abc");
	uploadRequest.setExtension("zip");
	Resource resource = new ClassPathResource("/org/springframework/cloud/skipper/server/service/log-9.9.9.zip");
	assertThat(resource.exists()).isTrue();
	byte[] originalPackageBytes = StreamUtils.copyToByteArray(resource.getInputStream());
	assertThat(originalPackageBytes).isNotEmpty();
	Assert.isTrue(originalPackageBytes.length != 0,
			"PackageServiceTests.Assert.isTrue: Package file as bytes must not be empty");
	assertInvalidPackageVersion(uploadRequest);
	uploadRequest.setVersion("1abc");
	assertInvalidPackageVersion(uploadRequest);
	uploadRequest.setVersion("1.abc.2");
	assertInvalidPackageVersion(uploadRequest);
	uploadRequest.setVersion("a.b.c");
	assertInvalidPackageVersion(uploadRequest);
	uploadRequest.setVersion("a.b.c.2");
	assertInvalidPackageVersion(uploadRequest);
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-skipper,代码行数:24,代码来源:PackageServiceTests.java

示例4: testHelloWorld

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
public void testHelloWorld() {
    final AScriptTaskMatlab<String> script = new AScriptTaskMatlab<String>() {

        @Override
        public void populateInputs(final IScriptTaskInputs inputs) {
            inputs.putString("hello", "World");
        }

        @Override
        public void executeScript(final IScriptTaskEngine engine) {
            //execute this script inline:
            //                engine.eval("world = strcat({'Hello '}, hello, '!')");
            //or run it from a file:
            engine.eval(new ClassPathResource(HelloWorldScript.class.getSimpleName() + ".m", getClass()));
        }

        @Override
        public String extractResults(final IScriptTaskResults results) {
            return results.getString("world");
        }
    };
    final String result = script.run(runner);
    Assertions.assertThat(result).isEqualTo("Hello World!");
}
 
开发者ID:subes,项目名称:invesdwin-context-matlab,代码行数:25,代码来源:HelloWorldScript.java

示例5: testUploadInvalidWorkflowType

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
@Test
public void testUploadInvalidWorkflowType() throws Exception {
	thrown.expect(ValidationJsonException.class);
	thrown.expect(MatcherUtil.validationMatcher("type",
			"Specified type 'Bug' exists but is not mapped to a workflow and there is no default association"));

	final JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
	try {
		// Delete the default workflow mapping, where type = '0'
		jdbcTemplate.update("update workflowschemeentity SET SCHEME=? WHERE ID = ?", 1, 10272);
		resource.upload(new ClassPathResource("csv/upload/nominal-simple.csv").getInputStream(), ENCODING, subscription,
				UploadMode.PREVIEW);
	} finally {
		jdbcTemplate.update("update workflowschemeentity SET SCHEME=? WHERE ID = ?", 10025, 10272);
	}
}
 
开发者ID:ligoj,项目名称:plugin-bt-jira,代码行数:17,代码来源:JiraImportPluginResourceTest.java

示例6: testUploadSimpleSyntax

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
@Test
public void testUploadSimpleSyntax() throws Exception {
	resource.upload(new ClassPathResource("csv/upload/nominal-simple.csv").getInputStream(), ENCODING, subscription, UploadMode.SYNTAX);
	em.flush();
	em.clear();
	final ImportStatus result = jiraResource.getTask(subscription);
	Assert.assertEquals(1, result.getChanges().intValue());
	Assert.assertNull(result.getComponents());
	Assert.assertNull(result.getCustomFields());
	Assert.assertEquals(1, result.getIssues().intValue());
	Assert.assertEquals(10074, result.getJira().intValue());
	Assert.assertNull(result.getMaxIssue());
	Assert.assertNull(result.getMinIssue());
	Assert.assertNull(result.getPriorities());
	Assert.assertNull(result.getResolutions());
	Assert.assertNull(result.getStatuses());
	Assert.assertNull(result.getTypes());
	Assert.assertNull(result.getUsers());
	Assert.assertNull(result.getVersions());
	Assert.assertEquals(getDate(2014, 03, 01, 12, 01, 00), result.getIssueFrom());
	Assert.assertEquals(UploadMode.SYNTAX, result.getMode());
	Assert.assertEquals("MDA", result.getPkey());
	Assert.assertEquals(getDate(2014, 03, 01, 12, 01, 00), result.getIssueTo());
	Assert.assertNull(result.getLabels());

	Assert.assertNull(result.getNewIssues());
	Assert.assertNull(result.getNewComponents());
	Assert.assertNull(result.getNewVersions());
}
 
开发者ID:ligoj,项目名称:plugin-bt-jira,代码行数:30,代码来源:JiraImportPluginResourceTest.java

示例7: uploadFileAndCreateAsset

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
private AssetInfo uploadFileAndCreateAsset(String fileName)
        throws ServiceException, IOException {
    final WritableBlobContainerContract uploader;
    final AssetInfo resultAsset;
    final AccessPolicyInfo uploadAccessPolicy;
    LocatorInfo uploadLocator = null;

    // Create an Asset
    resultAsset = mediaService
            .create(Asset.create().setName(fileName).setAlternateId("altId"));
    System.out.println("Created Asset " + fileName);

    // Create an AccessPolicy that provides Write access for 15 minutes
    uploadAccessPolicy = mediaService.create(AccessPolicy.create("uploadAccessPolicy",
            15.0, EnumSet.of(AccessPolicyPermission.WRITE)));

    // Create a Locator using the AccessPolicy and Asset
    uploadLocator = mediaService.create(Locator.create(uploadAccessPolicy.getId(),
            resultAsset.getId(), LocatorType.SAS));

    // Create the Blob Writer using the Locator
    uploader = mediaService.createBlobWriter(uploadLocator);

    // The local file that will be uploaded to your Media Services account
    try (final InputStream input = new ClassPathResource(fileName).getInputStream()) {
        System.out.println("Uploading " + fileName);

        // Upload the local file to the asset
        uploader.createBlockBlob(fileName, input);
    }
    // Inform Media Services about the uploaded files
    mediaService.action(AssetFile.createFileInfos(resultAsset.getId()));
    System.out.println("Uploaded Asset File " + fileName);

    mediaService.delete(Locator.delete(uploadLocator.getId()));
    mediaService.delete(AccessPolicy.delete(uploadAccessPolicy.getId()));

    return resultAsset;
}
 
开发者ID:Microsoft,项目名称:azure-spring-boot,代码行数:40,代码来源:MediaServicesSampleApplication.java

示例8: setup

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    JwtAccessTokenConverter converter = new DomainJwtAccessTokenConverter();
    KeyPair keyPair = new KeyStoreKeyFactory(
        new ClassPathResource(KEYSTORE_PATH), KEYSTORE_PSWRD.toCharArray())
        .getKeyPair(KEYSTORE_ALIAS);
    converter.setKeyPair(keyPair);
    converter.afterPropertiesSet();
    tokenStore = new JwtTokenStore(converter);
    tokenServices = new DomainTokenServices();
    tokenServices.setTokenStore(tokenStore);
    tokenServices.setTokenEnhancer(converter);
    tokenServices.setTenantPropertiesService(tenantPropertiesService);
    when(tenantPropertiesService.getTenantProps()).thenReturn(tenantProperties);
    when(tenantProperties.getSecurity()).thenReturn(security);
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:18,代码来源:DomainTokenServicesUnitTest.java

示例9: getPackageTemplate

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
public File getPackageTemplate () {

		// Loading resources has some corner cases, using spring to manage toURI
		// location
		File result = null;
		ClassPathResource cp = new ClassPathResource( "/releasePackageTemplate.json" );
		try {
			result = cp.getFile();
		} catch (IOException e) {
			logger.error( "Failed to find template", e );
		}

		return result;
	}
 
开发者ID:csap-platform,项目名称:csap-core,代码行数:15,代码来源:DefinitionParser.java

示例10: validateSpaceActivityNoImage

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
@Test
public void validateSpaceActivityNoImage() throws Exception {
	prepareMockSpace();

	// Activity
	httpServer.stubFor(get(urlEqualTo("/plugins/recently-updated/changes.action?theme=social&pageSize=1&spaceKeys=SPACE"))
			.willReturn(aResponse().withStatus(HttpStatus.SC_OK)
					.withBody(IOUtils.toString(
							new ClassPathResource("mock-server/confluence/confluence-space-SPACE-changes.html").getInputStream(),
							StandardCharsets.UTF_8))));

	// Avatar not found
	httpServer.stubFor(get(urlEqualTo("/some/default.png")).willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
	httpServer.start();

	final Map<String, String> parameters = pvResource.getNodeParameters("service:km:confluence:dig");
	parameters.put(ConfluencePluginResource.PARAMETER_SPACE, "SPACE");
	final Space space = resource.validateSpace(parameters);
	checkSpaceActivity(space);
	Assert.assertNull(space.getActivity().getAuthorAvatar());
}
 
开发者ID:ligoj,项目名称:plugin-km-confluence,代码行数:22,代码来源:ConfluencePluginResourceTest.java

示例11: testHelloWorld

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
public void testHelloWorld() {
    final AScriptTaskMatlab<String> script = new AScriptTaskMatlab<String>() {

        @Override
        public void populateInputs(final IScriptTaskInputs inputs) {
            inputs.putString("hello", "World");
        }

        @Override
        public void executeScript(final IScriptTaskEngine engine) {
            //execute this script inline:
            //                engine.eval("world = strcat('Hello ', hello, '!')");
            //or run it from a file:
            engine.eval(new ClassPathResource(HelloWorldScript.class.getSimpleName() + ".sce", getClass()));
        }

        @Override
        public String extractResults(final IScriptTaskResults results) {
            return results.getString("world");
        }
    };
    final String result = script.run(runner);
    Assertions.assertThat(result).isEqualTo("Hello World!");
}
 
开发者ID:subes,项目名称:invesdwin-context-matlab,代码行数:25,代码来源:HelloWorldScript.java

示例12: testVcapSingleServiceWithNulls

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
@Test
@SuppressFBWarnings("DM_DEFAULT_ENCODING")
public void testVcapSingleServiceWithNulls() {
    final Resource resource = new ClassPathResource("/vcap2.json");
    final String content;
    try {
        content = new String(
                Files.readAllBytes(Paths.get(resource.getURI())));
        final VcapResult result = parser.parse(content);
        final VcapPojo[] pojos = result.getPojos();
        assertNotNull(pojos);
        assertEquals(1, pojos.length);
        final VcapPojo pojo = pojos[0];

        LOG.debug("pojo = " + pojo);
        assertEquals(4, pojo.getCredentials().size());
        assertEquals(0, pojo.getTags().length);
        assertEquals(0, pojo.getVolumeMounts().length);
        assertEquals("azure-documentdb", pojo.getLabel());
        assertNull(pojo.getProvider());
        assertEquals("azure-documentdb", pojo.getServiceBrokerName());
        assertEquals("mydocumentdb", pojo.getServiceInstanceName());
        assertEquals("standard", pojo.getServicePlan());
        assertNull(pojo.getSyslogDrainUrl());

        assertEquals("docdb123mj",
                pojo.getCredentials().get("documentdb_database_id"));
        assertEquals("dbs/ZFxCAA==/",
                pojo.getCredentials().get("documentdb_database_link"));
        assertEquals("https://hostname:443/",
                pojo.getCredentials().get("documentdb_host_endpoint"));
        assertEquals(
                "3becR7JFnWamMvGwWYWWTV4WpeNhN8tOzJ74yjAxPKDpx65q2lYz60jt8WXU6HrIKrAIwhs0Hglf0123456789==",
                pojo.getCredentials().get("documentdb_master_key"));
    } catch (IOException e) {
        LOG.error("Error reading json file", e);
    }
}
 
开发者ID:Microsoft,项目名称:azure-spring-boot,代码行数:39,代码来源:AzureCloudFoundryServiceApplicationTest.java

示例13: testUploadDefaultWorkflowScheme

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
@Test
public void testUploadDefaultWorkflowScheme() throws Exception {
	final JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
	try {
		// Delete the default project/workflow mapping, where type = '0'
		jdbcTemplate.update(
				"update nodeassociation SET SOURCE_NODE_ID=? WHERE SOURCE_NODE_ID=? AND SOURCE_NODE_ENTITY=? AND SINK_NODE_ID=? AND SINK_NODE_ENTITY=? AND ASSOCIATION_TYPE=?",
				1, 10074, "Project", 10025, "WorkflowScheme", "ProjectScheme");
		resource.upload(new ClassPathResource("csv/upload/nominal-simple.csv").getInputStream(), ENCODING, subscription,
				UploadMode.PREVIEW);
	} finally {
		jdbcTemplate.update(
				"update nodeassociation SET SOURCE_NODE_ID=? WHERE SOURCE_NODE_ID=? AND SOURCE_NODE_ENTITY=? AND SINK_NODE_ID=? AND SINK_NODE_ENTITY=? AND ASSOCIATION_TYPE=?",
				10074, 1, "Project", 10025, "WorkflowScheme", "ProjectScheme");
	}

	final ImportStatus result = jiraResource.getTask(subscription);
	Assert.assertEquals(UploadMode.PREVIEW, result.getMode());
	Assert.assertFalse(result.isFailed());
	Assert.assertEquals(22, result.getStep());
}
 
开发者ID:ligoj,项目名称:plugin-bt-jira,代码行数:22,代码来源:JiraImportPluginResourceTest.java

示例14: setUp

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
protected void setUp() throws Exception {
	bundleContext = new MockBundleContext();

	context = new GenericApplicationContext();
	context.setClassLoader(getClass().getClassLoader());
	context.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
	SpringBlueprintConverterService converterService =
			new SpringBlueprintConverterService(null, context.getBeanFactory());
	converterService.add(new GenericConverter());
	context.getBeanFactory().setConversionService(converterService);

	reader = new XmlBeanDefinitionReader(context);
	reader.setDocumentLoader(new PublicBlueprintDocumentLoader());
	reader.loadBeanDefinitions(new ClassPathResource(CONFIG, getClass()));
	context.refresh();

	blueprintContainer = new SpringBlueprintContainer(context);
}
 
开发者ID:eclipse,项目名称:gemini.blueprint,代码行数:19,代码来源:GenericsTest.java

示例15: validateAdminAccess

import org.springframework.core.io.ClassPathResource; //导入依赖的package包/类
@Test
public void validateAdminAccess() throws Exception {
	httpServer.stubFor(get(urlEqualTo("/sessions/new")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
	httpServer.stubFor(get(urlEqualTo("/api/authentication/validate?format=json"))
			.willReturn(aResponse().withStatus(HttpStatus.SC_OK).withBody("{\"valid\":true}")));
	httpServer.stubFor(get(urlEqualTo("/provisioning"))
			.willReturn(aResponse().withStatus(HttpStatus.SC_OK).withBody("<html></html>")));
	httpServer.stubFor(
			get(urlEqualTo("/api/server/index?format=json")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)
					.withBody(IOUtils.toString(
							new ClassPathResource("mock-server/sonar/sonar-server-index.json").getInputStream(),
							StandardCharsets.UTF_8))));
	httpServer.start();

	final String version = resource
			.validateAdminAccess(pvResource.getNodeParameters("service:qa:sonarqube:bpr"));
	Assert.assertEquals("4.3.2", version);
}
 
开发者ID:ligoj,项目名称:plugin-qa-sonarqube,代码行数:19,代码来源:SonarPluginResourceTest.java


注:本文中的org.springframework.core.io.ClassPathResource类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。