Java Code Examples for org.springframework.core.io.ClassPathResource

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project c24-spring, under directory /c24-spring-integration/src/test/java/biz/c24/io/spring/integration/test/.

Source file: TestUtils.java

  22 
vote

public static ComplexDataObject loadObject() throws Exception {
  ClassPathResource resource=new ClassPathResource("valid-1.txt");
  TextualSource textualSource=new TextualSource(resource.getInputStream());
  ComplexDataObject object=textualSource.readObject(InputDocumentRootElement.getInstance());
  return object;
}
 

Example 2

From project Carolina-Digital-Repository, under directory /metadata/src/test/java/edu/unc/lib/dl/schematron/.

Source file: SchematronValidatorTest.java

  22 
vote

/** 
 * Test initialization of SchematronValidator.
 */
@Test public void testLoadSchemas(){
  SchematronValidator sv=new SchematronValidator();
  sv.loadSchemas();
  ClassPathResource test=new ClassPathResource("simple_mets_profile.sch",SchematronValidator.class);
  sv.getSchemas().put("test",test);
  sv.loadSchemas();
  sv.loadSchemas();
}
 

Example 3

From project ehour, under directory /eHour-persistence/src/main/java/net/rrm/ehour/persistence/appconfig/.

Source file: HibernateConfiguration.java

  22 
vote

private List<Resource> getMappingResources(Properties configProperties) throws IOException {
  List<Resource> resources=new ArrayList<Resource>();
  Resource[] queryResources=resolver.getResources("classpath:query/common/*.hbm.xml");
  resources.addAll(Arrays.asList(queryResources));
  ClassPathResource dbQueryResource=new ClassPathResource("query/" + configProperties.getProperty("reportquery.filename"));
  resources.add(dbQueryResource);
  return resources;
}
 

Example 4

From project moho, under directory /moho-remote/src/main/java/com/voxeo/rayo/client/xmpp/extensions/.

Source file: XmlProviderManagerFactory.java

  22 
vote

public static XmlProviderManager buildXmlProvider(){
  ClassPathResource res=new ClassPathResource("rayo-providers.xml");
  XmlBeanFactory factory=new XmlBeanFactory(res);
  XmlProviderManager manager=(XmlProviderManager)factory.getBean("xmlProviderManager");
  Validator validator=(Validator)factory.getBean("validator");
  RayoClientProvider rayoClientProvider=new RayoClientProvider();
  rayoClientProvider.setNamespaces(new ArrayList<String>());
  rayoClientProvider.getNamespaces().add("urn:xmpp:rayo:1");
  rayoClientProvider.getNamespaces().add("jabber:client");
  rayoClientProvider.setValidator(validator);
  rayoClientProvider.setClasses(new ArrayList<Class<?>>());
  manager.register(rayoClientProvider);
  return manager;
}
 

Example 5

From project OpenConext-api, under directory /coin-api-war/src/main/java/nl/surfnet/coin/api/service/.

Source file: MockServiceImpl.java

  22 
vote

