Java Code Examples for org.springframework.context.ApplicationContext

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 org.ops4j.pax.wicket, under directory /test/src/main/java/org/ops4j/pax/wicket/test/spring/.

Source file: PaxWicketSpringBeanComponentInjector.java

  39 
vote

public Object locateProxyTarget(){
  ApplicationContext appContext=Application.get().getMetaData(CONTEXT_KEY);
  if (beanName.equals("")) {
    return appContext.getBean(type);
  }
 else {
    return appContext.getBean(beanName);
  }
}
 

Example 2

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/listener/.

Source file: StartupListener.java

  35 
vote

/** 
 * This method uses the LookupManager to lookup available roles from the data layer.
 * @param context The servlet context
 */
public static void setupContext(final ServletContext context){
  final ApplicationContext ctx=WebApplicationContextUtils.getRequiredWebApplicationContext(context);
  final LookupManager mgr=(LookupManager)ctx.getBean("lookupManager");
  context.setAttribute(Constants.AVAILABLE_ROLES,mgr.getAllRoles());
  StartupListener.log.debug("Drop-down initialization complete [OK]");
  final CompassGps compassGps=ctx.getBean(CompassGps.class);
  compassGps.index();
}
 

Example 3

From project ajah, under directory /ajah-spring-mvc/src/main/java/com/ajah/spring/mvc/servlet/tag/.

Source file: SpringTag.java

  33 
vote

protected String getMessage(final MessageSourceResolvable resolvable){
  final ApplicationContext appContext=(ApplicationContext)this.pageContext.getServletContext().getAttribute("appContext");
  final MessageSource messageSource=appContext.getBean(MessageSource.class);
  if (log.isLoggable(Level.FINEST)) {
    log.finest(StringUtils.join(resolvable.getCodes()));
  }
  return messageSource.getMessage(resolvable,Locale.getDefault());
}
 

Example 4

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

Source file: SpringSyntaxTreeExamplesSupplier.java

  32 
vote

@Override public List<PotentialAssignment> getValueSources(ParameterSignature signature){
  SpringSyntaxTreeExamples annotation=signature.getAnnotation(SpringSyntaxTreeExamples.class);
  ApplicationContext ctx=new ClassPathXmlApplicationContext(annotation.contextLocation());
  @SuppressWarnings("unchecked") Map<String,String> exampleMap=(Map<String,String>)ctx.getBean(annotation.exampleMap());
  List<PotentialAssignment> examples=new ArrayList<PotentialAssignment>();
  for (  Entry<String,String> exampleEntry : exampleMap.entrySet()) {
    SyntaxTreeExample example=new SyntaxTreeExample();
    example.setQuery(exampleEntry.getKey());
    example.setSyntaxTree(exampleEntry.getValue().trim());
    examples.add(example);
  }
  return examples;
}
 

Example 5

From project arquillian-extension-spring, under directory /arquillian-service-integration-spring/src/main/java/org/jboss/arquillian/spring/integration/enricher/.

Source file: AbstractSpringInjectionEnricher.java

  32 
vote

/** 
 * <p>Injects beans into the tests case.</p>
 * @param testCase the test case
 */
private void injectClass(Object testCase){
  ApplicationContext applicationContext=getApplicationContext();
  if (applicationContext != null) {
    log.fine("Injecting dependencies into test case: " + testCase.getClass().getName());
    injectDependencies(applicationContext,testCase);
  }
}
 

Example 6

From project ATHENA, under directory /components/payments/src/test/java/org/fracturedatlas/athena/payments/web/resource/.

Source file: BasePaymentsTest.java

  32 
vote

public BasePaymentsTest(){
  super(new WebAppDescriptor.Builder("org.fracturedatlas.athena.web.resource").contextPath("payments").contextParam("contextConfigLocation","classpath:testApplicationContext.xml").servletClass(SpringServlet.class).contextListenerClass(ContextLoaderListener.class).contextParam("javax.ws.rs.Application","org.fracturedatlas.athena.payments.web.config.PaymentsConfig").build());
  ClientConfig cc=new DefaultClientConfig();
  Client c=Client.create(cc);
  webResource=c.resource(BASE_URI);
  webResource.addFilter(new LoggingFilter());
  payments=new AthenaPayments(webResource);
  ApplicationContext context=new ClassPathXmlApplicationContext("testApplicationContext.xml");
}
 

Example 7

From project banshun, under directory /banshun/core/src/test/java/com/griddynamics/banshun/analyzer/.

Source file: ContextAnalyzerTest.java

  32 
vote

/** 
 * This test checks whether the exceptions will happen during instantiation of cont
 */
@Test public void testNested(){
  ApplicationContext context=new ClassPathXmlApplicationContext("com/griddynamics/banshun/analyzer/root-context.xml");
  Registry registry=(Registry)context.getBean("root");
  SuperInterface first=registry.lookup("firstObject",SuperInterface.class);
  SubInterface second=registry.lookup("secondObject",SubInterface.class);
  assertNotNull(first);
  assertNotNull(second);
}
 

Example 8

From project catalog-api-client, under directory /client/src/main/java/com/shopzilla/api/driver/.

Source file: ProductClientDriver.java

  32 
vote

public static void main(String[] args){
  ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:applicationContext-client.xml");
  ProductClient client=applicationContext.getBean("productClient",ProductClient.class);
  credentialFactory=applicationContext.getBean("credentialFactory",CredentialFactory.class);
  apiKey=credentialFactory.getPublisherApiKey();
  publisherId=credentialFactory.getPublisherId();
  client.doProductSearch(apiKey,publisherId,keyword,10);
}
 

Example 9

From project constretto-core, under directory /constretto-spring/src/test/java/org/constretto/spring/assembly/.

Source file: AssemblyWithConcreteClassesTest.java

  32 
vote

