/** * 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(); }
/** * 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); } }
@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); }
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!"); }
@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); } }
@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()); }
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; }
@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); }
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; }
@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()); }
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!"); }
@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); } }
@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()); }
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); }
@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); }
public ServerConfigReader init(String props) { if (props != null) { serverProperties = props; } try { Resource res = new ClassPathResource(serverProperties); properties.load(res.getInputStream()); } catch (IOException e) { throw new RuntimeException("Failed to load server.properties!"); } /** * 如果本地没有配置走配置中心 */ if (properties.isEmpty()) { //properties = PropertyPlaceholderConfigurer.getPro(); } return this; }
@Before public void setUp() throws Exception { final PublicKeyFactoryBean pubKeyFactoryBean = new PublicKeyFactoryBean(); final PrivateKeyFactoryBean privKeyFactoryBean = new PrivateKeyFactoryBean(); pubKeyFactoryBean.setAlgorithm("DSA"); privKeyFactoryBean.setAlgorithm("DSA"); final ClassPathResource pubKeyResource = new ClassPathResource("DSAPublicKey01.key"); final ClassPathResource privKeyResource = new ClassPathResource("DSAPrivateKey01.key"); pubKeyFactoryBean.setLocation(pubKeyResource); privKeyFactoryBean.setLocation(privKeyResource); assertTrue(privKeyFactoryBean.getObjectType().equals(PrivateKey.class)); assertTrue(pubKeyFactoryBean.getObjectType().equals(PublicKey.class)); pubKeyFactoryBean.afterPropertiesSet(); privKeyFactoryBean.afterPropertiesSet(); final ServicesManager servicesManager = mock(ServicesManager.class); this.extractor = new GoogleAccountsArgumentExtractor((PublicKey) pubKeyFactoryBean.getObject(), (PrivateKey) privKeyFactoryBean.getObject(), servicesManager); }
public GeneralGenderDictionary() { try { ClassPathResource maleResource = new ClassPathResource(MALE_GENDER_FILE_LOCATION); ClassPathResource femaleResource = new ClassPathResource(FEMALE_GENDER_FILE_LOCATION); male = new BufferedReader(new InputStreamReader( maleResource.getInputStream(), StandardCharsets.UTF_8)) .lines().map(name -> name.toLowerCase()).collect(Collectors.toSet()); female = new BufferedReader(new InputStreamReader( femaleResource.getInputStream(), StandardCharsets.UTF_8)) .lines().map(name -> name.toLowerCase()).collect(Collectors.toSet()); } catch (IOException e) { e.printStackTrace(); } setCaseSensitive(false); }
protected void setUp() throws Exception { bundleContext = new MockBundleContext(); context = new GenericApplicationContext(); context.setClassLoader(getClass().getClassLoader()); context.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext)); context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.addPropertyEditorRegistrar(new BlueprintEditorRegistrar()); beanFactory.registerSingleton("blueprintContainer", new SpringBlueprintContainer(context)); } }); reader = new XmlBeanDefinitionReader(context); reader.setDocumentLoader(new PublicBlueprintDocumentLoader()); reader.loadBeanDefinitions(new ClassPathResource(CONFIG, getClass())); context.refresh(); blueprintContainer = new SpringBlueprintContainer(context); }
protected void setUp() throws Exception { BundleContext bundleContext = new MockBundleContext() { // service reference already registered public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException { return new ServiceReference[0]; } }; appContext = new GenericApplicationContext(); appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext)); appContext.setClassLoader(getClass().getClassLoader()); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext); // reader.setEventListener(this.listener); reader.loadBeanDefinitions(new ClassPathResource("osgiReferenceNestedBeans.xml", getClass())); appContext.refresh(); }
private RubriekMap() { final ClassPathResource classPathResource = new ClassPathResource("rubriekmap.csv"); try { try (InputStream is = classPathResource.getInputStream()) { parseStream(is); } } catch (IOException e) { throw new IllegalStateException(e); } }
@Override public String getTextContent() throws Exception{ Resource resource = new ClassPathResource(templateFile); try { byte[] bytes = new byte[1024]; InputStream resourceInputStream = resource.getInputStream(); StringBuilder str = new StringBuilder(); int read = resourceInputStream.read(bytes); while(read != -1){ str.append(new String(bytes)); read = resourceInputStream.read(bytes); } String htmlString = str.toString(); return String.format(htmlString, user.getFirstName(), token); } catch (IOException e) { throw new Exception("UserVerificationEmailTemplate Genarating Error", e); } }
@Override public void initialize(AbstractApplicationContext applicationContext) { PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer(); //load test.properties propertyPlaceholderConfigurer.setLocation(new ClassPathResource("test.properties")); applicationContext.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer); }
@Test public void testYamlMerge() throws IOException { DumperOptions dumperOptions = new DumperOptions(); dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); dumperOptions.setPrettyFlow(true); Yaml yaml = new Yaml(dumperOptions); Resource resource = new ClassPathResource("/org/springframework/cloud/skipper/server/service/ticktock-1.0.0"); Package pkg = this.packageReader.read(resource.getFile()); ConfigValues configValues = new ConfigValues(); Map<String, Object> configValuesMap = new TreeMap<>(); Map<String, Object> logMap = new TreeMap<>(); logMap.put("appVersion", "1.2.1.RELEASE"); configValuesMap.put("log", logMap); configValuesMap.put("hello", "universe"); String configYaml = yaml.dump(configValuesMap); configValues.setRaw(configYaml); Map<String, Object> mergedMap = ConfigValueUtils.mergeConfigValues(pkg, configValues); String mergedYaml = yaml.dump(mergedMap); String expectedYaml = StreamUtils.copyToString( TestResourceUtils.qualifiedResource(getClass(), "merged.yaml").getInputStream(), Charset.defaultCharset()); assertThat(mergedYaml).isEqualTo(expectedYaml); }
/** * Setup quartz scheduler */ @Bean public Scheduler quartzScheduler() { try { StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(new ClassPathResource("quartz.properties").getInputStream()); return factory.getScheduler(); } catch (SchedulerException | IOException e) { throw new IllegalStatusException("Unable to init quartz: " + e.getMessage()); } }
@PostConstruct public void loadSchema() throws IOException{ Resource schemaResource = new ClassPathResource("/demo-schema.graphqls"); TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(new InputStreamReader(schemaResource.getInputStream())); RuntimeWiring runtimeWiring = buildRuntimeWiring(); GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(typeDefinitionRegistry,runtimeWiring); graphQL = GraphQL.newGraphQL(graphQLSchema).build(); }
@Test public void testZUploadWithInsertNoAssociation() throws Exception { startOperationalServer(); this.subscription = getSubscription("gStack"); resource.upload(new ClassPathResource("csv/upload/nominal-complete-no-association.csv").getInputStream(), ENCODING, subscription, UploadMode.FULL); final ImportStatus result = jiraResource.getTask(subscription); Assert.assertEquals(1, result.getChanges().intValue()); Assert.assertEquals(1, result.getIssues().intValue()); Assert.assertEquals(30, result.getStep()); Assert.assertTrue(result.getCanSynchronizeJira()); Assert.assertTrue(result.getScriptRunner()); Assert.assertTrue(result.getSynchronizedJira()); }
/** * Clean data base with 'MDA' JIRA project. */ @AfterClass public static void cleanJiraDataBase2() throws SQLException { final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira-drop.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
public static String getString(String key) { Properties prop = null; try { Resource resource = new ClassPathResource(file_name); EncodedResource encodedResource = new EncodedResource(resource,"UTF-8"); prop = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { logger.error(e.getMessage(), e); } if (prop!=null) { return prop.getProperty(key); } return null; }
/** * Creates a new test instance with given parameters. * * @param checker Revocation checker instance. * @param expiredCRLPolicy Policy instance for handling expired CRL data. * @param certFiles File names of certificates to check. * @param crlFile File name of CRL file to serve out. * @param expected Expected result of check; null to indicate expected success. */ public CRLDistributionPointRevocationCheckerTests( final CRLDistributionPointRevocationChecker checker, final RevocationPolicy<X509CRL> expiredCRLPolicy, final String[] certFiles, final String crlFile, final GeneralSecurityException expected) { super(certFiles, expected); this.checker = checker; this.checker.setExpiredCRLPolicy(expiredCRLPolicy); this.webServer = new MockWebServer(8085, new ClassPathResource(crlFile), "text/plain"); }
/** * Make vars.properties available to spring integration configuration * System properties are only used if there is no setting in vars.properties. */ @Bean(name = "aemServiceConfigurationPropertiesConfigurer") public static PropertySourcesPlaceholderConfigurer configurer() { PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); ppc.setLocation(new ClassPathResource("META-INF/spring/jwala-defaults.properties")); ppc.setLocalOverride(true); ppc.setProperties(ApplicationProperties.getProperties()); return ppc; }
@Test public void getVersion() throws Exception { 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.getVersion(subscription); Assert.assertEquals("4.3.2", version); }
@Before public void setUp() throws Exception { this.authenticationHandler = new FileAuthenticationHandler(); this.authenticationHandler.setFileName( new ClassPathResource("org/jasig/cas/adaptors/generic/authentication.txt")); }
@Test public void testVcapTwoServicesSameServiceType() { Resource resource = new ClassPathResource("/vcap4.json"); String content; try { content = new String(Files.readAllBytes(Paths.get(resource.getURI()))); VcapResult result = parser.parse(content); VcapPojo[] pojos = result.getPojos(); assertNotNull(pojos); assertEquals(2, pojos.length); int matches = result.findCountByServiceType(VcapServiceType.AZURE_STORAGE); assertEquals(2, matches); VcapPojo pojo = result.findPojoForServiceTypeAndServiceInstanceName(VcapServiceType.AZURE_STORAGE, "mystorage"); LOG.debug("pojo = " + pojo); assertNotNull(pojo); pojo = result.findPojoForServiceTypeAndServiceInstanceName(VcapServiceType.AZURE_STORAGE, "mystorage2"); LOG.debug("pojo = " + pojo); assertNotNull(pojo); } catch (IOException e) { LOG.error("Error reading json file", e); } }
protected static X509Certificate[] createCertificates(final String... files) { final X509Certificate[] certs = new X509Certificate[files.length]; int i = 0; for (final String file : files) { try { certs[i++] = CertUtil.readCertificate(new ClassPathResource(file).getInputStream()); } catch (final Exception e) { throw new RuntimeException("Error creating certificate at " + file, e); } } return certs; }
/** * Read the spot region to the new format from an external JSON file. * * @throws IOException * When the JSON mapping file cannot be read. */ @PostConstruct public void initSpotToNewRegion() throws IOException { mapSpotToNewRegion.putAll(objectMapper.readValue( IOUtils.toString(new ClassPathResource(SPOT_TO_NEW_REGION_FILE).getInputStream(), StandardCharsets.UTF_8), new TypeReference<Map<String, String>>() { // Nothing to extend })); }
public void testPropertiesLoading() throws Exception { Properties testSettings = bundleCreator.getSettings(); Properties props = new Properties(); props.load(new ClassPathResource( "org/eclipse/gemini/blueprint/test/ConfigurableBundleCreatorTestsTest$1-bundle.properties").getInputStream()); assertEquals(props.getProperty(AbstractConfigurableBundleCreatorTests.INCLUDE_PATTERNS), testSettings.getProperty(AbstractConfigurableBundleCreatorTests.INCLUDE_PATTERNS)); assertEquals(props.getProperty(AbstractConfigurableBundleCreatorTests.MANIFEST), testSettings.getProperty(AbstractConfigurableBundleCreatorTests.MANIFEST)); }
@Bean public EhCacheManagerFactoryBean ehcache(){ EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean(); ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml")); ehCacheManagerFactoryBean.setShared(true); return ehCacheManagerFactoryBean; }
@Test public void testAuthenticatesUserInFileWithCommaSeparator() throws Exception { final UsernamePasswordCredential c = new UsernamePasswordCredential(); this.authenticationHandler.setFileName( new ClassPathResource("org/jasig/cas/adaptors/generic/authentication2.txt")); this.authenticationHandler.setSeparator(","); c.setUsername("scott"); c.setPassword("rutgers"); assertNotNull(this.authenticationHandler.authenticate(c)); }
@Test public void testZUploadWithInsertWithReIndex() throws Exception { startOperationalServer(); this.subscription = getSubscription("gStack"); resource.upload(new ClassPathResource("csv/upload/nominal-complete5.csv").getInputStream(), ENCODING, subscription, UploadMode.FULL); final ImportStatus result = jiraResource.getTask(subscription); Assert.assertEquals(7, result.getChanges().intValue()); Assert.assertEquals(3, result.getIssues().intValue()); Assert.assertEquals(30, result.getStep()); Assert.assertTrue(result.getCanSynchronizeJira()); Assert.assertTrue(result.getScriptRunner()); Assert.assertTrue(result.getSynchronizedJira()); }