Spring getEnvironment() - spring

Hi i am trying to write down a simple example of using Spring Profiles her is the code .
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles("kindergarten");
ctx.load("classpath:profile/*-config.xml");
ctx.refresh();
FoodProviderService foodProviderService =
ctx.getBean("foodProviderService", FoodProviderService.class);
List<Food> lunchSet = foodProviderService.provideLunchSet();
for (Food food: lunchSet) {
System.out.println("Food: " + food.getName());
}
}
But strange thing happens it GenericXmlApplicationContext dose not have getEnviroment() method in it's API so the third line
ctx.getEnvironment().setActiveProfiles("kindergarten");
dose not work.My STS refuses to run the main because he think this is a sintax error he gives me this message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method getEnvironment() is undefined for the type GenericXmlApplicationContext
any ideas ?
thanks.

Found the answer it seems i had 3.0.6.RELEASE Spring version but Profiles where added from 3.1.0 version so all i needed to do is go to my pom.xml and change this.
<spring.framework.version>3.0.6.RELEASE</spring.framework.version>
To this
<spring.framework.version>3.1.0.RELEASE</spring.framework.version>

Related

In Testcase statment gives error after upgrading the springboot version from 2.1.7 to 2.6.4

After updating the Spring Boot version to 2.6.4 I am getting error in the test case while in its old version 2.1.7 working fine
#Test
fun `Should include id in all outbound requests`() {
(authenticationSource as TestAuthenticationSource).setCoordinatorToken()
val request = PersonSearch().apply {
firstName = “Xyz”
lastName = “Abc”
}
val oid = UUID.randomUUID().toString()
client
.post()
.uri("/v/search/outbound")
.headers {
it.setBearerAuth("fakeToken")
it.set(CORRELATION_ID, oid)
}
.body(Mono.just(request), PersonSearch::class.java)
.exchange()
assertThat(server.requestCount).isEqualTo(2)
// The bellow line give error while it was working fine in previous version
assertThat(server.takeAllRequests()).allSatisfy { assertThat(it.headers.toMultimap()).containsEntry(CORRELATION_ID, listOf(oid)) }
// Trying in this way as well
assertThat(server.takeAllRequests()).allSatisfy { it -> assertThat(it.headers.toMultimap()).containsEntry(CORRELATION_ID, listOf(oid)) }
}
In error is shows the first line as -
Overload resolution ambiguity. All these functions match.
public open fun allSatisfy(requirements: Consumer<in RecordedRequest!>!): ObjectArrayAssert<RecordedRequest!>! defined in org.assertj.core.api.ObjectArrayAssert
public open fun allSatisfy(requirements: ThrowingConsumer<in RecordedRequest!>!): ObjectArrayAssert<RecordedRequest!>! defined in org.assertj.core.api.ObjectArrayAssert
While it throws same exception Message when running -
Kotlin: Overload resolution ambiguity:
public open fun allSatisfy(p0: Consumer<in RecordedRequest!>!): ObjectArrayAssert<RecordedRequest!>! defined in org.assertj.core.api.ObjectArrayAssert
public open fun allSatisfy(p0: ThrowingConsumer<in RecordedRequest!>!): ObjectArrayAssert<RecordedRequest!>! defined in org.assertj.core.api.ObjectArrayAssert
You are likely hitting https://github.com/assertj/assertj-core/issues/2357.
For workarounds see:
https://github.com/assertj/assertj-core/issues/2357#issuecomment-1103942325
https://github.com/assertj/assertj-core/issues/2357#issuecomment-1117013186
https://github.com/assertj/assertj-core/issues/2357#issuecomment-1087445548
As in this url assertj-core/issues/2357 suggested by #Joel Costigliola I have made small changes just added Consumer key after allSatisfy to eliminate the ambiguity.
assertThat(server.takeAllRequests())
.allSatisfy(
Consumer { // added part
assertThat(it.headers.toMultimap()).containsEntry(CORRELATION_ID, listOf(cId))
}
)

Intellij cannot resolve methods of classes from external library

I am working with the IBM Watson service and imported the library through a maven dependency.
I assumed everything went fine, as all the classes are shown in the external library section:
Instantiating classes works fine, but if I try to use methods from those classes Intellij says "cannot resolve symbol 'methodname'".
public class Watson
{
ConversationService service = new ConversationService("2017-07-02");
service.setUsernameAndPassword("username", "password");
NaturalLanguageClassifier n = new NaturalLanguageClassifier();
n.createClassifier()
}
I have already tried the invalidate caches action and tried other tricks I could find on the internet, but nothing worked... What do I do wrong? Is there any option I have to tick so that Intellij finds the methods?
You have to put the 4 lines within a method. For simplification, I put it in main.
public class Watson
{
public static void main(String[] args)
{
ConversationService service = new ConversationService("2017-07-02");
service.setUsernameAndPassword("sss", "ttt");
NaturalLanguageClassifier n = new NaturalLanguageClassifier();
n.createClassifier("name", "en", new File("/tmp/data"));
}
}

Cannot start bundle programmatically