@Test public void injectionUsingConstrettoWithEnvironmentSetAndUsinginterface(){
class MyConsumer {
    @Autowired CommonInterface commonInterface;
  }
  setProperty(ASSEMBLY_KEY,"stub");
  ApplicationContext ctx=loadContextAndInjectWithConstretto();
  MyConsumer consumer=new MyConsumer();
  ctx.getAutowireCapableBeanFactory().autowireBean(consumer);
  Assert.assertEquals(consumer.commonInterface.getClass(),CommonInterfaceStub.class);
}
 

Example 10

From project drools-mas, under directory /drools-mas-agent-web-archetype/src/main/resources/archetype-resources/src/test/java/.

Source file: KnowledgeResourcesCompilationTest.java

  32 
vote

@Test public void compilationTest(){
  ApplicationContext context=new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
  DroolsAgent agent=(DroolsAgent)context.getBean("agent");
  assertNotNull(agent);
  agent.dispose();
}
 

Example 11

From project entando-core-engine, under directory /src/test/java/com/agiletec/aps/.

Source file: BaseTestCase.java

  32 
vote

@Override protected void setUp() throws Exception {
  try {
    super.setUp();
    ServletContext srvCtx=new MockServletContext("",new FileSystemResourceLoader());
    ApplicationContext applicationContext=this.getConfigUtils().createApplicationContext(srvCtx);
    this.setApplicationContext(applicationContext);
    RequestContext reqCtx=this.createRequestContext(applicationContext,srvCtx);
    this.setRequestContext(reqCtx);
    this.setUserOnSession("guest");
  }
 catch (  Exception e) {
    throw e;
  }
}
 

Example 12

From project Gemini-Blueprint, under directory /integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/ns/.

Source file: NamespaceProviderAndConsumerTest.java

  32 
vote

public void testNSBundlePublishedOkay() throws Exception {
  ServiceReference ref=OsgiServiceReferenceUtils.getServiceReference(bundleContext,ApplicationContext.class.getName(),"(" + Constants.BUNDLE_SYMBOLICNAME + "="+ BND_SYM_NAME+ ")");
  assertNotNull(ref);
  ApplicationContext ctx=(ApplicationContext)bundleContext.getService(ref);
  assertNotNull(ctx);
  assertNotNull(ctx.getBean("nsBean"));
  assertNotNull(ctx.getBean("nsDate"));
}
 

Example 13

From project GNDMS, under directory /infra/src/de/zib/gndms/infra/system/.

Source file: PluginLoader.java

  32 
vote

public static void main(String[] args) throws Exception {
  if (args.length != 1) {
    System.out.println("java " + PluginLoader.class.getName() + " <plugin-dir>");
    System.exit(1);
  }
  ApplicationContext context=new ClassPathXmlApplicationContext("classpath:META-INF/00_system.xml");
  PluginLoader pl=new PluginLoader(args[0]);
  ClassLoader cl=pl.loadPlugins();
  PluggableTaskFlowProvider provider=(PluggableTaskFlowProvider)context.getAutowireCapableBeanFactory().getBean("taskFlowProvider");
  provider.setCl(cl);
  provider.loadPlugins();
  provider.listPlugins();
  System.exit(0);
}
 

Example 14

From project hdiv, under directory /hdiv-config/src/test/java/org/hdiv/config/xml/.

Source file: CustomSchemaTest.java

  32 
vote

public void testSchema(){
  ApplicationContext context=new ClassPathXmlApplicationContext("org/hdiv/config/xml/hdiv-config-test-schema.xml");
  Validation validation=(Validation)context.getBean("id1");
  assertNotNull(validation);
  System.out.println(validation.toString());
  System.out.println("-----------------------");
  HDIVConfig hdivConfig=(HDIVConfig)context.getBean("config");
  assertNotNull(hdivConfig);
  System.out.println(hdivConfig.toString());
  System.out.println("-----------------------");
  HDIVValidations validations=(HDIVValidations)context.getBean("editableParametersValidations");
  assertNotNull(validations);
  System.out.println(validations.toString());
}
 

Example 15

From project jagger, under directory /chassis/core/src/test/java/com/griddynamics/jagger/util/.

Source file: PropertiesResolverTest.java

  32 
vote

@Test public void testPropertiesResolver() throws MalformedURLException {
  ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"spring/test-properties-resolver.xml"});
  Assert.assertEquals(context.getBean("stringA"),"x-override");
  Assert.assertEquals(context.getBean("stringB"),"x-override/ex");
  Assert.assertEquals(context.getBean("stringC"),"x-override/y-default/ex");
  Assert.assertEquals(context.getBean("stringD"),"x-override+y-default");
}
 

Example 16

From project jAPS2, under directory /src/test/com/agiletec/aps/.

Source file: BaseTestCase.java

  32 
vote

@Override protected void setUp() throws Exception {
  try {
    super.setUp();
    ServletContext srvCtx=new MockServletContext("",new FileSystemResourceLoader());
    ApplicationContext applicationContext=this.getConfigUtils().createApplicationContext(srvCtx);
    this.setApplicationContext(applicationContext);
    RequestContext reqCtx=this.createRequestContext(applicationContext,srvCtx);
    this.setRequestContext(reqCtx);
    this.setUserOnSession("guest");
  }
 catch (  Exception e) {
    throw e;
  }
}
 

Example 17

From project java-maven-tests, under directory /src/hdb-demo/src/main/java/com/truward/hdbdemo/.

Source file: App.java

  32 
vote