@Override public GroupEntry getGroups(String userId,String onBehalfOf,Integer count,Integer startIndex,String sortBy){
  ClassPathResource pathResource=new ClassPathResource(String.format(JSON_PATH,userId,"groups"));
  if (!pathResource.exists()) {
    pathResource=new ClassPathResource(String.format(JSON_PATH,FALLBACK,"groups"));
  }
  try {
    return parser.parseGroups(pathResource.getInputStream());
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 6

From project sched-assist, under directory /sched-assist-spi-relationships/src/test/java/org/jasig/schedassist/impl/relationship/advising/.

Source file: AdvisorListRelationshipDataSourceImplTest.java

  22 
vote

@Test public void testSampleDataSource() throws Exception {
  ClassPathResource sample=new ClassPathResource("sample-advisorlist-data.txt");
  AdvisorListRelationshipDataSourceImpl dataSource=new AdvisorListRelationshipDataSourceImpl();
  List<StudentAdvisorAssignment> records=dataSource.readResource(sample,"1094");
  Assert.assertEquals(3,records.size());
  for (  StudentAdvisorAssignment rec : records) {
    Assert.assertEquals("1094",rec.getTermNumber());
    Assert.assertEquals("Spring 2008-2009",rec.getTermDescription());
    Assert.assertNull(rec.getCommitteeRole());
  }
}
 

Example 7

From project security_2, under directory /api/src/main/java/org/intalio/tempo/security/simple/.

Source file: SimpleSecurityProvider.java

  22 
vote

public InputStream getConfigStream() throws IOException {
  String filename=SystemPropertyUtils.resolvePlaceholders(_filename);
  File file=new File(filename);
  if (!file.exists()) {
    ClassPathResource resource=new ClassPathResource(filename);
    return resource.getInputStream();
  }
  return new FileInputStream(filename);
}
 

Example 8

From project android-joedayz, under directory /Proyectos/client/src/org/springframework/android/showcase/rest/.

Source file: HttpPostFormDataActivity.java

  21 
vote

@Override protected void onPreExecute(){
  showLoadingProgressDialog();
  Resource resource=new ClassPathResource("res/drawable/spring09_logo.png");
  formData=new LinkedMultiValueMap<String,Object>();
  formData.add("description","Spring logo");
  formData.add("file",resource);
}
 

Example 9

From project cas, under directory /cas-server-core/src/test/java/org/jasig/cas/authentication/principal/.

Source file: GoogleAccountsServiceTests.java

  21 
vote

public static GoogleAccountsService getGoogleAccountsService() throws Exception {
  final PublicKeyFactoryBean pubKeyFactoryBean=new PublicKeyFactoryBean();
  pubKeyFactoryBean.setAlgorithm("DSA");
  final PrivateKeyFactoryBean privKeyFactoryBean=new PrivateKeyFactoryBean();
  privKeyFactoryBean.setAlgorithm("DSA");
  final ClassPathResource pubKeyResource=new ClassPathResource("DSAPublicKey01.key");
  final ClassPathResource privKeyResource=new ClassPathResource("DSAPrivateKey01.key");
  pubKeyFactoryBean.setLocation(pubKeyResource);
  privKeyFactoryBean.setLocation(privKeyResource);
  pubKeyFactoryBean.afterPropertiesSet();
  privKeyFactoryBean.afterPropertiesSet();
  final DSAPrivateKey privateKey=(DSAPrivateKey)privKeyFactoryBean.getObject();
  final DSAPublicKey publicKey=(DSAPublicKey)pubKeyFactoryBean.getObject();
  final MockHttpServletRequest request=new MockHttpServletRequest();
  final String SAMLRequest="<?xml version=\"1.0\" encoding=\"UTF-8\"?><samlp:AuthnRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\"5545454455\" Version=\"2.0\" IssueInstant=\"Value\" ProtocolBinding=\"urn:oasis:names.tc:SAML:2.0:bindings:HTTP-Redirect\" ProviderName=\"https://localhost:8443/myRutgers\" AssertionConsumerServiceURL=\"https://localhost:8443/myRutgers\"/>";
  request.setParameter("SAMLRequest",encodeMessage(SAMLRequest));
  return GoogleAccountsService.createServiceFrom(request,privateKey,publicKey,"username");
}
 

Example 10

From project empire-db, under directory /empire-db-examples/empire-db-example-spring/src/main/java/org/apache/empire/samples/spring/.

Source file: SampleSpringApp.java

  21 
vote

static GenericApplicationContext getContext(){
  log.info("Creating Spring Application Context ...");
  GenericApplicationContext ctx=new GenericApplicationContext();
  XmlBeanDefinitionReader reader=new XmlBeanDefinitionReader(ctx);
  reader.loadBeanDefinitions(new ClassPathResource("/applicationContext.xml"));
  ctx.refresh();
  return ctx;
}
 

Example 11

From project faces, under directory /Proyectos/02-richfaces-solution/src/test/java/accounts/internal/dao/.

Source file: HibernateAccountRepositoryTest.java

  21 
vote

private SessionFactory createTestSessionFactory() throws Exception {
  LocalSessionFactoryBean factoryBean=new LocalSessionFactoryBean();
  factoryBean.setDataSource(createTestDataSource());
  Resource[] mappingLocations=new ClassPathResource[]{new ClassPathResource("Account.hbm.xml",HibernateAccountRepository.class),new ClassPathResource("Beneficiary.hbm.xml",HibernateAccountRepository.class)};
  factoryBean.setMappingLocations(mappingLocations);
  factoryBean.setHibernateProperties(createHibernateProperties());
  factoryBean.afterPropertiesSet();
  return (SessionFactory)factoryBean.getObject();
}
 

Example 12

From project galaxy, under directory /src/co/paralleluniverse/galaxy/.

Source file: Grid.java

  21 
vote

private Grid(String configFile,Object properties) throws InterruptedException {
  this.context=SpringContainerHelper.createContext("co.paralleluniverse.galaxy",configFile != null ? new FileSystemResource(configFile) : new ClassPathResource("galaxy.xml"),properties instanceof String ? new FileSystemResource((String)properties) : properties,new BeanFactoryPostProcessor(){
    @Override public void postProcessBeanFactory(    ConfigurableListableBeanFactory beanFactory1) throws BeansException {
      final DefaultListableBeanFactory beanFactory=((DefaultListableBeanFactory)beanFactory1);
    }
  }
);
  this.cluster=context.getBean("cluster",Cluster.class);
  this.clusterMonitor=new ClusterMonitor(cluster);
  this.backup=context.getBean("backup",Backup.class);
  this.cache=context.getBean("cache",Cache.class);
  this.store=new StoreImpl(cache);
  this.messenger=context.getBean("messenger",Messenger.class);
}
 

Example 13

From project Gemini-Blueprint, under directory /core/src/test/java/org/eclipse/gemini/blueprint/blueprint/config/.

Source file: CompendiumCmElementTst.java

  21 
vote

protected void setUp() throws Exception {
  context=new GenericApplicationContext();
  context.setClassLoader(getClass().getClassLoader());
  reader=new XmlBeanDefinitionReader(context);
  reader.loadBeanDefinitions(new ClassPathResource(CONFIG,getClass()));
  context.refresh();
}
 

Example 14

From project grails-searchable, under directory /src/java/grails/plugin/searchable/internal/.

Source file: SearchableUtils.java

  21 
vote

private static Map loadMetadata(){
  Resource r=new ClassPathResource(PROJECT_META_FILE);
  if (r.exists()) {
    return loadMetadata(r);
  }
  String basedir=System.getProperty("base.dir");
  if (basedir != null) {
    r=new FileSystemResource(new File(basedir,PROJECT_META_FILE));
    if (r.exists()) {
      return loadMetadata(r);
    }
  }
  return null;
}
 

Example 15

From project greenhouse, under directory /src/main/java/com/springsource/greenhouse/database/.

Source file: DatabaseUpgrader.java

  21 
vote

private void addInstallChangeSet(GenericDatabaseUpgrader upgrader){
  DatabaseChangeSet changeSet=new DatabaseChangeSet(DatabaseVersion.valueOf("4"));
  changeSet.add(installScript("Member.sql"));
  changeSet.add(installScript("Group.sql"));
  changeSet.add(installScript("Activity.sql"));
  changeSet.add(installScript("ConnectedApp.sql"));
  changeSet.add(installScript("Reset.sql"));
  changeSet.add(installScript("Invite.sql"));
  changeSet.add(installScript("Venue.sql"));
  changeSet.add(installScript("Event.sql"));
  changeSet.add(SqlDatabaseChange.inResource(new ClassPathResource("JdbcUsersConnectionRepository.sql",JdbcUsersConnectionRepository.class)));
  addInstallChanges(changeSet);
  upgrader.addChangeSet(changeSet);
}
 

Example 16

From project java-maven-tests, under directory /src/pg-lock-test/src/main/java/com/alexshabanov/service/impl/conf/.

Source file: AppConfigurationManager.java

  21 
vote

/** 
 * {@inheritDoc}Add all the inferior context's beans definitions.
 */
@Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
  final DefaultListableBeanFactory beanFactory=new DefaultListableBeanFactory(hostContext);
  final XmlBeanDefinitionReader reader=new XmlBeanDefinitionReader(beanFactory);
  reader.loadBeanDefinitions(new ClassPathResource(daoContextLocation),new ClassPathResource(INFERIOR_CONTEXT_LOCATION));
  hostPropertyConfigurer.postProcessBeanFactory(beanFactory);
  for (  final String beanName : reader.getBeanFactory().getBeanDefinitionNames()) {
    registry.registerBeanDefinition(beanName,reader.getBeanFactory().getBeanDefinition(beanName));
  }
}
 

Example 17

From project jsecurity, under directory /samples/spring/src/main/java/org/apache/ki/samples/spring/ui/.

Source file: WebStartView.java

  21 
vote

public void afterPropertiesSet() throws Exception {
  ClassPathResource resource=new ClassPathResource("logo.png");
  ImageIcon icon=new ImageIcon(resource.getURL());
  JLabel logo=new JLabel(icon);
  valueField=new JTextField(20);
  updateValueLabel();
  saveButton=new JButton("Save Value");
  saveButton.addActionListener(this);
  refreshButton=new JButton("Refresh Value");
  refreshButton.addActionListener(this);
  JPanel valuePanel=new JPanel(new FlowLayout(FlowLayout.CENTER));
  valuePanel.add(valueField);
  valuePanel.add(saveButton);
  valuePanel.add(refreshButton);
  secureMethod1Button=new JButton("Method #1");
  secureMethod1Button.addActionListener(this);
  secureMethod2Button=new JButton("Method #2");
  secureMethod2Button.addActionListener(this);
  secureMethod3Button=new JButton("Method #3");
  secureMethod3Button.addActionListener(this);
  JPanel methodPanel=new JPanel(new FlowLayout(FlowLayout.CENTER));
  methodPanel.add(secureMethod1Button);
  methodPanel.add(secureMethod2Button);
  methodPanel.add(secureMethod3Button);
  frame=new JFrame("Apache Ki Sample Application");
  frame.setSize(500,200);
  Container panel=frame.getContentPane();
  panel.setLayout(new BorderLayout());
  panel.add(logo,BorderLayout.NORTH);
  panel.add(valuePanel,BorderLayout.CENTER);
  panel.add(methodPanel,BorderLayout.SOUTH);
  frame.setVisible(true);
  frame.addWindowListener(new WindowAdapter(){
    public void windowClosing(    WindowEvent e){
      System.exit(0);
    }
  }
);
}
 

Example 18

From project mongeez, under directory /src/test/java/org/mongeez/.

Source file: MongeezTest.java

  21 
vote

private Mongeez create(String path){
  Mongeez mongeez=new Mongeez();
  mongeez.setFile(new ClassPathResource(path));
  mongeez.setMongo(mongo);
  mongeez.setDbName(dbName);
  mongeez.setVerbose(true);
  return mongeez;
}
 

Example 19

From project Mujina, under directory /mujina-sp/src/main/java/nl/surfnet/mujina/controllers/.

Source file: OpenSocialAPI.java

  21 
vote

public OpenSocialAPI(){
  super();
  Properties properties=new Properties();
  try {
    properties.load(new ClassPathResource("mujina-sp.properties").getInputStream());
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
  oauthCallbackUrl=properties.getProperty("OAUTH_CALLBACK_URL");
}
 

Example 20

From project nsi-minlog, under directory /functional-tests/src/test/java/dk/nsi/minlog/test/.

Source file: TestDBConfig.java

  21 
vote

@Bean public static PropertyPlaceholderConfigurer configuration(){
  final PropertyPlaceholderConfigurer props=new PropertyPlaceholderConfigurer();
  props.setLocations(new Resource[]{new ClassPathResource("default.properties"),new FileSystemResource(getProperty("jboss.server.config.url") + "minlog." + getProperty("user.name")+ ".properties"),new ClassPathResource("minlog." + getProperty("user.name") + ".properties"),new ClassPathResource("jdbc.default.properties"),new FileSystemResource(getProperty("jboss.server.config.url") + "jdbc." + getProperty("user.name")+ ".properties"),new ClassPathResource("jdbc." + getProperty("user.name") + ".properties"),new FileSystemResource(getProperty("user.home") + "/.minlog/passwords.properties")});
  props.setIgnoreResourceNotFound(true);
  props.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
  return props;
}
 

Example 21

From project obpro_team_p, under directory /twitter/twitter4j-stream/src/test/java/twitter4j/.

Source file: SpringCompatibilityTest.java

  21 
vote

protected void setUp() throws Exception {
  super.setUp();
  writeFile("./twitter4j.properties","user=one" + "\n" + "password=pasword-one");
  Resource res=new ClassPathResource("spring-beans.xml");
  beanFactory=new XmlBeanFactory(res);
}
 

Example 22

From project occi4java, under directory /core/src/main/java/occi/config/.

Source file: SpringOcciConfig.java

  21 
vote

@Bean public static PropertySourcesPlaceholderConfigurer properties(){
  PropertySourcesPlaceholderConfigurer pspc=new PropertySourcesPlaceholderConfigurer();
  Resource[] resources=new ClassPathResource[]{new ClassPathResource("OCCI.properties")};
  pspc.setLocations(resources);
  pspc.setIgnoreUnresolvablePlaceholders(true);
  return pspc;
}
 

Example 23

From project OpenConext-shared, under directory /src/main/java/nl/surfnet/coin/shared/service/.

Source file: ErrorMessageMailer.java

  21 
vote

/** 
 * Returns the contents of the mail template as a String
 * @param templateName the name of the mail template file, must be inside the folder{@literal mailtemplates}
 * @return the mail template as String
 * @throws java.io.IOException if the template file cannot be read
 */
String getTemplate(String templateName) throws IOException {
  InputStream input=null;
  try {
    input=new ClassPathResource("mailtemplates/" + templateName).getInputStream();
    return input == null ? "" : IOUtils.toString(input);
  }
  finally {
    if (input != null) {
      input.close();
    }
  }
}
 

Example 24

From project OpenConext-teams, under directory /coin-teams-war/src/test/java/nl/surfnet/coin/teams/control/.

Source file: AbstractControllerTest.java

  21 
vote

/** 
 * Creates Freemarker  {@link Configuration} that loads the template from the classpath folder {@literal ftl}
 * @return Freemarker Configuration
 * @throws IOException when this folder cannot be found
 */
protected Configuration getFreemarkerConfig() throws IOException {
  Configuration freemarkerConfiguration=new Configuration();
  Resource templateDir=new ClassPathResource("/ftl/");
  freemarkerConfiguration.setDirectoryForTemplateLoading(templateDir.getFile());
  freemarkerConfiguration.setObjectWrapper(new DefaultObjectWrapper());
  return freemarkerConfiguration;
}
 

Example 25

From project OpenTripPlanner, under directory /opentripplanner-integration/src/main/java/org/opentripplanner/integration/benchmark/.

Source file: RunBenchmarkPlanMain.java

  21 
vote

private GenericApplicationContext getApplicationContext(){
  GenericApplicationContext ctx=new GenericApplicationContext();
  XmlBeanDefinitionReader xmlReader=new XmlBeanDefinitionReader(ctx);
  xmlReader.loadBeanDefinitions(new ClassPathResource("org/opentripplanner/application-context.xml"));
  Map<String,BeanDefinition> additionalBeans=getAdditionalBeans();
  for (  Map.Entry<String,BeanDefinition> entry : additionalBeans.entrySet())   ctx.registerBeanDefinition(entry.getKey(),entry.getValue());
  ctx.refresh();
  ctx.registerShutdownHook();
  return ctx;
}
 

Example 26

From project qcadoo, under directory /qcadoo-model/src/main/java/com/qcadoo/model/internal/module/.

Source file: ModelModule.java

  21 
vote

@Override public void init(){
  try {
    modelXmlHolder.put(pluginIdentifier,modelName,new ClassPathResource(pluginIdentifier + "/" + resource).getInputStream());
  }
 catch (  IOException e) {
    throw new IllegalStateException(e.getMessage(),e);
  }
}
 

Example 27

From project randi2, under directory /src/test/java/de/randi2/ui/integration/.

Source file: AbstractUITest.java

  21 
vote

@BeforeClass public static void loadTestProperties(){
  try {
    testData.load((new ClassPathResource("testData.properties").getInputStream()));
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 28

From project rave, under directory /rave-providers/rave-opensocial-provider/rave-opensocial-core/src/main/java/org/apache/rave/commoncontainer/.

Source file: ConfigurablePropertiesModule.java

  21 
vote

/** 
 * 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());
  }
}
 

Example 29

From project riot, under directory /common/src/org/riotfamily/common/beans/config/.

Source file: ProfileConfigurer.java

  21 
vote

@Override public void afterPropertiesSet() throws Exception {
  Resource defaultProps=new ClassPathResource(getPath(defaultProfile));
  Resource profileProps=new ClassPathResource(getPath(getProfile()));
  setLocations(new Resource[]{defaultProps,profileProps});
  super.afterPropertiesSet();
}
 

Example 30

From project s4, under directory /s4-core/src/test/java/org/apache/s4/ft/.

Source file: S4App.java

  21 
vote

private void initConfigPaths(Class testClass,String s4CoreConfFileName) throws IOException {
  if (!configPathsInitialized) {
    S4TestCase.initS4Parameters();
    String testDir=testClass.getPackage().getName().replace('.',File.separatorChar);
    ClassPathResource propResource=new ClassPathResource("s4_core.properties");
    Properties prop=new Properties();
    if (propResource.exists()) {
      prop.load(propResource.getInputStream());
    }
 else {
      System.err.println("Unable to find s4_core.properties. It must be available in classpath");
      Thread.dumpStack();
      System.exit(12);
    }
    configBase=System.getProperty("user.dir") + File.separator + "src"+ File.separator+ "test"+ File.separator+ "java"+ File.separator+ testDir+ File.separator;
    String configPath=configBase + File.separatorChar + "wall_clock.xml";
    List<String> coreConfigUrls=new ArrayList<String>();
    coreConfigUrls.add(configPath);
    if (s4CoreConfFileName != null) {
      configPath=configBase + s4CoreConfFileName;
      File configFile=new File(configPath);
      if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n",configPath);
        Thread.dumpStack();
        System.exit(13);
      }
      coreConfigUrls.add(configPath);
    }
    String[] coreConfigFiles=new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);
    coreConfigFileUrls=new String[coreConfigFiles.length];
    for (int i=0; i < coreConfigFiles.length; i++) {
      coreConfigFileUrls[i]="file:" + coreConfigFiles[i];
    }
    configPathsInitialized=true;
  }
}
 

Example 31

From project shiro, under directory /samples/spring-client/src/main/java/org/apache/shiro/samples/spring/ui/.

Source file: WebStartView.java

  21 
vote

public void afterPropertiesSet() throws Exception {
  ClassPathResource resource=new ClassPathResource("logo.png");
  ImageIcon icon=new ImageIcon(resource.getURL());
  JLabel logo=new JLabel(icon);
  valueField=new JTextField(20);
  updateValueLabel();
  saveButton=new JButton("Save Value");
  saveButton.addActionListener(this);
  refreshButton=new JButton("Refresh Value");
  refreshButton.addActionListener(this);
  JPanel valuePanel=new JPanel(new FlowLayout(FlowLayout.CENTER));
  valuePanel.add(valueField);
  valuePanel.add(saveButton);
  valuePanel.add(refreshButton);
  secureMethod1Button=new JButton("Method #1");
  secureMethod1Button.addActionListener(this);
  secureMethod2Button=new JButton("Method #2");
  secureMethod2Button.addActionListener(this);
  secureMethod3Button=new JButton("Method #3");
  secureMethod3Button.addActionListener(this);
  JPanel methodPanel=new JPanel(new FlowLayout(FlowLayout.CENTER));
  methodPanel.add(secureMethod1Button);
  methodPanel.add(secureMethod2Button);
  methodPanel.add(secureMethod3Button);
  frame=new JFrame("Apache Shiro Sample Application");
  frame.setSize(500,200);
  Container panel=frame.getContentPane();
  panel.setLayout(new BorderLayout());
  panel.add(logo,BorderLayout.NORTH);
  panel.add(valuePanel,BorderLayout.CENTER);
  panel.add(methodPanel,BorderLayout.SOUTH);
  frame.setVisible(true);
  frame.addWindowListener(new WindowAdapter(){
    public void windowClosing(    WindowEvent e){
      System.exit(0);
    }
  }
);
}
 

Example 32

From project spring-amqp, under directory /spring-rabbit/src/test/java/org/springframework/amqp/rabbit/config/.

Source file: AdminParserTests.java

  21 
vote

/** 
 * Load application context. Fail if tests expects invalid spring-context, but spring-context is valid.
 * @return
 */
private XmlBeanFactory loadContext(){
  XmlBeanFactory beanFactory=null;
  try {
    ClassPathResource resource=new ClassPathResource(getClass().getSimpleName() + "-" + contextIndex+ "-context.xml",getClass());
    beanFactory=new XmlBeanFactory(resource);
    if (!validContext) {
      fail("Context " + resource + " suppose to fail");
    }
  }
 catch (  BeanDefinitionParsingException e) {
    if (validContext) {
      throw e;
    }
    logger.warn("Failure was expected",e);
  }
  return beanFactory;
}
 

Example 33

From project spring-android, under directory /spring-android-rest-template-test/src/main/java/org/springframework/web/client/.

Source file: AbstractRestTemplateIntegrationTests.java

  21 
vote

@MediumTest public void testMultipart() throws UnsupportedEncodingException {
  MultiValueMap<String,Object> parts=new LinkedMultiValueMap<String,Object>();
  parts.add("name 1","value 1");
  parts.add("name 2","value 2+1");
  parts.add("name 2","value 2+2");
  Resource logo=new ClassPathResource("res/drawable/icon.png");
  parts.add("logo",logo);
  restTemplate.postForLocation(baseUrl + "/multipart",parts);
}
 

Example 34

From project spring-android-samples, under directory /spring-android-showcase/client/src/org/springframework/android/showcase/rest/.

Source file: HttpPostFormDataActivity.java

  21 
vote

@Override protected void onPreExecute(){
  showLoadingProgressDialog();
  Resource resource=new ClassPathResource("res/drawable/spring09_logo.png");
  formData=new LinkedMultiValueMap<String,Object>();
  formData.add("description","Spring logo");
  formData.add("file",resource);
}
 

Example 35

From project spring-batch-admin, under directory /spring-batch-admin-manager/src/test/java/org/springframework/batch/admin/sample/.

Source file: JobConfigurationRequestIntegrationTests.java

  21 
vote

@Test @DirtiesContext public void testRegisterFromSimpleRequestString() throws Exception {
  MessagingTemplate gateway=new MessagingTemplate();
  gateway.setReceiveTimeout(500L);
  gateway.afterPropertiesSet();
  JobConfigurationRequest request=new JobConfigurationRequest();
  request.setXml(IOUtils.toString(new ClassPathResource("/staging-context.xml").getInputStream()));
  gateway.convertAndSend(requests,request);
  assertNotNull("Time out waiting for reply",result);
  assertEquals("[staging]",result.toString());
}
 

Example 36

From project spring-data-book, under directory /jpa/src/test/java/com/oreilly/springdata/jpa/.

Source file: AbstractIntegrationTest.java

  21 
vote

/** 
 * Populates the configured  {@link DataSource} with data from {@code data.sql}.
 * @throws SQLException
 */
@Before public void populateDatabase() throws SQLException {
  ResourceDatabasePopulator populator=new ResourceDatabasePopulator();
  populator.addScript(new ClassPathResource("data.sql"));
  Connection connection=null;
  try {
    connection=DataSourceUtils.getConnection(dataSource);
    populator.populate(connection);
  }
  finally {
    if (connection != null) {
      DataSourceUtils.releaseConnection(connection,dataSource);
    }
  }
}
 

Example 37

From project spring-data-commons, under directory /spring-data-commons-core/src/test/java/org/springframework/data/repository/config/.

Source file: TypeFilterParserUnitTests.java

  21 
vote

@Before public void setUp() throws SAXException, IOException, ParserConfigurationException {
  parser=new TypeFilterParser(context,classLoader);
  Resource sampleXmlFile=new ClassPathResource("type-filter-test.xml",TypeFilterParserUnitTests.class);
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  documentElement=factory.newDocumentBuilder().parse(sampleXmlFile.getInputStream()).getDocumentElement();
}
 

Example 38

From project spring-data-jpa, under directory /src/test/java/org/springframework/data/jpa/domain/support/.

Source file: AuditingBeanFactoryPostProcessorUnitTests.java

  21 
vote

@Before public void setUp(){
  beanFactory=new DefaultListableBeanFactory();
  XmlBeanDefinitionReader reader=new XmlBeanDefinitionReader(beanFactory);
  reader.loadBeanDefinitions(new ClassPathResource("auditing/" + getConfigFile()));
  processor=new AuditingBeanFactoryPostProcessor();
}
 

Example 39

From project spring-data-mongodb, under directory /spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/.

Source file: MongoDbFactoryParserIntegrationTests.java

  21 
vote

/** 
 * @see DATADOC-295
 */
@Test public void setsUpMongoDbFactoryUsingAMongoUri(){
  reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-uri.xml"));
  BeanDefinition definition=factory.getBeanDefinition("mongoDbFactory");
  ConstructorArgumentValues constructorArguments=definition.getConstructorArgumentValues();
  assertThat(constructorArguments.getArgumentCount(),is(1));
  ValueHolder argument=constructorArguments.getArgumentValue(0,MongoURI.class);
  assertThat(argument,is(notNullValue()));
}
 

Example 40

From project spring-flex-roo, under directory /org.springframework.flex.roo.addon/src/test/java/org/springframework/flex/roo/addon/as/classpath/as3parser/.

Source file: As3ParserClassMetadataValidParsingTests.java

  21 
vote

@Before public void setUp() throws Exception {
  initMocks(this);
  when(processManager.isDevelopmentMode()).thenReturn(true);
  ActiveProcessManager.setActiveProcessManager(processManager);
  String fileIdentifier=new ClassPathResource("com/foo/stuff/FooImpl.as").getFile().getCanonicalPath();
  metadataId="MID:" + ASPhysicalTypeIdentifier.class.getName() + "#SRC_MAIN_FLEX?com.foo.stuff.FooImpl";
  metadata=new As3ParserClassMetadata(fileManager,fileIdentifier,metadataId,metadataService,provider);
  assertNotNull(metadata);
  assertNotNull(metadata.getPhysicalTypeDetails());
  details=(As3ParserMutableClassOrInterfaceTypeDetails)metadata.getPhysicalTypeDetails();
}
 

Example 41

From project ANNIS, under directory /annis-service/src/main/java/annis/administration/.

Source file: AnnisAdminRunner.java

  20 
vote

private void usage(String error){
  Resource resource=new ClassPathResource("annis/administration/usage.txt");
  BufferedReader reader=null;
  try {
    reader=new BufferedReader(new InputStreamReader(resource.getInputStream(),"UTF-8"));
    for (String line=reader.readLine(); line != null; line=reader.readLine()) {
      System.out.println(line);
    }
  }
 catch (  IOException e) {
    log.warn("could not read usage information: " + e.getMessage());
  }
 finally {
    if (reader != null) {
      try {
        reader.close();
      }
 catch (      IOException ex) {
        log.error(null,ex);
      }
    }
  }
  if (error != null) {
    error(error);
  }
}
 

Example 42

From project bioportal-service, under directory /src/test/java/edu/mayo/cts2/framework/plugin/service/bioportal/service/transform/.

Source file: AssociationTransformTest.java

  20 
vote

@Before public void buildTransform() throws Exception {
  this.associationTransform=new AssociationTransform();
  IdentityConverter idConverter=EasyMock.createMock(IdentityConverter.class);
  UrlConstructor urlConstructor=EasyMock.createNiceMock(UrlConstructor.class);
  EasyMock.expect(idConverter.ontologyIdToCodeSystemName("1104")).andReturn("testCsName").anyTimes();
  EasyMock.expect(idConverter.ontologyVersionIdToCodeSystemVersionName("1104","44450")).andReturn("testCsVersionName").anyTimes();
  EasyMock.expect(idConverter.getCodeSystemAbout("csName","http://purl.bioontology.org/ontology/")).andReturn("http://test.doc.uri").anyTimes();
  EasyMock.expect(idConverter.getCodeSystemAbout("ICD10","http://purl.bioontology.org/ontology/")).andReturn("http://test.doc.uri").anyTimes();
  EasyMock.expect(idConverter.codeSystemVersionNameToVersion("ICD10")).andReturn("ICD10").anyTimes();
  EasyMock.replay(idConverter,urlConstructor);
  this.associationTransform.setIdentityConverter(idConverter);
  this.associationTransform.setUrlConstructor(urlConstructor);
  Resource resource=new ClassPathResource("bioportalXml/entityDescription.xml");
  StringWriter sw=new StringWriter();
  IOUtils.copy(resource.getInputStream(),sw);
  this.xml=sw.toString();
}
 

Example 43

From project flyway, under directory /flyway-commandline-largetest/src/test/java/com/googlecode/flyway/commandline/largetest/.

Source file: CommandLineLargeTest.java

  20 
vote

/** 
 * Runs the Flyway Command Line tool.
 * @param expectedReturnCode The expected return code for this invocation.
 * @param configFileName     The config file name. {@code null} for default.
 * @param operation          The operation {@code null} for none.
 * @param extraArgs          The extra arguments to pass to the tool.
 * @return The standard output produced by the tool.
 * @throws Exception thrown when the invocation failed.
 */
private String runFlywayCommandLine(int expectedReturnCode,String configFileName,String operation,String... extraArgs) throws Exception {
  List<String> args=new ArrayList<String>();
  String installDir=System.getProperty("installDir");
  args.add(installDir + "/flyway." + flywayCmdLineExtensionForCurrentSystem());
  if (operation != null) {
    args.add(operation);
  }
  if (configFileName != null) {
    String configFile=new ClassPathResource(configFileName).getFile().getPath();
    args.add("-configFile=" + configFile);
  }
  args.addAll(Arrays.asList(extraArgs));
  args.add("-X");
  ProcessBuilder builder=new ProcessBuilder(args);
  builder.directory(new File(installDir));
  builder.redirectErrorStream(true);
  Process process=builder.start();
  String stdOut=FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(),"UTF-8"));
  int returnCode=process.waitFor();
  System.out.print(stdOut);
  assertEquals("Unexpected return code",expectedReturnCode,returnCode);
  return stdOut;
}
 

Example 44

From project geronimo-xbean, under directory /xbean-spring/src/main/java/org/apache/xbean/spring/jndi/.

Source file: SpringInitialContextFactory.java

  20 
vote

public Context getInitialContext(Hashtable environment) throws NamingException {
  if (singleton != null) {
    return singleton;
  }
  Resource resource=null;
  Object value=environment.get(Context.PROVIDER_URL);
  String key="jndi.xml";
  if (value == null) {
    resource=new ClassPathResource(key);
  }
 else {
    if (value instanceof Resource) {
      resource=(Resource)value;
    }
 else {
      ResourceEditor editor=new ResourceEditor();
      key=value.toString();
      editor.setAsText(key);
      resource=(Resource)editor.getValue();
    }
  }
  BeanFactory context=loadContext(resource,key);
  Context answer=(Context)context.getBean("jndi");
  if (answer == null) {
    log.warn("No JNDI context available in JNDI resource: " + resource);
    answer=new DefaultContext(environment,new ConcurrentHashMap());
  }
  return answer;
}
 

Example 45

From project grails-data-mapping, under directory /grails-datastore-gemfire/src/main/groovy/org/grails/datastore/mapping/gemfire/.

Source file: GemfireDatastore.java

  20 
vote

public void afterPropertiesSet() throws Exception {
  CacheFactoryBean cacheFactory=new CacheFactoryBean();
  if (connectionDetails != null) {
    if (connectionDetails.containsKey(SETTING_CACHE_XML)) {
      Object entry=connectionDetails.remove(SETTING_CACHE_XML);
      if (entry instanceof Resource) {
        cacheFactory.setCacheXml((Resource)entry);
      }
 else {
        cacheFactory.setCacheXml(new ClassPathResource(entry.toString()));
      }
    }
    if (connectionDetails.containsKey(SETTING_PROPERTIES)) {
      Object entry=connectionDetails.get(SETTING_PROPERTIES);
      if (entry instanceof Properties) {
        cacheFactory.setProperties((Properties)entry);
      }
 else       if (entry instanceof Map) {
        final Properties props=new Properties();
        props.putAll((Map)entry);
        cacheFactory.setProperties(props);
      }
    }
  }
  try {
    if (gemfireCache == null) {
      cacheFactory.afterPropertiesSet();
      gemfireCache=cacheFactory.getObject();
    }
    initializeRegions(gemfireCache,mappingContext);
    initializeConverters(mappingContext);
  }
 catch (  Exception e) {
    throw new DatastoreConfigurationException("Failed to configure Gemfire cache and regions: " + e.getMessage(),e);
  }
}
 

Example 46

From project james, under directory /container-spring/src/main/java/org/apache/james/container/spring/resource/.

Source file: AbstractJamesResourceLoader.java

  20 
vote

/** 
 * Return the  {@link Resource} for the given url. If the resource can not befound null get returned
 * @see org.springframework.core.io.ResourceLoader#getResource(java.lang.String)
 */
public Resource getResource(String fileURL){
  Resource r=null;
  if (fileURL.startsWith(FileSystem.CLASSPATH_PROTOCOL)) {
    String resourceName=fileURL.substring(FileSystem.CLASSPATH_PROTOCOL.length());
    r=new ClassPathResource(resourceName);
  }
 else   if (fileURL.startsWith(FileSystem.FILE_PROTOCOL)) {
    File file=null;
    if (fileURL.startsWith(FileSystem.FILE_PROTOCOL_AND_CONF)) {
      file=new File(getConfDirectory() + "/" + fileURL.substring(FileSystem.FILE_PROTOCOL_AND_CONF.length()));
    }
 else     if (fileURL.startsWith(FileSystem.FILE_PROTOCOL_AND_VAR)) {
      file=new File(getVarDirectory() + "/" + fileURL.substring(FileSystem.FILE_PROTOCOL_AND_VAR.length()));
    }
 else     if (fileURL.startsWith(FileSystem.FILE_PROTOCOL_ABSOLUTE)) {
      file=new File(getAbsoluteDirectory() + fileURL.substring(FileSystem.FILE_PROTOCOL_ABSOLUTE.length()));
    }
 else {
      file=new File(getRootDirectory() + "/" + fileURL.substring(FileSystem.FILE_PROTOCOL.length()));
    }
    r=new FileSystemResource(file);
  }
 else {
    return null;
  }
  return r;
}
 

Example 47

From project lor-jamwiki, under directory /jamwiki-core/src/main/java/org/jamwiki/utils/.

Source file: Utilities.java

  20 
vote

/** 
 * Given a file name for a file that is located somewhere in the application classpath, return a File object representing the file.
 * @param filename The name of the file (relative to the classpath) that isto be retrieved.
 * @return A file object representing the requested filename.  Note that thefile name is not guaranteed to match the filename passed to this method since (for example) the file might be found in a JAR file and thus will need to be copied to a temporary location for reading.
 * @throws IOException Thrown if the classloader can not be found or ifthe file can not be found in the classpath.
 */
public static File getClassLoaderFile(String filename) throws IOException {
  Resource resource=new ClassPathResource(filename);
  try {
    return resource.getFile();
  }
 catch (  IOException e) {
  }
  InputStream is=null;
  FileOutputStream os=null;
  try {
    String tempFilename=RandomStringUtils.randomAlphanumeric(20);
    File file=File.createTempFile(tempFilename,null);
    is=resource.getInputStream();
    os=new FileOutputStream(file);
    IOUtils.copy(is,os);
    return file;
  }
  finally {
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);
  }
}
 

Example 48

From project OpenMEAP, under directory /server-side/openmeap-shared-serverside/src/com/openmeap/web/servlet/.

Source file: Log4JConfiguratorListener.java

  20 
vote

@Override public void contextInitialized(ServletContextEvent arg0){
  BasicConfigurator.configure();
  ServletContext servletContext=arg0.getServletContext();
  String xmlLoc=servletContext.getInitParameter("openmeap-log4j-xml");
  if (xmlLoc == null) {
    return;
  }
  try {
    Resource res=new ClassPathResource(xmlLoc);
    DOMConfigurator.configure(XmlUtils.getDocument(res.getInputStream()).getDocumentElement());
  }
 catch (  Exception ioe) {
    servletContext.log("The configuration failed.",ioe);
  }
}
 

Example 49

From project RSB, under directory /src/test/java/eu/openanalytics/rsb/component/.

Source file: EmailDepositHandlerTestCase.java

  20 
vote

@Test public void handleJob() throws Exception {
  final MimeMessage mimeMessage=new MimeMessage((Session)null);
  final MimeMessageHelper mmh=new MimeMessageHelper(mimeMessage,true);
  mmh.setReplyTo("[email protected]");
  mmh.setText("test job");
  mmh.addAttachment("r-job-sample.zip",new ClassPathResource("data/r-job-sample.zip"),Constants.ZIP_CONTENT_TYPE);
  final DepositEmailConfiguration depositEmailConfiguration=mock(PersistedDepositEmailConfiguration.class);
  when(depositEmailConfiguration.getApplicationName()).thenReturn(TEST_APPLICATION_NAME);
  final Message<MimeMessage> message=MessageBuilder.withPayload(mimeMessage).setHeader(EmailDepositHandler.EMAIL_CONFIG_HEADER_NAME,depositEmailConfiguration).build();
  emailDepositHandler.handleJob(message);
  final ArgumentCaptor<MultiFilesJob> jobCaptor=ArgumentCaptor.forClass(MultiFilesJob.class);
  verify(messageDispatcher).dispatch(jobCaptor.capture());
  final MultiFilesJob job=jobCaptor.getValue();
  assertThat(job.getApplicationName(),is(TEST_APPLICATION_NAME));
  assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_SUBJECT_META_NAME),is(true));
  assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_ADDRESSEE_META_NAME),is(true));
  assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_REPLY_TO_META_NAME),is(true));
  assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_REPLY_CC_META_NAME),is(true));
  assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_BODY_META_NAME),is(true));
  assertThat(job.getSource(),is(Source.EMAIL));
  job.destroy();
}
 

