ClassCastException On JBOSS OSGI 7.1 - jboss

I use JBOSS OSGI 7.1 for my project.
I have 2 bundle:
usermanagement (service provider)
jerseyBundle (service consumer)
When I deploy and start usermanagement bundle,
Then deploy and start jersey bundle.
jerseyBundle getServiceReference() successful.
Then.
I try to redeploy and restart usermanagement. Then refresh all bundles.
JerseyBundle getServiceReference() with Exception: "ClassCastException"
This is code I use to get service:
public <T> T getService(Class<T> type,List<ServiceReference> _sref) {
try {
ServiceReference sref = bundleContext.getServiceReference(type.getName());
if(sref != null)
{
_sref.add(sref);
}
return type.cast(bundleContext.getService(sref));
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
I use blueprint to register services.
I tried to ungetservice but it don't solved this problem.
public void unGetService(List<ServiceReference> _sref) {
try{
while(_sref != null && _sref.size() >0 )
{
System.err.println("==============" + bundleContext.ungetService(_sref.remove(0)));
}
}catch(Exception ex){
ex.printStackTrace();
}
}
Are there any ways to redeploy service provider bundle, don't need redeploy service consumer bundle?

The reason for the observed behaviour may be that OSGi caches the service object by bundle. So if you do bundleContext.getService(sref) then OSGI will store this object internally and always return the same until you do ungetService.
So when you update the service bundle which also contains the interface and refresh the client you will have a new class for the interface. If you now do a cast of an old service object to the new interface the ClassCastException will occur.
One way to cope with this is to only use the service object for a short period of time and then unget it. Like this:
ServiceReference sref = bundleContext.getServiceReference(type.getName());
myO = type.cast(bundleContext.getService(sref));
doStuff(myO);
bundleContext.ungetService(sref)
Of course this is only practicable for infrequent calls as you have some overhead.
The other way is to use a ServiceTracker and react on service additions and removals. So for example you could inject a service into your class which does "doStuff" and remove / replace the service when there are changes. This is quite hard to do on your own though.
In fact this is the reason why there are frameworks like declarative services (DS) or blueprint. These make sure to reinject service and restart your components when services come and go.
As you are already using blueprint on the provider side you might try to use it on the client side too. The blueprint client should not have the problems you observed.
Btw. blueprint and DS handle service dynamics very differently. Blueprint injects a proxy once and then just replaces the service object inside the proxy while DS will really restart your user component.

Related

loadbalanced ribbon client initialization against discovery service (eureka)

I have service which runs some init scripts after application startup (implemented with ApplicationListener<ApplicationReadyEvent>). In this scripts I need to call another services with RestTemplate which is #LoadBalanced. When the call to service is invoked there's no information about instances of remote service because discovery server was not contacted at that time (I guess).
java.lang.IllegalStateException: No instances available for api-service
at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:79)
So is there way how to get list of available services from discovery server at application startup, before my init script will execute?
Thanks
edit:
The problem is more related to fact, that in current environment (dev) all services are tied together in one service (api-service). So from within api-service I'm trying to call #LoadBalanced client api-service which doesn't know about self? Can I register some listener or something similar to know when api-service (self) will be available?
here are the sample applications. I'm mainly interested how to have working this method
edit2:
Now there could be the solution to create EurekaListener
public static class InitializerListener implements EurekaEventListener {
private EurekaClient eurekaClient;
private RestOperations restTemplate;
public InitializerListener(EurekaClient eurekaClient, RestOperations restTemplate) {
this.eurekaClient = eurekaClient;
this.restTemplate = restTemplate;
}
#Override
public void onEvent(EurekaEvent event) {
if (event instanceof StatusChangeEvent) {
if (((StatusChangeEvent) event).getStatus().equals(InstanceInfo.InstanceStatus.UP)) {
ResponseEntity<String> helloResponse = restTemplate.getForEntity("http://api-service/hello-controller/{name}", String.class, "my friend");
logger.debug("Response from controller is {}", helloResponse.getBody());
eurekaClient.unregisterEventListener(this);
}
}
}
}
and then register it like this:
EurekaEventListener initializerListener = new InitializerListener(discoveryClient, restTemplate);
discoveryClient.registerEventListener(initializerListener);
However this is only executed only when application is registered to discovery service first time. Next time when I stop the api-service and run it again, event is not published. Is there any other event which can I catch?
Currently, in Camden and earlier, applications are required to be registered in Eureka before they can query for other applications. Your call is likely too early in the registration lifecycle. There is an InstanceRegisteredEvent that may help. There are plans to work on this in the Dalston release train.

SOAP service in AEM 6.2

I'm trying to create a SOAP service in AEM 6.2 (the client cant make a REST call). Right now its up and works, the problem is when we redeploy or the AEM instance is reset... then the port of the service gets locked. Error on "create()".
final JaxWsServerFactoryBean jaxWsServerFactoryBean = new JaxWsServerFactoryBean();
jaxWsServerFactoryBean.setServiceClass(getWebServiceClass());
jaxWsServerFactoryBean.setAddress(this.webServiceAddress);
jaxWsServerFactoryBean.setServiceBean(this);
jaxWsServerFactoryBean.getInInterceptors().add(new LoggingInInterceptor());
jaxWsServerFactoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
server = jaxWsServerFactoryBean.create();
*ERROR* [OsgiInstallerImpl] org.apache.cxf.transport.http_jetty.JettyHTTPServerEngine Could not start Jetty server on port 4,517: Address already in use: bind
The first time I deploy works fine but then I have to change port for each redeploy... I'm closing the server if exists before that create, and if I call "isStarted()" it says false.
server.getDestination().shutdown();
server.stop();
server.destroy();
Really stuck for days on this, thank you for your help.
You should create a OSGI bundle and create your soap service inside the bundle.
#Activate
public void activate(BundleContext bundleContext) throws Exception {
... start your soap service
}
#Deactivate
public void deactivate() throws Exception {
... stop your soap service
}
Now you can restart your soap service by restarting the bundle. here is reference how to create a OSGI bundle. http://www.aemcq5tutorials.com/tutorials/create-osgi-bundle-in-aem/

annotation #RibbonClient not work together with RestTemplate

I am trying Ribbon configuration with RestTemplate based on bookmark service example but without luck, here is my code:
#SpringBootApplication
#RestController
#RibbonClient(name = "foo", configuration = SampleRibbonConfiguration.class)
public class BookmarkServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BookmarkServiceApplication.class, args);
}
#Autowired
RestTemplate restTemplate;
#RequestMapping("/hello")
public String hello() {
String greeting = this.restTemplate.getForObject("http://foo/hello", String.class);
return String.format("%s, %s!", greeting);
}
}
with error page as below:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Mar 22 19:59:33 GMT+08:00 2016
There was an unexpected error (type=Internal Server Error, status=500).
No instances available for foo
but if I remove annotation #RibbonClient, everything will be just ok,
#RibbonClient(name = "foo", configuration = SampleRibbonConfiguration.class)
and here is SampleRibbonConfiguration implementation:
public class SampleRibbonConfiguration {
#Autowired
IClientConfig ribbonClientConfig;
#Bean
public IPing ribbonPing(IClientConfig config) {
return new PingUrl();
}
#Bean
public IRule ribbonRule(IClientConfig config) {
return new AvailabilityFilteringRule();
}
}
Is it because RibbonClient can not work with RestTemplate together?
and another question is that does Ribbon configuration like load balancing rule could be configured via application.yml configuration file?
as from Ribbon wiki, seems we can configure Ribbon parameters like NFLoadBalancerClassName, NFLoadBalancerRuleClassName etc in property file, does Spring Cloud also supports this?
I'm going to assume you're using Eureka for Service Discovery.
Your particular error:
No instances available for foo
can happen for a couple of reasons
1.) All services are down
All of the instances of your foo service could legitimately be DOWN.
Solution: Try visiting your Eureka Dashboard and ensure all the services are actually UP.
If you're running locally, the Eureka Dashboard is at http://localhost:8761/
2.) Waiting for heartbeats
When you very first register a service via Eureka, there's a period of time where the service is UP but not available. From the documentation
A service is not available for discovery by clients until the
instance, the server and the client all have the same metadata in
their local cache (so it could take 3 heartbeats)
Solution: Wait a good 30 seconds after starting your foo service before you try calling it via your client.
In your particular case I'm going to guess #2 is likely what's happening to you. You're probably starting the service and trying to call it immediately from the client.
When it doesn't work, you stop the client, make some changes and restart. By that time though, all of the heartbeats have completed and your service is now available.
For your second question. Look at the "Customizing the Ribbon Client using properties" section in the reference documentation. (link)