public static void main(String[] args){
  System.out.println("HDB app");
  final ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"application-context.xml"});
  printSampleProfiles((Service)context.getBean("service"));
  try {
    if (args.length > 10) {
      SimpleHsqlAccessor.playWithHsqldb1();
    }
    SimpleHsqlAccessor.playWithHsqldb2(context);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 18

From project lenya, under directory /org.apache.lenya.core.ac/src/main/java/org/apache/lenya/ac/impl/.

Source file: DefaultAccessController.java

  32 
vote

/** 
 * Creates the accreditable manager.
 * @param configuration The access controller configuration.
 * @throws ConfigurationException when the configuration failed.
 * @throws ServiceException when something went wrong.
 * @throws ParameterException when something went wrong.
 */
protected void setupAccreditableManager(Configuration configuration) throws ConfigurationException, ServiceException, ParameterException {
  Configuration config=configuration.getChild(ACCREDITABLE_MANAGER_ELEMENT,false);
  if (config != null) {
    ApplicationContext context=WebAppContextUtils.getCurrentWebApplicationContext();
    AccreditableManagerFactory factory=(AccreditableManagerFactory)context.getBean(AccreditableManagerFactory.ROLE);
    this.accreditableManager=factory.getAccreditableManager(config);
    this.accreditableManager.addItemManagerListener(this);
  }
}
 

Example 19

From project lilith, under directory /tracing/src/test/java/de/huxhorn/lilith/tracing/.

Source file: TracingAspectTest.java

  32 
vote

@Test public void defaultTracing(){
  ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"defaultTracing.xml"});
  TracingAspect tracingAspect=(TracingAspect)context.getBean("tracingAspect");
  if (logger.isInfoEnabled())   logger.info("Using tracingAspect {}",tracingAspect);
  ExampleServiceIfc exampleService=(ExampleServiceIfc)context.getBean("exampleService");
  callExampleService(exampleService);
}
 

Example 20

From project OpenReports, under directory /src/org/efs/openreports/dispatcher/.

Source file: FileDispatcher.java

  32 
vote

public void init(ServletConfig servletConfig) throws ServletException {
  ApplicationContext appContext=WebApplicationContextUtils.getRequiredWebApplicationContext(servletConfig.getServletContext());
  directoryProvider=(DirectoryProvider)appContext.getBean("directoryProvider",DirectoryProvider.class);
  imageDirectory=directoryProvider.getReportImageDirectory();
  imageTempDirectory=directoryProvider.getTempDirectory();
  reportGenerationDirectory=directoryProvider.getReportGenerationDirectory();
  super.init(servletConfig);
  log.info("Started...");
}
 

Example 21

From project OpenTripPlanner, under directory /opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/.

Source file: GraphBuilderMain.java

  32 
vote

public static void main(String[] args) throws IOException {
  if (args.length == 0) {
    System.err.println("usage: config.xml");
    System.exit(-1);
  }
  List<String> paths=new ArrayList<String>();
  paths.add("classpath:org/opentripplanner/graph_builder/application-context.xml");
  for (  String arg : args)   paths.add(arg);
  ApplicationContext context=createContext(paths,new HashMap<String,BeanDefinition>());
  GraphBuilderTask task=(GraphBuilderTask)context.getBean("graphBuilderTask");
  task.run();
}
 

Example 22

From project org.openscada.atlantis, under directory /org.openscada.da.server.exporter.spring/src/org/openscada/da/server/exporter/spring/.

Source file: SpringHiveFactory.java

  32 
vote

protected ApplicationContext getApplicationContext(final String file){
  ApplicationContext ctx=this.ctxMap.get(file);
  if (ctx == null) {
    ctx=new FileSystemXmlApplicationContext(file);
    this.ctxMap.put(file,ctx);
  }
  return ctx;
}
 

Example 23

From project PortalTests, under directory /core-tests/src/main/java/eu/jasha/portaltests/stories/.

Source file: PortalStories.java

  32 
vote

protected PortalStories(){
  CrossReference crossReference=new CrossReference().withJsonOnly().withOutputAfterEachStory(true).excludingStoriesWithNoExecutedScenarios(true);
  ContextView contextView=new LocalFrameContextView().sized(640,120);
  SeleniumContext seleniumContext=new SeleniumContext();
  SeleniumStepMonitor stepMonitor=new SeleniumStepMonitor(contextView,seleniumContext,crossReference.getStepMonitor());
  Format[] formats=new Format[]{new SeleniumContextOutput(seleniumContext),CONSOLE,WEB_DRIVER_HTML};
  StoryReporterBuilder reporterBuilder=new StoryReporterBuilder().withCodeLocation(codeLocationFromClass(this.getClass())).withFailureTrace(true).withFailureTraceCompression(true).withDefaultFormats().withFormats(formats).withCrossReference(crossReference);
  Configuration configuration=new SeleniumConfiguration().useSeleniumContext(seleniumContext).useFailureStrategy(new FailingUponPendingStep()).useStoryControls(new StoryControls().doResetStateBeforeScenario(false)).useStepMonitor(stepMonitor).useStoryLoader(new LoadFromClasspath(this.getClass())).useStoryReporterBuilder(reporterBuilder);
  useConfiguration(configuration);
  ApplicationContext context=new SpringApplicationContextFactory("applicationContext-tests.xml").createApplicationContext();
  useStepsFactory(new SpringStepsFactory(configuration,context));
}
 

Example 24

From project rave, under directory /rave-integration-tests/rave-core-tests/src/main/java/org/apache/rave/integrationtests/stories/.

Source file: PortalStories.java

  32 
vote

protected PortalStories(){
  CrossReference crossReference=new CrossReference().withJsonOnly().withOutputAfterEachStory(true).excludingStoriesWithNoExecutedScenarios(true);
  ContextView contextView=new LocalFrameContextView().sized(640,120);
  SeleniumContext seleniumContext=new SeleniumContext();
  SeleniumStepMonitor stepMonitor=new SeleniumStepMonitor(contextView,seleniumContext,crossReference.getStepMonitor());
  Format[] formats=new Format[]{new SeleniumContextOutput(seleniumContext),CONSOLE,WEB_DRIVER_HTML};
  StoryReporterBuilder reporterBuilder=new StoryReporterBuilder().withCodeLocation(codeLocationFromClass(this.getClass())).withFailureTrace(true).withFailureTraceCompression(true).withDefaultFormats().withFormats(formats).withCrossReference(crossReference);
  Configuration configuration=new SeleniumConfiguration().useSeleniumContext(seleniumContext).useFailureStrategy(new FailingUponPendingStep()).useStoryControls(new StoryControls().doResetStateBeforeScenario(false)).useStepMonitor(stepMonitor).useStoryLoader(new LoadFromClasspath(this.getClass())).useStoryReporterBuilder(reporterBuilder);
  useConfiguration(configuration);
  ApplicationContext context=new SpringApplicationContextFactory("applicationContext-tests.xml").createApplicationContext();
  useStepsFactory(new SpringStepsFactory(configuration,context));
}
 