Example 50

From project servicemix4-features, under directory /camel/servicemix-camel/src/test/java/org/apache/servicemix/camel/nmr/ws/rm/.

Source file: WSRMTest.java

  20 
vote

public void testDecoupled() throws Exception {
  SpringBusFactory bf=new SpringBusFactory();
  bus=bf.createBus("/org/apache/servicemix/camel/ws/rm/decoupled.xml");
  LoggingInInterceptor in=new LoggingInInterceptor();
  bus.getInInterceptors().add(in);
  bus.getInFaultInterceptors().add(in);
  LoggingOutInterceptor out=new LoggingOutInterceptor();
  bus.getOutInterceptors().add(out);
  bus.getOutFaultInterceptors().add(out);
  QName serviceName=new QName("http://cxf.apache.org/greeter_control","GreeterService");
  URL wsdl=new ClassPathResource("/wsdl/greeter_control.wsdl").getURL();
  GreeterService gs=new GreeterService(wsdl,serviceName);
  final Greeter greeter=gs.getGreeterPort();
  LOG.fine("Created greeter client.");
  ConnectionHelper.setKeepAliveConnection(greeter,true);
  TwowayThread t=new TwowayThread(greeter);
  t.start();
  long wait=3000;
  while (wait > 0) {
    long start=System.currentTimeMillis();
    try {
      Thread.sleep(wait);
    }
 catch (    InterruptedException ex) {
    }
    wait-=System.currentTimeMillis() - start;
  }
  greeter.greetMeOneWay("oneway");
  t.join();
  assertEquals("Unexpected response to twoway request","oneway",t.getResponse());
}
 

