OSGi Declarative Services - NullPointer Exception - osgi

I have a problem with my Declarative Services. I have 2 bundles, one is a server provider and another the user interface that consumes the service.
On server side, the implementation is:
public boolean checkUser(){
return true;
}
And the XML file inside OSGi-INF folder:
<component name="ZBService">
<implementation class="service.ZBService" />
<service>
<provide interface="service.IZBService" />
</service>
</component>
On client side, the implementation is:
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService{
IZBService zb;
public void setZBService(IZBService eventAdmin) {
this.zb = eventAdmin;
}
public void unsetZBService(IZBService eventAdmin){
if(this.zb == eventAdmin){
this.zb = null;}
}
public boolean greetServer(String input, String input2) throws Exception {
return zb.checkUser();
}
}
And XML file:
<component name="ZBService">
<implementation class="main.java.com.gwt.app.server.GreetingServiceImpl" />
<service>
<provide interface="main.java.com.gwt.app.client.GreetingService"/>
</service>
<reference name="zb" interface="service.IZBService" bind="setZBService" unbind="unsetZBService" cardinality="0..n" policy="dynamic" />
</component>
Also, I have included the tag Service-Component on manifest file and I have deployed the equinox ds bundle that is ACTIVE.
The client is a GWT user interface, then I inject the service reference into server side of GWT. Well, when I deploy the application on Equinox it runs, but when I push the button, I launch an event to call ZBService. I have debugged the application and the error is zb attribute is null. It is to say, the dependence is nos injected. However the services are exposed on Equinox. If I write services on Equinox console, the services are deployed. Then, my conclusion is the error is due to the injection does not perform.
I would like to know if someone knows what is the reason??
Thanks a lot in advance!!
Nice day
EDIT:
I did your suggestions but it doesn't run. I change the component names and condinality/policy. The result is the same --> NullPointerException due to the injection isn't done.
Also I have debug the application to see if the methods bind and/or unbind are called, but they aren't.
The complete class is:
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService{
static protected IZBService zb;
public GreetingServiceImpl(){
System.out.println("Constructor GreetingServiceImpl");
}
public IZBService getZb() {
return zb;
}
public void setZb(IZBService zb) {
GreetingServiceImpl.zb = zb;
}
public void unsetZb(IZBService zb) {
GreetingServiceImpl.zb = zb;
}
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Cache the current thread
Thread currentThread = Thread.currentThread();
// We are going to swap the class loader
ClassLoader oldContextClassLoader = currentThread.getContextClassLoader();
currentThread.setContextClassLoader(this.getClass().getClassLoader());
super.service(req, resp);
currentThread.setContextClassLoader(oldContextClassLoader);
}
public void activate(ComponentContext context) {
System.out.println("Creating new greeter for " + context.getProperties().get("name")
+ ": " + context.getComponentInstance().toString());
}
public void activate() {
System.out.println("Activando la referencia al servicio");
}
public void deactivate(ComponentContext context) {
System.out.println("Deactivating greeter for " + context.getProperties().get("name")
+ ": " + context.getComponentInstance().toString());
}
public boolean greetServer(String input, String input2) throws Exception {
return zb.checkUser();
}
}
And the XML client is:
<?xml version="1.0" encoding="UTF-8" ?>
<scr:component name="serviceZB" xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0">
<implementation class="main.java.com.gwt.app.server.GreetingServiceImpl" />
<!-- <service>
<provide interface="main.java.com.gwt.app.client.GreetingService"/>
</service> -->
<reference name="zb" interface="service.IZBService"
bind="setZb" unbind="unsetZb" cardinality="1..1"
policy="static" />
</scr:component>
Why isn't the service injected if the service is deployed???