Example 25

From project red5-mavenized, under directory /red5_base/src/main/java/org/red5/server/net/rtmp/.

Source file: RTMPConnection.java

  32 
vote

/** 
 * Getter for video codec factory.
 * @return Video codec factory
 */
public VideoCodecFactory getVideoCodecFactory(){
  final IContext context=scope.getContext();
  ApplicationContext appCtx=context.getApplicationContext();
  if (!appCtx.containsBean(VIDEO_CODEC_FACTORY)) {
    return null;
  }
  return (VideoCodecFactory)appCtx.getBean(VIDEO_CODEC_FACTORY);
}
 

Example 26

From project Betfair-Trickle, under directory /src/test/java/uk/co/onehp/trickle/dao/.

Source file: HibernateBetDaoCustomT.java

  31 
vote

@Ignore public static void main(final String[] args){
  final ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:/spring-trickle.xml");
  final BetDao betDao=(BetDao)applicationContext.getBean("betDao");
  final RaceDao raceDao=(RaceDao)applicationContext.getBean("raceDao");
  final Race race=new Race(867,"Race",new LocalDateTime(2012,2,22,19,19,0),"meeting");
  final Horse horse=new Horse();
  horse.setRunnerId(441);
  horse.setRaceId(867);
  horse.setRace(race);
  race.addHorse(horse);
  final Strategy strategy1=new Strategy();
  strategy1.setBetSecondsBeforeStartTime(Lists.newArrayList(120,270,600));
  final Strategy strategy2=new Strategy();
  strategy2.setBetSecondsBeforeStartTime(Lists.newArrayList(120,270,700));
  raceDao.saveOrUpdate(race);
  final Bet bet1=new Bet(horse,strategy1);
  betDao.saveOrUpdate(bet1);
  final Bet bet2=new Bet(horse,strategy2);
  betDao.saveOrUpdate(bet2);
  System.out.println(betDao.getBetsToPlace());
}
 

Example 27

From project Blitz, under directory /src/com/laxser/blitz/.

Source file: BlitzFilter.java

  31 
vote

/** 
 * ?????????? ApplicationContext ????????EB-INF??EB-INF/classes? jar???spring?????????????????????? ApplicationContext ???
 * @return
 * @throws IOException
 */
private WebApplicationContext prepareRootApplicationContext() throws IOException {
  if (logger.isInfoEnabled()) {
    logger.info("[init/rootContext] starting ...");
  }
  ApplicationContext oldRootContext=(ApplicationContext)getServletContext().getAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
  if (oldRootContext != null) {
    if (oldRootContext.getClass() != BlitzWebAppContext.class) {
      throw new IllegalStateException("Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!");
    }
    if (logger.isInfoEnabled()) {
      logger.info("[init/rootContext] the root context exists:" + oldRootContext);
    }
    return (BlitzWebAppContext)oldRootContext;
  }
  BlitzWebAppContext rootContext=new BlitzWebAppContext(getServletContext(),load,false);
  String contextConfigLocation=this.contextConfigLocation;
  if (StringUtils.isBlank(contextConfigLocation)) {
    String webxmlContextConfigLocation=getServletContext().getInitParameter("contextConfigLocation");
    if (StringUtils.isBlank(webxmlContextConfigLocation)) {
      contextConfigLocation=BlitzWebAppContext.DEFAULT_CONFIG_LOCATION;
    }
 else {
      contextConfigLocation=webxmlContextConfigLocation;
    }
  }
  rootContext.setConfigLocation(contextConfigLocation);
  rootContext.setId("Blitz.root");
  rootContext.refresh();
  if (logger.isInfoEnabled()) {
    logger.info("[init/rootContext] exits");
  }
  getServletContext().setAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,rootContext);
  if (logger.isInfoEnabled()) {
    logger.info("[init/rootContext] Published Blitz.root WebApplicationContext [" + rootContext + "] as ServletContext attribute with name ["+ ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE+ "]");
  }
  return rootContext;
}
 

Example 28

From project brix-cms, under directory /brix-rmiserver/src/main/java/org/brixcms/rmiserver/web/dav/.

Source file: WebDavServlet.java

  31 
vote

@Override public void init(ServletConfig config) throws ServletException {
  super.init(config);
  final ServletContext sc=config.getServletContext();
  ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(sc);
  if (context == null) {
    throw new IllegalStateException("Could not find application context");
  }
  repository=(Repository)BeanFactoryUtils.beanOfTypeIncludingAncestors(context,Repository.class);
  if (repository == null) {
    throw new IllegalStateException("Could not find JackRabbit repository in spring context");
  }
  UserService users=(UserService)BeanFactoryUtils.beanOfTypeIncludingAncestors(context,UserService.class);
  if (repository == null) {
    throw new IllegalStateException("Could not find UserService implementation in spring context");
  }
  authorizer=new Authorizer(users);
  credentialsProvider=getCredentialsProvider();
}
 

Example 29

From project Carolina-Digital-Repository, under directory /solr-ingest/src/main/java/edu/unc/lib/dl/data/ingest/solr/.

Source file: UpdateDocTransformer.java

  31 
vote

/** 
 * Initializes the transformer by retrieving the XSLT document to use and building a transformer from it. 
 * @throws Exception
 */