Example 51

From project chargifyService, under directory /src/main/java/com/mondora/chargify/controller/.

Source file: Chargify.java

  19 
vote

protected DefaultHttpClient createHttpClient(){
  if (beanFactory == null) {
    beanFactory=new XmlBeanFactory(new ClassPathResource("sense-context.xml"));
  }
  return (DefaultHttpClient)beanFactory.getBean("httpClient",DefaultHttpClient.class);
}
 

Example 52

From project flip, under directory /spring/src/main/java/com/tacitknowledge/flip/spring/config/.

Source file: InterceptHandlerParser.java

  19 
vote

@Override protected AbstractBeanDefinition parseInternal(Element element,ParserContext parserContext){
  XmlBeanFactory factory=new XmlBeanFactory(new ClassPathResource("com/tacitknowledge/flip/spring/context.xml"));
  BeanDefinitionBuilder beanBuilder=BeanDefinitionBuilder.rootBeanDefinition(FlipSpringAspect.class);
  String defaultUrlValue=element.getAttribute("default-url");
  MutablePropertyValues propertyValues=new MutablePropertyValues();
  propertyValues.addPropertyValue("defaultValue",defaultUrlValue);
  propertyValues.addPropertyValue(FlipSpringAspect.FEATURE_SERVICE_BEAN_NAME,new RuntimeBeanReference(FlipSpringAspect.FEATURE_SERVICE_BEAN_NAME));
  beanBuilder.getRawBeanDefinition().setPropertyValues(propertyValues);
  for (  String name : factory.getBeanDefinitionNames()) {
    parserContext.getRegistry().registerBeanDefinition(name,factory.getBeanDefinition(name));
  }
  parserContext.getRegistry().registerBeanDefinition(FlipSpringAspect.ASPECT_BEAN_NAME,beanBuilder.getBeanDefinition());
  return null;
}
 