Here is a list of things you can try:
First, remove the "static" of zb, that could be the problem.
If you are using Equinox, add the -Dequinox.ds.print=true flag to the VM arguments and see more information about parsing XMLs and so
Of course, add sysouts to setZB and unsetZB :)
Remember that IZBService implementation needs a constructor without arguments
If you are using Equinox use the "list -c" command to obtain information of each component (it's cool because says exactly why a component is not registered).
Set the "inmediate=true" in XMLs to force to inmediatly activation.

You have both components with the same name, , which is kind of awkward when discussing them.
The reference on the client side has: cardinality="0..n" policy="dynamic". Which means it can be activated with zero to n references. Yet your code does not handle this. It seems to expect exactly one reference. Perhaps you should use cardinality="1..1" policy="static".

Related

Spring webflow binder not binding collection object

I'm using spring webflow v2.4.8 in my app, and trying to bind the model properties using <binder></binder>. But my collection objects (list1, list2 both ArrayList) never get bound. If I remove the <binder></binder> altogether, all properties are getting correctly bound, but in my case that is not an option.
Do I need to use some custom converter here? Any help greatly appreciated
<view-state id="myId" model="myModel" view="myView" >
<binder>
<binding property="list1"/>
<binding property="list2"/>
<binding property="string1"/>
<binding property="string2"/>
.
.
.
</binder>
.
.
.
</view-state>
It's been a while, but in my project I have a custom ConversionService, so maybe you can try using one like this:
[EDIT]
Here is an example of a converter using a service (that gets the object from the db)
#Named
public class StringToMyType extends StringToObject {
#Inject
private MyTypeService service;
public StringToMyType(MyType myObject) {
super(myObject);
}
#Override
protected Object toObject(String id, Class<?> targetClass) throws Exception {
if (id != null && id.length != 0) {
return service.findById(new Long(id));
} else return null;
}
#Override
protected String toString(Object myObject) throws Exception {
return Objects.toString(((MyType) myObject).getId());
}
}
and add it here
public class CustomDefaultConversionService extends DefaultConversionService {
#Override
protected void addDefaultConverters() {
super.addDefaultConverters();
addConverter(new MyTypeConverter()
addConverter(new ObjectToCollection(this));
}
}
it needs to then be registered this way (xml):
<webflow:flow-builder-services id="flowBuilderServices" view-factory-creator="mvcViewFactoryCreator" conversion-service="conversionService"/>
<bean id="conversionService" class="path.to.converter.CustomDefaultConversionService"/>
hope this helps

camel with twitter simple example

I am novice in apache-camel and I started with simple apache camel-twitter example using spring. I am using 2.20 version for camel and 2.19 version for camel-twitter. Below is my router code,
public class TwitterRouter extends RouteBuilder {
public void configure() throws Exception {
System.out.println("Test");
String twitter = "twitter://streaming/filter?type=event&keywords="+ URLEncoder.encode("london", "utf8")+"&consumerKey=key&consumerSecret=secretkey&accessToken=accesstoken&accessTokenSecret=accesstokensecret";
from(twitter).process(new Processor() {
public void process(Exchange exchange) throws Exception {
Status status = exchange.getIn().getBody(Status.class);
ProducerTemplate template = exchange.getContext().createProducerTemplate();
User user = status.getUser();
String name = user.getName();
System.out.println("name "+name);
template.sendBody("twitter","name "+name);
String screenName = user.getScreenName();
String text = status.getText();
}
});
System.out.println("Test1");
}
And my spring context file as below,
<bean id="routeBuilder" class="com.xyz.route.TwitterRouter" />
<camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="routeBuilder" />
</camelContext>
So below are my queries,
After running program only Test and Test1 messages are printed on console. But whatever inside process method is not printed on console. I tried with producttemplate also but its not printing. So can anybody please help.
Also I tried to search for simpe camel-twitter example but not found. Does anybody have such example.

Custom JASPIC on WebSphere error message

Though similar, the specific problem I have is not addressed in Use JASPIC auth module on WebSphere 8.5
I am getting the following error message:
SECJ8027E: The path and name of file where JASPI persistent registrations are stored must be specified using property com.ibm.websphere.jaspi.configuration.
I can set the custom property in the administration to some existing folder but I wanted to make sure that is the right approach or if there is some step I was missing.
Note I am specifically using the "embedded in application" approach rather than a server installed JASPIC module so I have something like this
#WebListener
public class JaspicInitializer implements
ServletContextListener {
#Override
public void contextInitialized(final ServletContextEvent sce) {
final Map<String, String> options = new HashMap<>();
AuthConfigFactory.getFactory()
.registerConfigProvider(AuthModuleConfigProvider.class.getName(), options, "HttpServlet", null, null);
}
}
I had the error on both WebSphere 8.5.5.11 and 9.0.0.3
From #Uux comment, I changed the way I do the registration so it no longer give the error.
#WebListener
public class JaspicInitializer implements
ServletContextListener {
private String registrationID;
#Override
public void contextDestroyed(final ServletContextEvent sce) {
AuthConfigFactory.getFactory().removeRegistration(registrationID);
}
#Override
public void contextInitialized(final ServletContextEvent sce) {
final ServletContext context = sce.getServletContext();
registrationID = AuthConfigFactory.getFactory()
.registerConfigProvider(new AuthModuleConfigProvider(), "HttpServlet",
context.getVirtualServerName() + " " + context.getContextPath(), "JEE Sample");
}
}
Also WebSphere Global Security needs to be configured with
Enable application security
Enable Java Authentication SPI (JASPI)

TestNG. Need to run specific method before all tests and specifiic test after all tests

Used Selenium + TestNG + Maven.
I want to automate testing vulnerabilities using OWASP ZAP. For this I need to start ZAProxyScanner before all tests - execute method before all tests.
public void initZap(){
zapScanner = new ZAProxyScanner(ZAP_PROXYHOST,ZAP_PROXYPORT,ZAP_APIKEY);
zapScanner.clear(); //Start a new session
zapSpider = (Spider)zapScanner;
}
and when all functional tests were executed - run test for searching vulnerabilities
#Test
public void scanning() throws ClientApiException{
spiderWithZap();
setAlertAndAttackStrength();
zapScanner.setEnablePassiveScan(true);
scanWithZap();
}
Method and test located in one class, e.g. public class TestSecurity
Here is sample of my testng.xml with packages containing functional tests
<suite name="Chrome" thread-count="1" parallel="tests" configfailurepolicy="continue">
<test name="chrome">
<parameter name="browser" value="chrome"/>
<packages>
<package name="tests.suiteLogIn"></package>
<package name="tests.suiteSettings"></package>
<package name="tests.suiteSearch"></package>
</packages>
</test>
UPD. post modified code with AfterTest in it.
I use only Before/AfterMethod annotations
#BeforeMethod(alwaysRun=true)
#Parameters({"browser", "environment"})
public void setUp(#Optional ("firefox") String browser, #Optional ("local") String environment, Method method) throws IOException {
System.out.println("Test name: " + method.getName());
WebDriver driver = getMyDriver(browser, environment);
System.setProperty(ESCAPE_PROPERTY, "false");
}
#AfterMethod(alwaysRun=true)
#Parameters("browser")
public void tearDown(#Optional ("firefox") String browser){
DriverMaster.stopDriver();
}
#BeforeSuite
#Parameters("browser")
public void startZap(#Optional ("firefox") String browser){
if(browser.equals("firefox")){
sec.initZap();
}
}
#AfterSuite
#Parameters("browser")
public void scanZap(#Optional ("firefox") String browser) throws ClientApiException{
if(browser.equals("firefox")){
LoginPage lp = new LoginPage(getDriverInstance()).load();
lp.login("name", "pass");
sec.scanning();
}
}
You basically have two options:
Use #BeforeSuite and #AfterSuite and include that in the files to run or make all your classes extend it
Use ITestListener or ISuiteListener and put the setup and teardown code in their before and after methods.
With listeners, one advantage that I can see is if you want to do conditional teardown (scanning) based on some testresults you can control that too.

What are the other ways to specify code for Insight to analyze?

Spring Insight documentation states:
A trace represents a thread of execution. It is usually started by an HTTP request but can also be started by a background job
My application architecture style is one of queues running in the background that I'd like to instrument as well. However, I can't figure out how to get Spring Insight to instrument these calls initiated by queued message. I.e. I'd like to instrument the trace after a message is read off of the queue.
How can I ensure Insight instruments these background jobs?
I ended up creating an aspect that targets all of the Command Handlers. It extends the AbstractOperationCollectionAspect, implements the collectionPoint aspect passing in the Handler as an argument to use when it implements the createOperation method.
I.e.
public aspect CommandHandlerOperationCollectionAspect extends AbstractOperationCollectionAspect
{
public pointcut collectionPoint():
execution(* com.xtrac.common.core.handler.ThreadedHandler.HandlerRunnable.executeActorHandler(com.xtrac.common.core.handler.Handler,java.lang.Object));
protected Operation createOperation(JoinPoint jp)
{
Object[] args = jp.getArgs();
com.xtrac.common.core.handler.Handler handler = (Handler) args[0];
Operation operation = new Operation()
.type(XTRACOperationType.COMMAND_HANDLER)
.label(handler.getClass().getSimpleName())
.sourceCodeLocation(getSourceCodeLocation(jp));
return operation;
}
#Override
public String getPluginName()
{
return HandlerPluginRuntimeDescriptor.PLUGIN_NAME;
}
#Override
public boolean isMetricsGenerator()
{
return true;
}
}
I also implemented an AbstractSingleTypeEndpointAnalyzer to fill out the analyzer:
public class HandlerEndPointAnalyzer extends AbstractSingleTypeEndpointAnalyzer
{
private static final HandlerEndPointAnalyzer INSTANCE=new HandlerEndPointAnalyzer();
private HandlerEndPointAnalyzer() {
super(XTRACOperationType.COMMAND_HANDLER);
}
public static final HandlerEndPointAnalyzer getInstance() {
return INSTANCE;
}
#Override
protected EndPointAnalysis makeEndPoint(Frame handlerFrame, int depth) {
Operation operation = handlerFrame.getOperation();
String resourceLabel = operation.getLabel();
String exampleRequest = EndPointAnalysis.getHttpExampleRequest(handlerFrame);
return new EndPointAnalysis(EndPointName.valueOf(resourceLabel),
resourceLabel,
exampleRequest,
getOperationScore(operation, depth),
operation);
}
being sure to add it as a descriptor:
public class HandlerPluginRuntimeDescriptor extends PluginRuntimeDescriptor {
public static final String PLUGIN_NAME = "handler";
private static final HandlerPluginRuntimeDescriptor INSTANCE=new HandlerPluginRuntimeDescriptor();
private static final List<? extends EndPointAnalyzer> epAnalyzers=
ArrayUtil.asUnmodifiableList(HandlerEndPointAnalyzer.getInstance());
private HandlerPluginRuntimeDescriptor() {
super();
}
public static final HandlerPluginRuntimeDescriptor getInstance() {
return INSTANCE;
}
#Override
public Collection<? extends EndPointAnalyzer> getEndPointAnalyzers() {
return epAnalyzers;
}
#Override
public String getPluginName() {
return PLUGIN_NAME;
}
}
All noted in the spring xml file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:insight="http://www.springframework.org/schema/insight-idk"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/insight-idk http://www.springframework.org/schema/insight-idk/insight-idk-1.0.xsd">
<insight:plugin name="handler" version="${project.version}" publisher="XTRAC Solutions LLC" />
<insight:operation-group group="XTRAC Handlers" operation="command_handler_operation" />
<insight:operation-group group="XTRAC Handlers" operation="event_handler_operation" />
<insight:operation-group group="XTRAC Classic" operation="xtrac_workflow_operation" />
<insight:operation-view operation="command_handler_operation"
template="com/xtrac/insight/command_handler_operation.ftl" />
<insight:operation-view operation="event_handler_operation"
template="com/xtrac/insight/event_handler_operation.ftl" />
<insight:operation-view operation="xtrac_workflow_operation"
template="com/xtrac/insight/xtrac_workflow_operation.ftl" />
<bean id="handlerPluginEndPointAnalyzer"
class="com.xtrac.insight.HandlerEndPointAnalyzer"
factory-method="getInstance"
lazy-init="true"
/>
<bean id="handlerPluginRuntimeDescriptor"
class="com.xtrac.insight.HandlerPluginRuntimeDescriptor"
factory-method="getInstance"
lazy-init="true"
/>
</beans>
along with some ftls.
I also created a MethodOperationCollectionAspect to collect some of the web service calls that occur in these handers. This sets it up for a nice display that tells me a lot about what is going on during the hander operation, and how much time it takes. E.g.
This set up a framework for maintaining a monitor on the health of the application if I set up the base line Thresholds for the named handlers
This is very useful because I can then tell if the application is healthy. Otherwise, the endpoints default to <200 ms for healthy.

Resources