public void init() throws Exception {
  ApplicationContext ctx=new ClassPathXmlApplicationContext();
  Resource res=ctx.getResource("classpath:/transform/" + xslName);
  Source transformSource=new StreamSource(res.getInputStream());
  TransformerFactory factory=TransformerFactory.newInstance();
  factory.setURIResolver(new URIResolver(){
    public Source resolve(    String href,    String base) throws TransformerException {
      Source result=null;
      if (href.startsWith("/"))       result=new StreamSource(UpdateDocTransformer.class.getResourceAsStream(href));
 else       result=new StreamSource(UpdateDocTransformer.class.getResourceAsStream("/transform/" + href));
      return result;
    }
  }
);
  Templates transformTemplate=factory.newTemplates(transformSource);
  transformer=transformTemplate.newTransformer();
}
 

Example 30

From project data-access, under directory /src/org/pentaho/platform/dataaccess/datasource/wizard/service/impl/utils/.

Source file: PentahoSystemHelper.java

  31 
vote

public static void init(){
  if (PentahoSystem.getInitializedOK()) {
    return;
  }
  try {
    PentahoSystem.setSystemSettingsService(new PathBasedSystemSettings());
    if (PentahoSystem.getApplicationContext() == null) {
      StandaloneApplicationContext applicationContext=new StandaloneApplicationContext(getSolutionPath(),"");
      applicationContext.setFullyQualifiedServerURL(getBaseUrl());
      String inContainer=System.getProperty("incontainer","false");
      if (inContainer.equalsIgnoreCase("false")) {
        System.setProperty("java.naming.factory.initial","org.osjava.sj.SimpleContextFactory");
        System.setProperty("org.osjava.sj.root",getSolutionPath() + "/system/simple-jndi");
        System.setProperty("org.osjava.sj.delimiter","/");
      }
      ApplicationContext springApplicationContext=getSpringApplicationContext();
      IPentahoObjectFactory pentahoObjectFactory=new StandaloneSpringPentahoObjectFactory();
      pentahoObjectFactory.init(null,springApplicationContext);
      PentahoSystem.setObjectFactory(pentahoObjectFactory);
      springApplicationContext.getBean("pentahoSystemProxy");
      PentahoSystem.init(applicationContext);
    }
  }
 catch (  Exception e) {
    logger.error(e);
  }
}
 

Example 31

From project logback-extensions, under directory /spring/src/main/java/ch/qos/logback/ext/spring/.

Source file: DelegatingLogbackAppender.java

  31 
vote

private Appender<ILoggingEvent> getDelegate(){
  ApplicationContext context=ApplicationContextHolder.getApplicationContext();
  try {
    @SuppressWarnings("unchecked") Appender<ILoggingEvent> appender=context.getBean(beanName,Appender.class);
    appender.setContext(getContext());
    if (!appender.isStarted()) {
      appender.start();
    }
    return appender;
  }
 catch (  NoSuchBeanDefinitionException e) {
    stop();
    addError("The ApplicationContext does not contain an Appender named [" + beanName + "]. This delegating appender will now stop processing events.",e);
  }
  return null;
}
 

Example 32

From project ManalithBot, under directory /ManalithBotConsole/src/main/java/org/manalith/ircbot/console/.

Source file: Launcher.java

  31 
vote

public static void main(String[] args) throws Exception {
  Options options=new Options();
  options.addOption("c",true,"config file");
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,args);
  String configFile="config.xml";
  String configFileOptionArg=cmd.getOptionValue("c");
  if (StringUtils.isNotBlank(configFileOptionArg)) {
    configFile=configFileOptionArg;
  }
  ApplicationContext context=new FileSystemXmlApplicationContext(configFile);
  UsernamePasswordAuthenticationToken userToken=new UsernamePasswordAuthenticationToken("admin","admin");
  SecurityContextHolder.getContext().setAuthentication(userToken);
  Launcher launcher=context.getBean(Launcher.class);
  ConsoleReader reader=new ConsoleReader();
  String line;
  while (!StringUtils.equals((line=reader.readLine("prompt> ")),"exit")) {
    String[] strs=StringUtils.split(line," ");
    launcher.sendMessage(strs[0],strs[1]);
  }
}
 

Example 33

From project Red5, under directory /src/org/red5/server/api/.

Source file: ScopeUtils.java

  31 
vote

/** 
 * Returns scope services (e.g. SharedObject, etc) for the scope. Method uses either bean name passes as a string or class object.
 * @param scope The scope service belongs to
 * @param name Bean name
 * @param defaultClass Class of service
 * @return				Service object
 */
protected static Object getScopeService(IScope scope,String name,Class<?> defaultClass){
  if (scope == null) {
    return null;
  }
  final IContext context=scope.getContext();
  ApplicationContext appCtx=context.getApplicationContext();
  Object result;
  if (!appCtx.containsBean(name)) {
    if (defaultClass == null) {
      return null;
    }
    try {
      result=defaultClass.newInstance();
    }
 catch (    Exception e) {
      log.error("{}",e);
      return null;
    }
  }
 else {
    result=appCtx.getBean(name);
  }
  return result;
}
 

Example 34

From project red5-server, under directory /src/org/red5/server/api/.

Source file: ScopeUtils.java

  31 
vote

/** 
 * Returns scope services (e.g. SharedObject, etc) for the scope. Method uses either bean name passes as a string or class object.
 * @param scope The scope service belongs to
 * @param name Bean name
 * @param defaultClass Class of service
 * @return				Service object
 */
protected static Object getScopeService(IScope scope,String name,Class<?> defaultClass){
  if (scope == null) {
    return null;
  }
  final IContext context=scope.getContext();
  ApplicationContext appCtx=context.getApplicationContext();
  Object result;
  if (!appCtx.containsBean(name)) {
    if (defaultClass == null) {
      return null;
    }
    try {
      result=defaultClass.newInstance();
    }
 catch (    Exception e) {
      log.error("{}",e);
      return null;
    }
  }
 else {
    result=appCtx.getBean(name);
  }
  return result;
}
 

Example 35

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

Source file: TranslationModule.java

  30 
vote