Example 53

From project Kundera-Examples, under directory /src/test/java/com/impetus/kundera/examples/spring/.

Source file: SpringExampleDaoTest.java

  19 
vote

/** 
 * @throws java.lang.Exception
 */
@Before public void setUp() throws Exception {
  CassandraCli.cassandraSetUp();
  CassandraCli.createKeySpace("KunderaExamples");
  CassandraCli.columnFamilyExist("SIMPLE_COMMENT","KunderaExamples");
  XmlBeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
  dao=(SpringExampleDao)beanFactory.getBean("springExampleDao");
}
 

Example 54

From project spring-data-neo4j, under directory /spring-data-neo4j-examples/imdb/src/main/java/org/neo4j/examples/imdb/parser/.

Source file: ImdbParser.java

  19 
vote

/** 
 * Get file reader that corresponds to file extension.
 * @param file      the file name
 * @param pattern   TODO
 * @param skipLines TODO
 * @return a file reader that uncompresses data if needed
 * @throws IOException
 * @throws FileNotFoundException
 */
private BufferedReader getFileReader(final String file,String pattern,int skipLines) throws IOException, FileNotFoundException {
  BufferedReader fileReader;
  if (file.endsWith(".gz")) {
    fileReader=new BufferedReader(new InputStreamReader(new GZIPInputStream(new ClassPathResource(file).getInputStream())));
  }
 else   if (file.endsWith(".zip")) {
    fileReader=new BufferedReader(new InputStreamReader(new ZipInputStream(new ClassPathResource(file).getInputStream())));
  }
 else {
    fileReader=new BufferedReader(new FileReader(file));
  }
  String line="";
  while (!pattern.equals(line)) {
    line=fileReader.readLine();
  }
  for (int i=0; i < skipLines; i++) {
    line=fileReader.readLine();
  }
  return fileReader;
}