I have an app with many endpoints. I made a change to functionWhoIsCallingMe(). I want to find which controller endpoints call this function (directly or hierarchically) so I can test it.
#RequestMapping("/a")
someEndpoint(){
anyFunction()
}
#RequestMapping("/b")
anotherEndpoint(){
functionWhoIsCallingMe()
}
anyFunction(){
functionWhoIsCallingMe()
}
Given this code I want to know ["/a", "/b"] is calling functionWhoIsCallingMe().
I tried "Call Hierarchy" but that's not practical here because it would take to long to open all the tabs. I also tried filtering like suggested here, but that doesn't work because you can only specify one type of class to NOT match and if it doesn't match it wont show the calling method. I can't say only show files with Controller in the file name.
#RequestMapping("/b")
public void someEndpoint() {
anyFunction(1);
}
#RequestMapping("/b")
public void anotherEndpoint() {
functionWhoIsCallingMe(1);
}
public void anyFunction(int val/** init val=1*/) {
functionWhoIsCallingMe(val + 1);
}
public void functionWhoIsCallingMe(int val/** init val=1*/) {
try {
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
String defName = ste[val + 1].getMethodName();
String[] path = this.getClass().getMethod(defName).getAnnotation(RequestMapping.class).value();
System.out.println("Url path:" + path[0]);
} catch (Exception ex) {
}
}
Related
I am really needing some help on this.
I have adopted the JNOTIFY approach to detecting any new files in a directory. When the file arrives the Listener informs that a new file is in the location.
#BeforeTest(alwaysRun=true)
public void Polling() throws Exception {
ListenToNotifications.checkFolderPickup();
}
I have attempted this where I addded a call to my Setup function in order to call my setup function after the file is detected.
//snippet from Listener Class from checkFolderPickup();
public void fileCreated(int wd, String rootPath, String name) {
print("New File just created " + rootPath + " : " + name);
Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
try {
BaseTest.setup();
} catch (Exception e) {
e.printStackTrace();
}
}
My question is //Thread.sleep(1000000) i feel this is not a safe approach and I wanted to know if there is any other approach that I could possibly use instead of a Thread.Sleep, because this function will have to be executed once each time a new file is available and the old file will be deleted eventually and so on, I cannot make the Sleep to short , it will just ignore and continue with Base.Setup()
public static void checkFolderPickup() throws Exception {
...removed other code
boolean watchSubtree = true;
int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());
//Thread.sleep(1000000);
Thread.sleep(20000);
boolean res = JNotify.removeWatch(watchID);
if (!res) {
// invalid watch ID specified.
}
}
I basically need my framework to keep polling that directory and each time it will execute the base setup process and follow a workflow, delete the file then poll again and so on.
Can anyone please advise?
You don't need any other modules , you can use custom expected condition:##
using:
import java.io.File;
define the method inside any pageobject class:
private ExpectedCondition<Boolean> newfilepresent() {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
File f = new File("D:\\workplace");
return f.listFiles().length>1;
}
#Override
public String toString() {
return String.format("wait for new file to be present within the time specified");
}
};
}
we created a custom expected condition method now use it as:
and in code wait like:
wait.until(pageobject.filepresent());
Output:
Failed:
Passed
Once you register a watch on a directory with JNotify, it will continue to deliver events for files in that directory. You should not remove the watch if you wish to continue to receive events for that directory.
In our setup, we perform some STATIC-INIT build steps including adding all resource paths to a list in an object. We use a Recorder for this, because the object cannot be accessed during the static init phase. In JVM mode, we see that the list does indeed contain all resource paths. However, this is not the case in Native mode. The list remains empty, even though the build logs show that we iterated over the resources and added them to the list.
This is what our setup looks like:
First: The file that is accessible at runtime and contains all resource paths.
#ApplicationScoped
public class ServiceResourcesList {
private List<String> resources;
public ServiceResourcesList() {
resources = new ArrayList<>();
}
public void addResource(String resource) {
this.resources.add(resource);
}
public List<String> getResources() {
return resources;
}
public List<String> getResources(Predicate<String> filter) {
return resources.stream().filter(filter).collect(Collectors.toList());
}
}
The recorder, which returns a BeanContainerListener:
#Recorder
public class ServiceResourcesListRecorder {
public BeanContainerListener addResourceToList(String resource) {
return beanContainer -> {
ServiceResourcesList producer = beanContainer.instance(ServiceResourcesList.class);
producer.addResource(resource);
};
}
}
And finally the (simplified) buildstep. Note that we use a BuildProducer which should make sure that the objects have been registered already before applying the Recorder methods.
#BuildStep
#Record(STATIC_INIT)
void createResourceList(final BuildProducer<BeanContainerListenerBuildItem> containerListenerProducer, ServiceResourcesListRecorder recorder) {
// Some code to get the resource paths, but this could be anything
// ...
for (String resourcePath: resourcePaths) {
LOGGER.info(resourcePath + " added to recorder");
containerListenerProducer.produce(new BeanContainerListenerBuildItem(recorder.addResourceToList(resourcePath)));
}
}
Am I doing something wrong? Are recorders not meant to be used for native executables? Should I add RegisterForReflection somewhere?
Thanks
We solved this problem by using RUNTIME-INIT and static methods instead.
I want to use the BluetoothA2DPSink service in android,
it's a hidden class but I built a modified SDK and ROM and now Android studio can see it.
The problem is I can't use it, whenever i try
'BluetoothA2DPSink sink = new BluetoothA2DPSink()'
I get this error: "BluetoothA2DPSink() is not public in 'android.bluetooth.BluetoothA2dpSink'. Connot be accesed from outside package".
I verified it and it is in fact public:
"public final class BluetoothA2dpSink implements BluetoothProfile{..."
How can I use its methods?
Any help would be much appreciated.
If you pasted your error message correctly, the problem is not with the class, but with the constructor. Note the parentheses in "BluetoothA2DPSink() is not public in 'android.bluetooth.BluetoothA2dpSink'. Connot be accesed from outside package" — that is a reference to a constructor, not a class. Make sure the zero-argument constructor is public.
Try the below code. It is done using reflection. You can not simply create an object by calling the constructor for BluetoothA2DPSink. You also need to use another class BluetoothProfile.java.
Object mBluetoothA2DPSink;
/**
* This function will connect to A2DPsink profile of the server device to manage audio profile connection
*/
public void getBluetoothA2DPsink() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
try {
final int A2DPprofile = BluetoothProfile.class.getField("A2DP_SINK").getInt(null);
BluetoothProfile.ServiceListener mProfileListener1 = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == A2DPprofile) {
mBluetoothA2DPSink = proxy;
}
}
public void onServiceDisconnected(int profile) {
if (profile == A2DPprofile) {
mBluetoothA2DPSink = null;
try {
mContext.unregisterReceiver(mA2DPReciever);
} catch (IllegalArgumentException e) {
Log.e(TAG, e.getMessage());
}
}
}
};
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(mContext, mProfileListener1, A2DPprofile);
} catch (NoSuchFieldException | IllegalAccessException e) {
Log.e(TAG, e.getMessage());
}
}
My Jgroups config file contains the protocol/config
<FD timeout="3000" max_tries="3" />
But how do I use this in the Java code. For example, if there is a cluster and when I detect a failure I want to call an external notifier service via a REST call, like /nodeDown/nodeID
I'm not able to find any java code which does this, all I see is message receive and send, is there a way I can implement this?
Thanks
Adding some more info
I have done the step of writing a RecieverAdpater and override the start, stop, send, recieve method. Please find some code here,
public void receive(Message msg) {
JGroupsDataPacket pckt = (JGroupsDataPacket) msg.getObject();
if ( pckt.getCmd().equals("cacheUpdate") ){
int uid = pckt.getAffectedUid();
cacheUpdateRoutine(uid);
}
if ( pckt.getCmd().equals("ack") ){
System.out.println("got the mesaage!");
}
logger.log(LogLevel.ERROR, "received msg from " + msg.getSrc() + ": " + msg.getObject());
}
public void send(JGroupsDataPacket pckt){
Message msg = new Message(null, null, pckt);
msg.setFlag(Message.Flag.RSVP);
try {
channel.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
I want to know where should I add code for example to handle the TimeOutException when I'm sending a message with the RSVP flag enabled. Another requirement is to know, which is the Java callback method which is called when SUSPECT(P) is triggered. I want to catch and handle the machine's going down, timout etc.
Is the viewAccepted() the only place where I can handle this? Is there a sample code around this?
Also is http://www.jgroups.org/manual/html/user-channel.html
the section 3. APIs give all java/programmatic things we can do with JGroups.
Thanks again
I found some documentation here, I think this is the class which I'm supposed to override
public interface MembershipListener {
void viewAccepted(View new_view);
void suspect(Object suspected_mbr);
void block();
void unblock();
}
OK, first off, you have a JChannel. You need to use it to register for view callbacks, like this:
JChannel ch;
ch.setReceiver(this);
'this' extends ReceiverAdapter and overrides viewAccepted():
public void viewAccepted(View view) {
// handle new view
}
To determine the members which left between views v1 and v2:
List<Address> left_mbrs=View.leftMembers(v1,v2);
I have Java-related question:
I want to know is there a way to create path to class (in program) by using a variable(s).
Im making a program that will download pictures from certain sites and show them to a user. However, different sites have different forms, that's why I have to define a series of functions specific to each. They cannot be put in the same class because functions that preform same job (just for another site) would have to have same names. I'm trying to make adding support for another site later as simple as possible.
Anyway, the question is, could I call a function in program using a variable to determine its location.
For example: code.picturesite.functionINeed();
code is the package containing all of the coding, and picturesite is not a class but rather a variable containing the name of the desired class - that way I can only change value of the variable to call a different function (or the same function in a different class).
I don't really expect that to be possible (this was more for you to understand the nature of the problem), but is there another way to do what I'm trying to achieve here?
Yes, there is a way. It's called reflection.
Given a String containing the class name, you can get an instance like this:
Class<?> c = Class.forName("com.foo.SomeClass");
Object o = c.newInstance(); // assuming there's a default constructor
If there isn't a default constructor, you can get a reference to one via c.getConstructor(param1.getClass(), param2.getClass(), etc)
Given a String containing the method name and an instance, you can invoke that method like this:
Method m = o.getClass().getMethod("someMethod", param1.getClass(), param2.getClass(), etc);
Object result = m.invoke(o, param1, param2, etc);
I'm not immediately seeing anything in your question that couldn't be solved by, instead of having a variable containing a class name, having a variable containing an instance of that class -- to call a function on the class, you would have to know it implements that function, so you could put the function in an interface.
interface SiteThatCanFoo {
void foo();
}
And
class SiteA extends Site implements SiteThatCanFoo {
public void foo() {
System.out.println("Foo");
}
}
Then:
Site currentSite = getCurrentSite(); // or getSiteObjectForName(siteName), or similar
if (SiteThatCanFoo.isAssignableFrom(currentSite.class)) {
((SiteThatCanFoo)currentSite).foo();
}
So you want to do something like this (check ImageDownloader.getImageFrom method)
class SiteADownloader {
public static Image getImage(URI uri) {
System.out.println("invoking SiteADownloader on "+uri);
Image i = null;
// logic for dowlnoading image from siteA
return i;
}
}
class SiteBDownloader {
public static Image getImage(URI uri) {
System.out.println("invoking SiteBDownloader on "+uri);
Image i = null;
// logic for dowlnoading image from siteB
return i;
}
}
// MAIN CLASS
class ImageDownloader {
public static Image getImageFrom(String serverName, URI uri) {
Image i = null;
try {
// load class
Class<?> c = Class.forName(serverName + "Downloader");
// find method to dowload img
Method m = c.getDeclaredMethod("getImage", URI.class);
// invoke method and store result (method should be invoked on
// object, in case of static methods they are invoked on class
// object stored earlier in c reference
i = (Image) m.invoke(c, uri);
} catch (NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException | ClassNotFoundException e) {
e.printStackTrace();
}
return i;
}
// time for test
public static void main(String[] args) {
try {
Image img = ImageDownloader.getImageFrom("SiteB", new URI(
"adress"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}