public TranslationModule(final ApplicationContext applicationContext,final TranslationModuleService translationModuleService,final String pluginIdentifier,final String basename,final String path){
  this.applicationContext=applicationContext;
  this.translationModuleService=translationModuleService;
  this.pluginIdentifier=pluginIdentifier;
  this.basename=basename;
  this.path=path;
}
 

Example 36

From project qi4j-libraries, under directory /spring/src/main/java/org/qi4j/library/spring/bootstrap/internal/application/.

Source file: Qi4jApplicationFactoryBean.java

  30 
vote

public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
  if (this.applicationBootstrap instanceof ApplicationContextAware) {
    ApplicationContextAware aware=(ApplicationContextAware)this.applicationBootstrap;
    aware.setApplicationContext(applicationContext);
  }
}
 

Example 37

From project CalendarPortlet, under directory /src/main/java/org/jasig/portlet/calendar/spring/.

Source file: PortletApplicationContextLocator.java

  29 
vote

/** 
 * If running in a web application the existing  {@link WebApplicationContext} will be returned. ifnot a singleton  {@link ApplicationContext} is created if needed and returned. Unless a {@link WebApplicationContext}is specifically needed this method should be used as it will work both when running in and out of a web application
 * @return The {@link ApplicationContext} for the portal. 
 */
public static ApplicationContext getApplicationContext(String importExportContextFile){
  final ServletContext context=servletContext;
  if (context != null) {
    LOGGER.debug("Using WebApplicationContext");
    if (applicationContextCreator.isCreated()) {
      final IllegalStateException createException=new IllegalStateException("A portal managed ApplicationContext has already been created but now a ServletContext is available and a WebApplicationContext will be returned. " + "This situation should be resolved by delaying calls to this class until after the web-application has completely initialized.");
      LOGGER.error(createException,createException);
      LOGGER.error("Stack trace of original ApplicationContext creator",directCreatorThrowable);
      throw createException;
    }
    final WebApplicationContext webApplicationContext=WebApplicationContextUtils.getWebApplicationContext(context);
    if (webApplicationContext == null) {
      throw new IllegalStateException("ServletContext is available but WebApplicationContextUtils.getWebApplicationContext(ServletContext) returned null. Either the application context failed to load or is not yet done loading.");
    }
    return webApplicationContext;
  }
  return applicationContextCreator.get(importExportContextFile);
}
 

Example 38

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

Source file: OpenIdServiceTests.java

  29 
vote

@Override protected void setUp() throws Exception {
  request.addParameter("openid.identity","http://openid.ja-sig.org/battags");
  request.addParameter("openid.return_to","http://www.ja-sig.org/?service=fa");
  request.addParameter("openid.mode","checkid_setup");
  sharedAssociations=mock(ServerAssociationStore.class);
  manager=new ServerManager();
  manager.setOPEndpointUrl("https://localshot:8443/cas/login");
  manager.setEnforceRpId(false);
  manager.setSharedAssociations(sharedAssociations);
  context=mock(ApplicationContext.class);
  ApplicationContextProvider contextProvider=new ApplicationContextProvider();
  contextProvider.setApplicationContext(context);
  cas=mock(CentralAuthenticationService.class);
}
 

Example 39

From project Dempsy, under directory /lib-dempsyimpl/src/test/java/com/nokia/dempsy/.

Source file: TestDempsy.java

  29 
vote

@Test public void testMpStartMethod() throws Throwable {
  runAllCombinations("SinglestageApplicationActx.xml",new Checker(){
    @Override public void check(    ApplicationContext context) throws Throwable {
      TestAdaptor adaptor=(TestAdaptor)context.getBean("adaptor");
      Object message=new Object();
      Dempsy dempsy=(Dempsy)context.getBean("dempsy");
      TestMp mp=(TestMp)getMp(dempsy,"test-app","test-cluster1");
      assertEquals(1,mp.startCalls.get());
      message=new TestMessage("HereIAm - testMPStartMethod");
      adaptor.pushMessage(message);
      final Object msg=message;
      assertTrue(poll(baseTimeoutMillis,mp,new Condition<TestMp>(){
        @Override public boolean conditionMet(        TestMp mp){
          return msg.equals(mp.lastReceived.get());
        }
      }
));
      assertEquals(1,mp.startCalls.get());
    }
    public String toString(){
      return "testMPStartMethod";
    }
  }
);
}
 

Example 40

From project ehour, under directory /eHour-wicketweb/src/test/java/net/rrm/ehour/ui/common/.

Source file: AbstractSpringInjectorTester.java

  29 
vote

@Before public void springLocatorSetup() throws Exception {
  ISpringContextLocator springContextLocator=new ISpringContextLocator(){
    private static final long serialVersionUID=4009835114662176903L;
    public ApplicationContext getSpringContext(){
      return getMockContext();
    }
  }
;
  InjectorHolder.setInjector(new AnnotSpringInjector(springContextLocator));
}
 

Example 41

From project fiftyfive-wicket, under directory /fiftyfive-wicket-archetype/src/main/resources/archetype-resources/src/test/java/.

Source file: BaseWicketUnitTest.java

  29 
vote

@Before public void createTester(){
  this.tester=new WicketTester(new WicketApplication(){
    @Override public RuntimeConfigurationType getConfigurationType(){
      return RuntimeConfigurationType.DEPLOYMENT;
    }
    @Override protected ApplicationContext getApplicationContext(){
      StaticWebApplicationContext context;
      context=new StaticWebApplicationContext();
      initSpringContext(context);
      return context;
    }
    @Override public WicketSession newSession(    Request request,    Response response){
      if (null == BaseWicketUnitTest.this.session) {
        BaseWicketUnitTest.this.session=super.newSession(request,response);
      }
      return BaseWicketUnitTest.this.session;
    }
  }
);
}
 

Example 42

From project fire-samples, under directory /cache-demo/src/main/java/demo/vmware/commands/.

Source file: CommandRegionUtils.java

  29 
vote

/** 
 * this is an argument for making this a singleton bean instead of static. We cold then make this ApplicationContextAware
 * @param mainContext
 * @param targetRegionName
 * @return
 */