Note: In my case, I'm using Apache Felix implementation if that's matters.
I have written bundle which I'm using as test. It's very simple "Hello World" bundle that do nothing more than print message to stdout when started/stopped:
public class Activator implements BundleActivator {
#Override
public void start(BundleContext context) throws Exception {
System.out.println("Hello, World.");
}
#Override
public void stop(BundleContext context) throws Exception {
System.out.println("Goodbye, World.");
}
}
There is also MANIFEST file which rather pointless to post since when I deploy above bundle through Apache Felix console from standard distribution (which can be downloaded here) bundle starts and print out message.
Next step I'm trying to do is deploy the very same bundle using programmatic approach. Unfortunately this is not working for me. My code looks as follow:
public static void main(String[] args) throws Exception {
FrameworkFactory frameworkFactory = getFrameworkFactory();
Framework framework = frameworkFactory.newFramework(null);
System.out.println("BundleID = " + framework.getBundleId());
System.out.println("State = " + getState(framework.getState()));
framework.init();
System.out.println("BundleID = " + framework.getBundleId());
System.out.println("State = " + getState(framework.getState()));
BundleContext bundleContext = framework.getBundleContext();
bundleContext.addBundleListener((event) -> {
System.out.println("Bundle Changed Event");
});
bundleContext.addFrameworkListener((event) -> {
System.out.println("Framework Event");
});
bundleContext.addServiceListener((event) -> {
System.out.println("Service Changed Event");
});
Bundle bundle = bundleContext.installBundle("file://<absolute-path-to-bundle-jar-same-as-above");
System.out.println("BundleID = " + bundle.getBundleId());
System.out.println("State = " + getState(bundle.getState()));
bundle.start();
System.out.println("BundleID = " + bundle.getBundleId());
System.out.println("State = " + getState(bundle.getState()));
}
private static FrameworkFactory getFrameworkFactory() throws IllegalStateException {
ServiceLoader<FrameworkFactory> loader = ServiceLoader.load(FrameworkFactory.class);
FrameworkFactory factory = null;
for (FrameworkFactory iterator : loader) {
if (factory != null) {
throw new IllegalStateException("Ambiguous SPI implementations.");
}
factory = iterator;
}
return factory;
}
private static String getState(int state) {
switch (state) {
case Bundle.UNINSTALLED:
return "UNINSTALLED";
case Bundle.INSTALLED:
return "INSTALLED";
case Bundle.RESOLVED:
return "RESOLVED";
case Bundle.STARTING:
return "STARTING";
case Bundle.STOPPING:
return "STOPPING";
case Bundle.ACTIVE:
return "ACTIVE";
default:
throw new IllegalStateException("Unknown state");
}
}
The output looks like follow:
BundleID = 0
State = INSTALLED
BundleID = 0
State = STARTING
Bundle Changed Event
BundleID = 1
State = INSTALLED
BundleID = 1
State = INSTALLED
So as far as I understand bundle got installed but last 4 lines indicate that bundle.start() got ignored for some reason.
Could you point out me what am I missing to make this work?
After hour of debugging and reading through javadoc more carefully this is happening because framework was only initialized instead of being started. To make example work you have to simply add framework.start() after framework.init() (or just call framwork.start() which calls framework.init() if found it necessary).
I'm leaving this information as there are few confusing things:
Official documentation to Apache Felix have information about embedding framework into host application. Unfortunately there is only example that use Apache Felix custom mechanisms that make it not portable to other implementations. What is confusing is warning note which if you want to create portable solution you should use init() and getBundleContext(). Whole note cited bellow:
WARNING The felix.systembundle.activators configuration property is specific to the Felix framework implementation. If you want your code to work with other framework implementations, you should call init() on the framework instance and use getBundleContext() directly. Otherwise, the approach would be very similar.
JavaDoc for parameterless version of init() method do not mention about initialization is not same as starting the framework, although init(FrameworkListener...) have such information.
This Framework will not actually be started until start is called.

Java8, Nashorn: failed to load external .js script file

I'm brand new to Nashorn and trying to load my first js file as follow:
public static void main(String[] args) {
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName("nashorn");
try {
engine.eval("load('https://cdn.jsdelivr.net/sockjs/1.0.3/sockjs.min.js')");
}catch(final ScriptException e) {
System.err.println(e);
}
}
I get the following Exception:
javax.script.ScriptException: TypeError: Cannot read property "prototype" from undefined in http://cdn.jsdelivr.net/sockjs/1.0.3/sockjs.min.js at line number 3
in addition, when I try to evaluate the following:
engine.eval("load('https://code.jquery.com/jquery-1.11.3.min.js')");
the eval() method doesn't return at all - it just stuck on debug (Using Eclipse).
Any idea why prototype isn't defined, any why I cannot evaluate jquery js file?
Thanks!
Nashorn is a ECMAScript5 compatible JavaScript engine. WebSocket API is not a part of ECMAScript 5 but browser API. That's because you get exception.

Pro Spring 3book, class path resource [app-context-annotation.xml] cannot be opened because it does not exist

I'm trying to learn Spring3 by following book Pro Spring3. I'm in chapter 4 where the author explains IoC and DI. He uses GenericXmlApplicationContext to specify the configuration file. He does the following:
package com.apress.prospring3.ch4;
import org.springframework.context.support.GenericXmlApplicationContext;
public class UsingSetterInjection {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
//ctx.load("classpath:app-context-xml.xml");
ctx.load("classpath:app-context-annotation.xml");
ctx.refresh();
MessageRenderer messageRenderer = ctx.getBean("messageRenderer", MessageRenderer.class);
messageRenderer.render();
}
}
My structure is
src/main/resources/app-context-annotation.xml
IOException parsing XML document from class path resource [app-context-annotation.xml]; nested exception is java.io.FileNotFoundException: class path resource [app-context-annotation.xml] cannot be opened because it does not exist
Give the complete path and it will work like a charm.
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:META-INF/spring/app-context-annotation.xml");
Can you try using the following line to load your xml file?
ctx.load("classpath*:app-context-annotation.xml");
I have added a * after the classpath. I think this should resolve your problem. Otherwise you need to check whether this file is there in the application classpath or not.
Cheers.

Resources