Example usage for org.springframework.context.support GenericApplicationContext getBean

List of usage examples for org.springframework.context.support GenericApplicationContext getBean

Introduction

In this page you can find the example usage for org.springframework.context.support GenericApplicationContext getBean.

Prototype

@Override
    public Object getBean(String name) throws BeansException 

Source Link

Usage

From source file:org.openplans.delayfeeder.LoadFeeds.java

public static void main(String args[]) throws HibernateException, IOException {
    if (args.length != 1) {
        System.out.println("expected one argument: the path to a csv of agency,route,url");
    }/*from   w w w  . j a v  a 2 s .co m*/
    GenericApplicationContext context = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
    xmlReader.loadBeanDefinitions("org/openplans/delayfeeder/application-context.xml");
    xmlReader.loadBeanDefinitions("data-sources.xml");

    SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");

    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.beginTransaction();

    FileReader fileReader = new FileReader(new File(args[0]));
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    while (bufferedReader.ready()) {
        String line = bufferedReader.readLine().trim();
        if (line.startsWith("#")) {
            continue;
        }
        if (line.length() < 3) {
            //blank or otherwise broken line
            continue;
        }

        String[] parts = line.split(",");
        String agency = parts[0];
        String route = parts[1];
        String url = parts[2];
        Query query = session.createQuery("from RouteFeed where agency = :agency and route = :route");
        query.setParameter("agency", agency);
        query.setParameter("route", route);
        @SuppressWarnings("rawtypes")
        List list = query.list();
        RouteFeed feed;
        if (list.size() == 0) {
            feed = new RouteFeed();
            feed.agency = agency;
            feed.route = route;
            feed.lastEntry = new GregorianCalendar();
        } else {
            feed = (RouteFeed) list.get(0);
        }
        if (!url.equals(feed.url)) {
            feed.url = url;
            feed.lastEntry.setTimeInMillis(0);
        }
        session.saveOrUpdate(feed);
    }
    tx.commit();
}

From source file:org.transitappliance.loader.LoaderFrontEnd.java

/**
 * The main CLI of the program. Just loads the config file and spins up Spring.
 * @param args The command line arguments. Uses varargs so this can be called from a script
 *///w  w w  . j av a2s.  c om
public static void main(String... args) {
    // benchmarking
    long startTime = System.currentTimeMillis();
    long totalTime;

    // Modeled after the main method in OTP Graph Builder

    // arg checking
    if (args.length == 0) {
        System.out.println("usage: loader config.xml");
        System.exit(1);
    }

    System.out.println("Transit Appliance Stop Loader");

    // Load Spring
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ctx);

    // Load config file for this agency and database adapter
    for (String file : args)
        reader.loadBeanDefinitions(new FileSystemResource(file));

    // get the loader, config'd for this agency
    TransitStopLoader loader = (TransitStopLoader) ctx.getBean("transitStopLoader");

    loader.loadStops();
}

From source file:org.mzd.shap.spring.cli.ConfigSetup.java