public static GemfireTemplate findTemplateForRegionName(ApplicationContext mainContext,String targetRegionName){
  Map<String,GemfireTemplate> allRegionTemplates=getAllGemfireTemplates(mainContext);
  for (  String key : allRegionTemplates.keySet()) {
    GemfireTemplate oneTemplate=allRegionTemplates.get(key);
    if (oneTemplate.getRegion().getName().equals(targetRegionName)) {
      return oneTemplate;
    }
  }
  throw new IllegalArgumentException("region not found " + targetRegionName);
}
 

Example 43

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

Source file: ClassPathXmlApplicationContext.java

  29 
vote

/** 
 * Creates a ClassPathXmlApplicationContext which loads the configuration at the specified locations on the class path.
 * @param configLocations the locations of the configuration files on the class path
 * @param refresh if true the configurations are immedately loaded; otherwise the configurations are not loadeduntil refresh() is called
 * @param parent the parent of this application context
 * @param xmlPreprocessors the SpringXmlPreprocessors to apply before passing the xml to Spring for processing
 * @throws BeansException if a problem occurs while reading the configuration
 */
public ClassPathXmlApplicationContext(String[] configLocations,boolean refresh,ApplicationContext parent,List xmlPreprocessors) throws BeansException {
  super(configLocations,false,parent);
  this.xmlPreprocessors=xmlPreprocessors;
  if (refresh) {
    refresh();
  }
}
 

Example 44

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

Source file: SearchableCompassFactoryBean.java

  29 
vote

private Compass buildCompass(){
  LOG.debug("Building new Compass");
  CompassConfiguration configuration=CompassConfigurationFactory.newConfiguration();
  Map converters=new HashMap();
  Map context=new HashMap();
  context.put("customConverters",converters);
  Converter converter=new StringMapConverter();
  configuration.registerConverter(StringMapConverter.CONVERTER_NAME,converter);
  converters.put(StringMapConverter.CONVERTER_NAME,converter);
  configuration.getSettings().setSetting("compass.engine.analyzer.searchableplugin_whitespace.type","whitespace");
  configuration.getSettings().setSetting("compass.engine.analyzer.searchableplugin_simple.type","simple");
  configuration.getSettings().setObjectSetting(ApplicationContext.class.getName() + ".INSTANCE",applicationContext);
  searchableCompassConfigurator.configure(configuration,context);
  Compass compass=configuration.buildCompass();
  LOG.debug("Done building Compass");
  return compass;
}
 

Example 45

From project handlebars.java_1, under directory /handlebars-springmvc/src/main/java/com/github/jknack/handlebars/springmvc/.

Source file: HandlebarsViewResolver.java

  29 
vote

/** 
 * Creates a new template loader.
 * @param context The application's context.
 * @return A new template loader.
 */
protected TemplateLoader createTemplateLoader(final ApplicationContext context){
  TemplateLoader templateLoader=new SpringTemplateLoader(context);
  templateLoader.setPrefix(getPrefix());
  templateLoader.setSuffix(getSuffix());
  return templateLoader;
}
 

Example 46

From project heritrix3, under directory /commons/src/main/java/org/archive/spring/.

Source file: ConfigPathConfigurer.java

  29 
vote

/** 
 * Remember ApplicationContext, and if possible primary  configuration file's home directory.  Requires appCtx be a PathSharingContext 
 * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
 */
public void setApplicationContext(ApplicationContext appCtx) throws BeansException {
  this.appCtx=(PathSharingContext)appCtx;
  String basePath;
  if (appCtx instanceof PathSharingContext) {
    basePath=this.appCtx.getConfigurationFile().getParent();
  }
 else {
    basePath=".";
  }
  path=new ConfigPath("job base",basePath);
  path.setConfigurer(this);
}
 

Example 47

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

Source file: AbstractBundleTracker.java

  29 
vote

/** 
 * Return the  {@link BeanFactory} for the given {@link BundleContext}. If none can be found we just create a new  {@link AbstractDelegatedExecutionApplicationContext} and return the {@link BeanFactory} of it
 * @param bundleContext
 * @return factory
 * @throws Exception
 */
private BeanFactory getBeanFactory(final BundleContext bundleContext) throws Exception {
  final String filter="(" + OsgiServicePropertiesResolver.BEAN_NAME_PROPERTY_KEY + "="+ bundleContext.getBundle().getSymbolicName()+ ")";
  final ServiceReference[] applicationContextRefs=bundleContext.getServiceReferences(ApplicationContext.class.getName(),filter);
  if (applicationContextRefs == null || applicationContextRefs.length != 1) {
    AbstractDelegatedExecutionApplicationContext context=new AbstractDelegatedExecutionApplicationContext(){
    }
;
    context.setBundleContext(bundleContext);
    context.setPublishContextAsService(true);
    context.refresh();
    return context.getBeanFactory();
  }
 else {
    return ((ApplicationContext)bundleContext.getService(applicationContextRefs[0])).getAutowireCapableBeanFactory();
  }
}
 

Example 48

From project jdonframework, under directory /doc/chinese/.

Source file: AppContextJdon.java

  29 
vote

/** 
 * ApplicationContextAware's method at first run, startup Jdon Framework 
 */
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  this.applicationContext=applicationContext;
  if (servletContext == null)   if (applicationContext instanceof WebApplicationContext) {
    servletContext=((WebApplicationContext)applicationContext).getServletContext();
    if (servletContext == null) {
      System.err.print("this class only fit for Spring Web Application");
      return;
    }
  }
  AppContextWrapper acw=new ServletContextWrapper(servletContext);
  ContainerFinder containerFinder=new ContainerFinderImp();
  containerWrapper=containerFinder.findContainer(acw);
}
 

Example 49

From project jeppetto, under directory /jeppetto-test-support/src/main/java/org/iternine/jeppetto/testsupport/.

Source file: JdbcDatabaseProvider.java

  29 
