I'd like to use an instance of a class that another plugin creates.
In particular, I'd like to use the instance of MQConnection that the mq-notifier-plugin creates and maintains.
I've declared this plugin as a dependency in the POM:
<dependency>
<groupId>com.sonymobile.jenkins.plugins.mq</groupId>
<artifactId>mq-notifier</artifactId>
<version>1.2.5</version>
</dependency>
Imported the class:
import com.sonymobile.jenkins.plugins.mq.mqnotifier.MQConnection;
Tried to get the instance and add a message within the workflowstep:
..
public static class TestConnectionWorkflowStep extends AbstractSynchronousNonBlockingStepExecution<Void> {
private static final long serialVersionUID = 1L;
#StepContextParameter
private transient Run build;
#StepContextParameter
transient TaskListener listener;
#Override
protected Void run() throws Exception {
..
// fill in with exchange, routing_key, data, properties
MQConnection.getInstance().addMessageToQueue(..);
}
}
It compiles fine. I've also instrumented the MQConnection class to log whenever a message is added.
It seems that none of my build step messages are added to the instance's queue and just silently continues.
And as expected, I do still see messages from the mq-notifier-plugin showing up fine.
I've tried using Jenkins.getInstance().getPlugin(MQConnection.class) but doesn't work since MQConnection isn't a subclass of Plugin.
How can I access the MQConnection instance from my plugin?
getInstance() likely assumes an instance was already created when the application was started up, and it retrieves that instance. Since you're calling the method from a library, that startup hasn't happened, so there's no instance to return.
Look at the getInstance() code if you can, and also check any mq-notifier application startup or main methods in the library class. See how it instantiates the MQConnection instance, and you'll need to do the same thing.
There's probably some dependency injection going on in the other project.
I'd like to use the instance of MQConnection that the mq-notifier-plugin creates and maintains.
You're either going to have to have the two applications running side-by-side and communicating with each other, or you're going to have to figure out how to instantiate MQConnection yourself.
It seems that none of my build step messages are added to the instance's queue and just silently continues.
Is this running remotely then? If you have a remote MQConnection instance running then simply calling getInstance will not be enough for the two seperate programs to communicate with each other.
Related
I have some objects registered in my Rmi registry, i check that it's done because when i do a LocateRegistry.getRegistry().list() it results 2 registries like:
0 = "rmi://Mac.local/192.168.1.40:1099/DataService"
1 = "rmi://Mac.local/192.168.1.40:1099/AuthService"
Then, i call a
ServicioAutenticacionInterface authService = (ServicioAutenticacionInterface) Naming.lookup("rmi://Mac.local/192.168.1.40:1099/AuthService");
It throws a NotBoundException..
Just say that interfaces are in a package named commons defined as a dependency for server package who is it´s trying to invoke that lookup.
You passed a URL to Registry.bind()/rebind() instead of just a name.
URLs are passed to Naming.bind()/rebind()/unbind()/lookup(), and returned by Naming.list()`.
Simple names (such as "AuthService") are passed to Registry.bind()/rebind()/unbind()/lookup()
Whatever you passed to Registry.bind()/rebind() is returned verbatim by Registry.list().
Ergo, as Registry.list() is returning URLs, you must have supplied them via Registry.bind()/rebind().
For proof, try Naming.list("rmi://Mac.local/192.168.1.40:1099"). It will return this:
0 = "rmi://Mac.local/192.168.1.40:1099/rmi://Mac.local/192.168.1.40:1099/DataService"
1 = "rmi://Mac.local/192.168.1.40:1099/rmi://Mac.local/192.168.1.40:1099/AuthService"
which is obviously not what you want.
So you need to either use Naming.bind()/rebind() with the same URL strings, or else remove the URL part of the strings and keep using Registry.bind()/rebind().
java.rmi.NotBoundException:
My RMI-based application was working fine until I introduced another function which utilizes a service(WatchService), the service had an internal infinite loop and so this would stall the whole application.
My thought was that, when the server was started, maybe binding process did not completely happen because of the loop implemented inside the service, and the service was started at the same time during binding phase, and so when the client came looking up for the server stub, it could not find it because it wasn't bound or registered/fully in the first place.
When I removed the function/service everything worked fine again, but since I needed the service/function, I had to start it on a new thread inside the same class of the server stub like so
private class FileWatcherThread implements Runnable {
public FileWatcherThread() {
}
#Override
public void run() {
startMonitors();
}
}
Then somewhere inside your main code start the defined thread above.
new Thread(new FileWatcherThread()).start();
And this startMonitors(); is the method that has infinite loop and is defined in the main class, FileWatcherThread is an inner class of the main server class- it actually depends on how you have done your implementation and design. Just get the idea then see if it suits your problem.
I am trying to build my first android app. I have multiple Activities and I am using a Handler and an AssetFileDescriptor in order to play a sound file.
My problem is, how can I pass these objects around? I have one Activity that starts a timer via the handler, and another which stops the timer via the handler. Should I pass these objects around between Activities, or is there another way?
I am not used to Java, but I was wondering if I could make a config static class or something that creates all of these objects, and then each one of my Activities would just access these objects from this static config class. However, this has its own problems, since in order to call the method getAssets(), I cannot use a static class ("Cannot make a static reference to a non-static method.")
Any ideas?
This simplest solution would be to store objects in the Application class, here is a SO answer on the topic Using the Android Application class to persist data
Another more advanced option would be to use Dagger. It is a Dependency Injection framework that can do a lot of cool stuff but is somewhat difficult to get running (atleast took me some time to get working).
Dagger enables defining a Singleton class like this:
#Singleton
public class MySingletonObject {
#Inject
MySingletonObject() {
...
}
}
And whenever you need it in your app:
public class SomeActivityOrFragment {
#Inject MySingletonObject mySingletonObject;
...
mySingletonObject.start();
}
public class SomeOtherActivityOrFragment {
#Inject MySingletonObject mySingletonObject;
...
mySingletonObject.stop();
}
Can i attach java shutdown hook across jvm .
I mean can I attach shut down from my JVM to weblogic server running in different jvm?
The shutdown hook part is in Runtime.
The across JVM part you'll have to implement yourself, because only you know how your JVMs can discover and identify themselves.
It could be as simple as creating a listening socket at JVM1 startup, and sending port number of JVM2 to it. JVM1 would send shutdown notification to JVM2 (to that port) in its shutdown hook.
The short anser is: You can, but not out of the box and there are some pitfalls so please read the section pitfalls at the end.
A shutdown hook must be a thread object Runtime.addShutdownHook(Thread) that the jvm can access. Thus it must be instantiated within that jvm.
The only way I see to do it is to implement a Runnable that is also Serializable and some kind of remote service (e.g. RMI) which you can pass the SerializableRunnable. This service must then create a Thread pass the SerializableRunnable to that Thread's constructor and add it as a shutdown hook to the Runtime.
But there is also another problem in this case. The SerializableRunnable has no references to objects within the remote service's jvm and you have to find a way how that SerializableRunnable can obtain them or to get them injected. So you have the choice between a ServiceLocator or an
dependency injection mechanism. I will use the service locator pattern for the following examples.
I would suggest to define an interface like this:
public interface RemoteRunnable extends Runnable, Serializable {
/**
* Called after de-serialization from a remote invocation to give the
* RemoteRunnable a chance to obtain service references of the jvm it has
* been de-serialized in.
*/
public void initialize(ServiceLocator sl);
}
The remote service method could then look like this
public class RemoteShutdownHookService {
public void addShutdownhook(RemoteRunnable rr){
// Since an instance of a RemoteShutdownHookService is an object of the remote
// jvm, it can provide a mechanism that gives access to objects in that jvm.
// Either through a service locator
ServiceLocator sl = ...;
rr.initialize(sl);
// or a dependency injection.
// In case of a dependecy injection the initialize method of RemoteRunnable
// can be omitted.
// A short spring example:
//
// AutowireCapableBeanFactory beanFactory = .....;
// beanFactory.autowireBean(rr);
Runtime.getRuntime().addShutdownHook(new Thread(rr));
}
}
and your RemoteRunnable might look lioke this
public class SomeRemoteRunnable implements RemoteRunnable {
private static final long serialVersionUID = 1L;
private SomeServiceInterface someService;
#Override
public void run() {
// call someService on shutdown
someService.doSomething();
}
#Override
public void initialize(ServiceLocator sl) {
someService = sl.getService(SomeServiceInterface.class);
}
}
Pitfalls
There is only one problem with this approach that is not obvious. The RemoteRunnable implementation class must be available in the remote service's classpath. Thus you can not just create a new RemoteRunnable class and pass an instance of it to the remote service. You always have to add it to the remote JVMs classpath.
So this approach only makes sense if the RemoteRunnable implements an algorithm that can be configured by the state of the RemoteRunnable.
If you want to dynamically add arbitrary shutdown hook code to the remote JVM without the need to modify the remote JVMs classpath you must use a dynamic language and pass that script to the remote service, e.g. groovy.
I'm constructing an AsyncHttpClient like this:
public AsyncHttpClient getAsyncHttpClient() {
AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder()
.setProxyServer(makeProxyServer())
.setRequestTimeoutInMs((int) Duration.create(ASYNC_HTTP_REQUEST_TIMEOUT_MIN, TimeUnit.MINUTES).toMillis())
.build();
return new AsyncHttpClient(new NettyAsyncHttpProvider(config), config);
}
This gets called once at startup, and then the return value is passed around and used in various places. makeProxyServer() is my own function to take my proxy settings an return a ProxyServer object. What I need to do is be able to change the proxy server settings and then recreate the AsyncHttpClient object. But, I don't know how to shut it down cleanly. A bit of searching on leads me to believe that close() isn't gracefull. I'm worried about spinning up a whole new executor and set of threads every time the proxy settings change. This won't be often, but my application is very long-running.
I know I can use RequestBuilder.setProxyServer() for each request, but I'd like to have it set in one spot so that all callers of my asyncHttpClient instance obey the system-wide proxy settings without each developer having to remember to do it.
What's the right way to re-configure or teardown and rebuild a Netty-based AsyncHttpClient?
The problem with using AsyncHttpClient.close() is that it shuts down the thread pool executor used by the provider, then there is no way to re-use the client without re-building it, because as per documentation, the executor instance cannot be reused once ts is shutdown. So, there is no way but re-build the client if you go that way (unless you implement your own ExecutorService that would have another shutdown logic, but it is a long way to go, IMHO).
However, from looking into the implementation of NettyAsyncHttpProvider, I can see that it stores the reference to the given AsyncHttpClientConfiginstance and calls its getProxyServerSelector() to get the proxy settings for every new NettyAsyncHttpProvider.execute(Request...) invocation (i.e. for every request executed by AsyncHttpClient).
Then, if we could make the getProxyServerSelector() return the configurable instance of ProxyServerSelector, that would do the thing.
Unfortunately, AsyncHttpClientConfig is designed to be a read-only container, instantiated by AsyncHttpClientConfig.Builder.
To overcome this limitation, we would have to hack it, using, say, "wrap/delegate" approach:
Create a new class, derived from AsyncHttpClientConfig. The class should wrap the given separate AsyncHttpClientConfig instance and implement the delegation of the AsyncHttpClientConfig getters to that instance.
To be able to return the proxy selector we want at any given point of time, we make this setting mutable in a this wrapper class and expose the setter for it.
Example:
public class MyAsyncHttpClientConfig extends AsyncHttpClientConfig
{
private final AsyncHttpClientConfig config;
private ProxyServerSelector proxyServerSelector;
public MyAsyncHttpClientConfig(AsyncHttpClientConfig config)
{
this.config = config;
}
#Override
public int getMaxTotalConnections() { return config.maxTotalConnections; }
#Override
public int getMaxConnectionPerHost() { return config.maxConnectionPerHost; }
// delegate the others but getProxyServerSelector()
...
#Override
public ProxyServerSelector getProxyServerSelector()
{
return proxyServerSelector == null
? config.getProxyServerSelector()
: proxyServerSelector;
}
public void setProxyServerSelector(ProxyServerSelector proxyServerSelector)
{
this.proxyServerSelector = proxyServerSelector;
}
}
Now, in your example, wrap your AsyncHttpClient config instance with our new wrapper and use it to configure the AsyncHttpClient:
Example:
MyAsyncHttpClientConfig myConfig = new MyAsyncHttpClientConfig(config);
return new AsyncHttpClient(new NettyAsyncHttpProvider(myConfig), myConfig);
Whenever you invoke myConfig.setProxyServerSelector(newSelector), the new request executed by NettyAsyncHttpProvider instance in your client will use the new proxy server settings.
A few hints/warnings:
This approach relies on the internal implementation of NettyAsyncHttpProvider; therefore make your own judgement on maintainability, future Netty libraries versions upgrade strategy etc. You could always look at the Netty source code before upgrading to the new version. At the current point, I personally think it is unlikely to change too much to invalidate this implementation.
You could get ProxyServerSelector for ProxyServer by using com.ning.http.util.ProxyUtils.createProxyServerSelector(proxyServer) - that's exactly what AsyncHttpClientConfig.Builder does.
The given example has no synchronization logic for accessing proxyServerSelector; you may want to add some as your application logic needs.
Maybe it is a good idea to submit a feature request for AsyncHttpClient to be able to setup a "configuration factory" for the AsyncHttpProvider so all these complications would vanish :-)
You should be holding a RequestHandle instance for all your unfinished requests. When you want to shut down, you can loop through and call isFinished() on all of them until they are all done. Then you know you can safely close it and no pending requests will be killed.
Once it's closed, just build a new one. Don't try to reuse the existing one. If you have references to it around, change those to reference a Factory that will return the current one.
I want to develop a framework(eg automation) which people can use.The idea is i build a container kind of thing (eg tomcat but not exactly like a webserver).The container will have one xml file which will hold the enties of classes that are to be executed. (eg like web.xml of tomcat)
for eg xml (run.xml) can be like follows
<job>jobNameXyz</job>
<class>com.pkg.jobXyz <class>
Each of the xml job class should extedn MyBaseClass like how servlet extends HttpServlet and override
specified method doJob
public class MyClass extends Job{
public String doJob(){
//do some thing
}
}
When i place Myclass inside my continner and trigger container the jobmust run and the method doJob
How can this be done?Any one can enter deploy his jobs by putting his class file in our dir and then editing run.xml
How can this be done?Any guidelines
Your container should parse the XML file, extract a list of class names, call Class.forName for all the class names, to get a list of Class objects. Then use Class.newInstance to call the default constructor of each of the class, cast the created objects to Job, and call their doJob method.
I would use (and have been using) ANT for this purpose.
EDIT:
The couple of techniques that I have used are:
Using ANT exec task
Using customized ANT task.
Whichever technique you use, the idea is to call ANT to execute the build file. This can be invoked via invoking ANT process externally (using Runtime.exec java ant for instance) or invoking the build file programmatically.