public static void main(String[] args) {
    // check args
    if (args.length != 1) {
        exitOnError(1, null);//from  w ww  . ja va  2 s  .  com
    }

    // check file existance
    File analyzerXML = new File(args[0]);
    if (!analyzerXML.exists()) {
        exitOnError(1, "'" + analyzerXML.getPath() + "' did not exist\n");
    }

    // prompt user whether existing data should be purged
    boolean isPurged = false;
    String ormContext = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    try {
        System.out.println("\nDo you wish to purge the database before running setup?");
        System.out.println("WARNING: all existing data in SHAP will be lost!");
        System.out.println("Really purge? yes/[NO]");
        String ans = br.readLine();
        if (ans.toLowerCase().equals("yes")) {
            System.out.println("Purging enabled");
            ormContext = "orm-purge-context.xml";
            isPurged = true;
        } else {
            System.out.println("Purging disabled");
            ormContext = "orm-context.xml";
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    // run tool
    try {
        // Using a generic application context since we're referencing
        // both classpath and filesystem resources.
        GenericApplicationContext ctx = new GenericApplicationContext();
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
        xmlReader.loadBeanDefinitions(new ClassPathResource("datasource-context.xml"),
                new ClassPathResource(ormContext), new FileSystemResource(analyzerXML));
        ctx.refresh();

        /*
         * Create an base admin user.
         */
        if (isPurged) {
            //only attempted if we've wiped the old database.
            RoleDao roleDao = (RoleDao) ctx.getBean("roleDao");
            Role adminRole = roleDao.saveOrUpdate(new Role("admin", "ROLE_ADMIN"));
            Role userRole = roleDao.saveOrUpdate(new Role("user", "ROLE_USER"));
            UserDao userDao = (UserDao) ctx.getBean("userDao");
            userDao.saveOrUpdate(new User("admin", "admin", "shap01", adminRole, userRole));
        }

        /*
         * Create some predefined analyzers. Users should have modified
         * the configuration file to suit their environment.
         */
        AnnotatorDao annotatorDao = (AnnotatorDao) ctx.getBean("annotatorDao");
        DetectorDao detectorDao = (DetectorDao) ctx.getBean("detectorDao");

        ConfigSetup config = (ConfigSetup) ctx.getBean("configuration");

        for (Annotator an : config.getAnnotators()) {
            System.out.println("Adding annotator: " + an.getName());
            annotatorDao.saveOrUpdate(an);
        }

        for (Detector dt : config.getDetectors()) {
            System.out.println("Adding detector: " + dt.getName());
            detectorDao.saveOrUpdate(dt);
        }

        System.exit(0);
    } catch (Throwable t) {
        System.err.println(t.getMessage());
        System.exit(1);
    }
}

From source file:com.wavemaker.commons.util.SpringUtils.java

public static Object getBean(Resource resource, String beanName) {
    GenericApplicationContext ctx = initSpringConfig(false);
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(resource);
    ctx.refresh();//from   w  ww.  ja v  a  2  s.c  o m
    return ctx.getBean(beanName);
}

From source file:edu.internet2.middleware.psp.shibboleth.AllGroupNamesDataConnectorTest.java

/**
 * Test ignore principal names except for {@link BulkProvisioningRequest.BULK_REQUEST_ID}.
 *///from   ww  w . j a  va  2 s . c  o m
public void testIgnorePrincipalName() {

    try {
        GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
        AllGroupNamesDataConnector gdc = (AllGroupNamesDataConnector) gContext.getBean("testGetAllIdentifiers");
        AttributeMap currentMap = new AttributeMap(gdc.resolve(getShibContext("principalName")));

        assertTrue(currentMap.getMap().isEmpty());

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:edu.internet2.middleware.psp.shibboleth.AllGroupNamesDataConnectorTest.java

/**
 * Test get all identifiers.//from   w w w .j  a  v  a2  s . c  o  m
 */
public void testGetAllIdentifiers() {

    try {
        GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
        AllGroupNamesDataConnector gdc = (AllGroupNamesDataConnector) gContext.getBean("testGetAllIdentifiers");
        AttributeMap currentMap = new AttributeMap(
                gdc.resolve(getShibContext(BulkProvisioningRequest.BULK_REQUEST_ID)));

        List<String> values = new ArrayList<String>();
        values.add(groupA.getName());
        values.add(groupB.getName());
        values.add(groupC.getName());

        AttributeMap correctMap = new AttributeMap();
        correctMap.setAttribute(AllGroupNamesDataConnector.ALL_IDENTIFIERS_ATTRIBUTE_ID,
                values.toArray(new String[] {}));

        assertEquals(correctMap, currentMap);

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:edu.internet2.middleware.psp.shibboleth.AllStemNamesDataConnectorTest.java

/**
 * Test ignore principal names except for {@link BulkProvisioningRequest.BULK_REQUEST_ID}.
 *///from   w  w w . jav  a 2s.co m
public void testIgnorePrincipalName() {

    try {
        GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
        AllStemNamesDataConnector sdc = (AllStemNamesDataConnector) gContext.getBean("testAll");
        AttributeMap currentMap = new AttributeMap(sdc.resolve(getShibContext("principalName")));

        assertTrue(currentMap.getMap().isEmpty());

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:edu.internet2.middleware.psp.shibboleth.AllStemNamesDataConnectorTest.java

/**
 * Test get all identifiers.//  ww w .j a  v a  2  s .c om
 */
public void testGetAllIdentifiers() {

    try {
        GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
        AllStemNamesDataConnector sdc = (AllStemNamesDataConnector) gContext.getBean("testAll");
        AttributeMap currentMap = new AttributeMap(
                sdc.resolve(getShibContext(BulkProvisioningRequest.BULK_REQUEST_ID)));

        Stem etc = StemFinder.findByName(grouperSession, "etc", true);

        Set<Stem> etcChildStems = etc.getChildStems(Scope.SUB);

        List<String> values = new ArrayList<String>();
        values.add(parentStem.getName());
        values.add(childStem.getName());

        for (Stem stem : etcChildStems) {
            values.add(stem.getName());
        }

        values.add(etc.getName());

        AttributeMap correctMap = new AttributeMap();
        correctMap.setAttribute(AllStemNamesDataConnector.ALL_IDENTIFIERS_ATTRIBUTE_ID,
                values.toArray(new String[] {}));
        assertEquals(correctMap, currentMap);

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:edu.internet2.middleware.psp.shibboleth.AllMemberSubjectIdsDataConnectorTest.java

/**
 * Test ignore principal names except for {@link BulkProvisioningRequest.BULK_REQUEST_ID}.
 *//*ww  w.jav a 2 s .co m*/
public void testIgnorePrincipalName() {

    try {
        GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
        AllMemberSubjectIdsDataConnector mdc = (AllMemberSubjectIdsDataConnector) gContext
                .getBean("testIdOnly");
        AttributeMap currentMap = new AttributeMap(mdc.resolve(getShibContext("principalName")));

        assertTrue(currentMap.getMap().isEmpty());

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:edu.internet2.middleware.psp.shibboleth.AllMemberSubjectIdsDataConnectorTest.java

public void testMemberSourceFilter() {
    try {/*from   w  w w  . j ava2s  .c  o m*/
        GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
        AllMemberSubjectIdsDataConnector mdc = (AllMemberSubjectIdsDataConnector) gContext
                .getBean("testIdOnly");

        AttributeMap currentMap = new AttributeMap(
                mdc.resolve(getShibContext(BulkProvisioningRequest.BULK_REQUEST_ID)));

        List<String> values = new ArrayList<String>();
        values.add(SubjectTestHelper.SUBJ0_ID);
        values.add(SubjectTestHelper.SUBJ1_ID);
        values.add(SubjectTestHelper.SUBJ2_ID);
        values.add(SubjectTestHelper.SUBJ3_ID);

        AttributeMap correctMap = new AttributeMap();
        correctMap.setAttribute(AllMemberSubjectIdsDataConnector.ALL_IDENTIFIERS_ATTRIBUTE_ID,
                values.toArray(new String[] {}));

        assertEquals(correctMap, currentMap);

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}