vote

@Override public Database getDatabase(Properties properties,ApplicationContext applicationContext){
  ConnectionSource connectionSource=this.getConnectionSource(properties,applicationContext);
  if (connectionSource != null) {
    return DatabaseFactory.getDatabase(connectionSource);
  }
 else {
    return null;
  }
}
 

Example 50

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

Source file: SpringIniWebConfiguration.java

  29 
vote

protected SecurityManager getOrCreateSecurityManager(ApplicationContext appCtx,Map<String,Map<String,String>> sections){
  String beanName=getSecurityManagerBeanName();
  SecurityManager securityManager=null;
  if (beanName != null) {
    securityManager=(SecurityManager)appCtx.getBean(beanName,org.apache.ki.mgt.SecurityManager.class);
  }
  if (securityManager == null) {
    securityManager=getSecurityManagerByType(appCtx);
  }
  if (securityManager == null) {
    securityManager=createDefaultSecurityManagerFromRealms(appCtx,sections);
  }
  if (securityManager == null) {
    String msg="Unable to locate a " + SecurityManager.class.getName() + " instance in the "+ "Spring WebApplicationContext.  You can 1) simply just define the securityManager as a bean ("+ "it will be automatically located based on type) or "+ "2) explicitly specifify which bean is retrieved by setting this filter's "+ "'securityManagerBeanName' init-param or 3) define one or more "+ Realm.class.getName()+ " instances and a default SecurityManager using those realms will be created automatically.";
    throw new ApplicationContextException(msg);
  }
  return securityManager;
}
 

Example 51

From project mapfish-print, under directory /src/main/java/org/mapfish/print/map/readers/.

Source file: MapReaderFactoryFinder.java

  29 
vote

@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  Map<String,MapReaderFactory> tmpFac=applicationContext.getBeansOfType(MapReaderFactory.class);
  for (  Map.Entry<String,MapReaderFactory> entry : tmpFac.entrySet()) {
    if (!entry.getKey().contains("-")) {
      throw new BeanInitializationException("All MapFactoryReaders must have an id with format:  type-MapReaderFactory");
    }
    factories.put(entry.getKey().split("-")[0].toLowerCase(),entry.getValue());
  }
}
 

Example 52

From project mateo, under directory /src/test/java/mx/edu/um/mateo/general/test/.

Source file: GenericWebXmlContextLoader.java

  29 
vote

@Override public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception {
  GenericWebApplicationContext context=new GenericWebApplicationContext();
  context.getEnvironment().setActiveProfiles(mergedConfig.getActiveProfiles());
  prepareContext(context);
  new XmlBeanDefinitionReader(context).loadBeanDefinitions(mergedConfig.getLocations());
  AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
  context.refresh();
  context.registerShutdownHook();
  return context;
}
 

Example 53

From project NewsReaderPortlet, under directory /src/main/java/org/jasig/portlet/newsreader/spring/.

Source file: PortletApplicationContextLocator.java

  29 
vote

/** 
 * If running in a web application the existing  {@link WebApplicationContext} will be returned. ifnot a singleton  {@link ApplicationContext} is created if needed and returned. Unless a {@link WebApplicationContext}is specifically needed this method should be used as it will work both when running in and out of a web application
 * @return The {@link ApplicationContext} for the portal. 
 */
public static ApplicationContext getApplicationContext(String importExportContextFile){
  final ServletContext context=servletContext;
  if (context != null) {
    LOGGER.debug("Using WebApplicationContext");
    if (applicationContextCreator.isCreated()) {
      final IllegalStateException createException=new IllegalStateException("A portal managed ApplicationContext has already been created but now a ServletContext is available and a WebApplicationContext will be returned. " + "This situation should be resolved by delaying calls to this class until after the web-application has completely initialized.");
      LOGGER.error(createException,createException);
      LOGGER.error("Stack trace of original ApplicationContext creator",directCreatorThrowable);
      throw createException;
    }
    final WebApplicationContext webApplicationContext=WebApplicationContextUtils.getWebApplicationContext(context);
    if (webApplicationContext == null) {
      throw new IllegalStateException("ServletContext is available but WebApplicationContextUtils.getWebApplicationContext(ServletContext) returned null. Either the application context failed to load or is not yet done loading.");
    }
    return webApplicationContext;
  }
  return applicationContextCreator.get(importExportContextFile);
}
 

Example 54

From project ohmageServer, under directory /src/org/ohmage/spring/.

Source file: ConfigurationSingletonValidityTester.java

  29 
vote

/** 
 * Performs validation against the ApplicationContext by checking for singleton instances in the package names provided on construction. It  is a bit odd to be performing the validation in a setter method, but the ApplicationContextAware interface specifies a setter and the context cannot be validated without it.
 */
public void setApplicationContext(ApplicationContext applicationContext){
  validate(applicationContext);
  classNames.clear();
  classNames=null;
  if (classesToIgnore != null) {
    classesToIgnore.clear();
    classesToIgnore=null;
  }
  logger=null;
}
 

Example 55

From project openengsb-framework, under directory /ports/ws/src/main/java/org/openengsb/ports/ws/.

Source file: WSIncomingPort.java

  29 
vote

private ApplicationContext createSpringCxfContext(){
  OsgiBundleXmlApplicationContext ctx=new OsgiBundleXmlApplicationContext(CXF_CONFIG);
  ctx.setPublishContextAsService(false);
  ctx.setBundleContext(bundleContext);
  ctx.refresh();
  return ctx;
}
 

Example 56

From project portal, under directory /portal-core/src/main/java/org/devproof/portal/core/app/.

Source file: PortalRequestCycleProcessor.java

  29 
vote

public PortalRequestCycleProcessor(ApplicationContext context){
  configurationService=(ConfigurationService)context.getBean("configurationService");
  userService=(UserService)context.getBean("userService");
  emailService=(EmailService)context.getBean("emailService");
  mountService=(MountService)context.getBean("mountService");
}