How can I use the service fabric actor model from MVC project?

I used the stateful actor template in visual studio 2015 to create a service fabric service. In the same solution I created an MVC app and in the about controller I attempted to copy the code from the sample client. When I run the web app and execute about action it just hangs. I don't get an exception or anything that indicates why it didn't work. Running the sample client console app where I got the code works just fine. Any suggestions on what may be wrong?
public ActionResult About()
{
var proxy = ActorProxy.Create<IO365ServiceHealth>(ActorId.NewId(), "fabric:/O365Services");
try
{
int count = 10;
Console.WriteLine("Setting Count to in Actor {0}: {1}", proxy.GetActorId(), count);
proxy.SetCountAsync(count).Wait(); /* Hangs here */
Console.WriteLine("Count from Actor {0}: {1}", proxy.GetActorId(), proxy.GetCountAsync().Result);
}
catch (Exception ex)
{
Console.WriteLine("{0}", ex.Message);
}
ViewBag.Message = "Your application description page.";
return View();
}
Is the MVC app hosted within Service Fabric? If not then it won't be able to access Service Fabric information unless it's exposed in some way (e.g. through an OwinCommunicationListener on a service).

Has anyone successfully deployed a GWT app on Heroku?

Heroku recently began supporting Java apps. Looking through the docs, it seems to resemble the Java Servlet Standard. Does anyone know of an instance where a GWT app has been successfully deployed on Heroku? If so, are there any limitations?
Yes, I've got a successful deployment using the getting started with Java instructions here:
http://devcenter.heroku.com/articles/java
I use the Maven project with appassembler plugin approach but added gwt-maven-plugin to compile a GWT app during the build.
When you push to heroku you see the GWT compile process running, on one thread only so quite slow but it works fine.
The embedded Jetty instance is configured to serve up static resources at /static from src/main/resources/static and I copy the compiled GWT app to this location during the build and then reference the .nocache.js as normal.
What else do you want to know?
You've got a choice, either build the Javascript representation of your GWT app locally into your Maven project, commit it and the read it from your app, or to generate it inside Heroku via the gwt-maven-plugin as I mentioned.
The code to serve up files from a static location inside your jar via embedded Jetty is something like this inside a Guice ServletModule:
(See my other answer below for a simpler and less Guice-driven way to do this.)
protected void configureServlets() {
bind(DefaultServlet.class).in(Singleton.class);
Map<String, String> initParams = new HashMap<String, String>();
initParams.put("pathInfoOnly", "true");
initParams.put("resourceBase", staticResourceBase());
serve("/static/*").with(DefaultServlet.class, initParams);
}
private String staticResourceBase() {
try {
return WebServletModule.class.getResource("/static").toURI().toString();
}
catch (URISyntaxException e) {
e.printStackTrace();
return "couldn't resolve real path to static/";
}
}
There's a few other tricks to getting embedded Jetty working with guice-servlet, let me know if this isn't enough.
My first answer to this turned out to have problems when GWT tried to read its serialization policy. In the end I went for a simpler approach that was less Guice-based. I had to step through the Jetty code to understand why setBaseResource() was the way to go - it's not immediately obvious from the Javadoc.
Here's my server class - the one with the main() method that you point Heroku at via your app-assembler plugin as per the Heroku docs.
public class MyServer {
public static void main(String[] args) throws Exception {
if (args.length > 0) {
new MyServer().start(Integer.valueOf(args[0]));
}
else {
new MyServer().start(Integer.valueOf(System.getenv("PORT")));
}
}
public void start(int port) throws Exception {
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setBaseResource(createResourceForStatics());
context.setContextPath("/");
context.addEventListener(new AppConfig());
context.addFilter(GuiceFilter.class, "/*", null);
context.addServlet(DefaultServlet.class, "/");
server.setHandler(context);
server.start();
server.join();
}
private Resource createResourceForStatics() throws MalformedURLException, IOException {
String staticDir = getClass().getClassLoader().getResource("static/").toExternalForm();
Resource staticResource = Resource.newResource(staticDir);
return staticResource;
}
}
AppConfig.java is a GuiceServletContextListener.
You then put your static resources under src/main/resources/static/.
In theory, one should be able to run GWT using the embedded versions of Jetty or Tomcat, and bootstrap the server in main as described in the Heroku Java docs.