How to playback Wiremock in java? - java

I have been trying to playback the recordings in java that are done before .I gave my path to mappings and recordings to WiremockServer and then used enableRecordMappings() method for recording .It is able to record mappings in my specified path. But when I try to playback with new server, how to tell it to look for my path for recordings?
I even copied my mappings and __files folders into WEB-INF/wiremock as said in documentation,but it is not replaying.Can some one help me here?
I am using below code for recording
WireMockServer wmServer = new WireMockServer(httpPort, httpsPort);
wmServer.enableRecordMappings(mappings, files);
wmServer.stubFor(any(urlMatching(".*")).willReturn(aResponse().proxiedFrom("https://10.122.45.65")));
wmServer.start();
I am taking inputs from a xml file .All variables are initialized correctly.

try this
wmServer.loadMappingsUsing(new JsonFileMappingsSource(mappings));
the problem, it need to have files in folder ~/test/resources/__files/*

Related

Groovy: Save gform input type file to the assets pipeline (or similar)

(Sorry if this is simple; this is my first post)
Is the groovy/grails asset pipeline modifiable at runtime?
Problem: I am creating an application where users create the objects. The objects are stored as text files so that only the necessary objects are built at runtime. Currently, the text file includes a string which represents the filename of the image. The plan was to have these images stored in assets/images/ as this works best for later displaying the object. However, now I am running into issues with saving files to assets/images/ at run time, and I can't even figure out if this is possible. *Displaying images already works in the way I require if I drag and drop the images into the desired folder, however I need a way for the controller to put the image there instead. The relevant section of controller code:
def folder = new File("languageDevelopment/grails-app/assets/images/")
//println folder
def f = request.getFile('keyImage');
if (f.empty)
{
flash.message = 'file cannot be empty'
render(view: 'create')
return
}
f.transferTo(folder)
The error I'm receiving is a fileNotFoundException
"/var/folders/9c/0brqct9j6pj4j85wnc5zljvc0000gn/T/languageDevelopment/grails-app/assets/images (No such file or directory)"
on f.transferTo(folder)
What is the section it is adding to the beginning of my "folder" object?
Thanks in advance. If you need more information or have a suggestion to a different route please let me know!
new File("languageDevelopment/grails-app/assets/images/")
This folder is present only in your sources
After deployment it will looks like "/PATH-TO-TOMCAT/webapps/ROOT/assets/" if you use tomcat.
Also asset/images, asset/font etc. will be merged to assets folder.
If you'd like to store temporary files you can create some directory under src/resources folder.
For example "src/resources/images"
And you can get access to this folder from classloader:
this.class.classLoader.getResource('images/someImage.png').path

Extracting files from res folder in Executable JAR (txt files to be specific)

I would like to ask if its possible to put text files into my jar, I use them to make my map in my game, but users can get Highscores. now I want to save the Highscores with the map, so I have to save the map on the user their PC. Is there any way how I could do this? I've searched the internet for some ideas but I could not find anything that even came close to what I've wanted. I only had 3/4th of a year java so I don't know much about these things, everything that happens outside the debug of eclipse are problems for me(files are mainly one of those things, null exceptions, etc).
The main question now.
Is it possible to do? If yes, do you have any terms I could search on, or some sites/guides/tutorials? If no, is there any other way how I could save the highscores?
EDIT:
to make clear
Can I get the text file (the text inside the file) to be extracted to a different file in like the home directory of my game (where I save the settings and stuff) the basic maps are inside the jar file, so I want them to be extracted on the first start-up of the program
Greetings Carolien
"extracted to a different file in like the home directory of my game (where i save the settings and stuff) the basic maps are inside the jar file, so i want them to be extracted on the first startup of the program"
You can get the URL by using getClass().getResource()
URL url = getClass().getResource("/res/myfile.txt");
Then create a File object from the URI of the URL
File file = new File(url.toURI());
Then just perform your normal file operations.
if (file.renameTo(new File(System.getProperty("user.home") + "\\" + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
Assuming your file structure is like below, it should work fine
ProjectRoot
src
res
myfile.txt
Note: the above is moving the entire file. If you want to extract just the data inside the file, then you can simple use
InputStream is = getClass().getResourceAsStream("/res/myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The just do normal IO operation with the reader. See here for help with writing the file.

FileTransfer "Saved file:" followed by FileNotFoundException

My app downloads a zip file from a remote webserver, then extracts it.
The javascript successfully calls FileTransfer, which logs:
FileTransfer Saved file: file:///data/data/com.yadda.yadda/update.zip
As part of the success function, javascript calls my custom update plugin which immediately tests for the file:
Context ctx = this.cordova.getActivity().getBaseContext();
File update = new File(ctx.getFilesDir(),"update.zip");
if(!update.exists()) Log.w("File not found",update.getAbsolutePath());
The log for that last line is:
File Not Found /data/data/com.yadda.yadda/update.zip
Later in a try/catch block I have an InputStream variable created and one of the catch blocks is a FileNotFoundException which is firing every time.
Begin edit - more info
The FileNotFoundException has an interesting bit. The file path is wrong - even though I'm sending the same "update" variable to create the FileInputStream
InputStream fileis = new FileInputStream(update);
And the interesting bit of the exception:
Caused by: java.io.FileNotFoundException: /data/data/com.yadda.yadda/files/update.zip
End edit
What is going wrong here? Cordova logs that the file transfer completed and the file was saved, but then the file doesn't exist when I test for it! When I create the FileInputStream, why is the path different, causing the exception?
What am I missing? Everything works fine in the IOS version of the app.
Edit 2: per request, I browsed the device filesystem and found that update.zip does indeed exist in /data/user/0/com.yadda.yadda
OK, somewhere there is a bug. I'm inclined to believe it's a bug in getAbsolutePath() because I'm seeing consistent operation elsewhere.
When I create the "File update" variable, then immediately test and log the update.getAbsolutePath() - it shows the correct path. But when I attempt to create the FileInputStream, the path is different (+ /files/)
So, a little searching and I found that in order to access the application data directory (without /files) I must send a different directory with the new File command. Here's what it looks like:
File update = new File(ctx.getApplicationInfo().dataDir,"update.zip");
Obtaining the dir with getFilesDir()
ctx.getFilesDir() = /data/data/com.yadda.yadda/files
Obtaining the correct dir
ctx.getApplicationInfo().dataDir = /data/data/com.yadda.yadda

Save all files from a folder in a jar

First:
I know, this question was asked about 100 times already.
I know, someone already could have gave the right answer.
But anyway, I have to ask this again. I didn't found a solution working for me. sorry.
I'm writing a game in java. Of course I have many packages (folders) with sounds and pictures and so on. But these folders are each of variable size. So I want to save the content of such a folder dynamically in a list.
Usually, I was making this:
File f[] = new File(getClass.getResource("/home/res/").toURI()).listFiles();
Now I can iterate though this file object and save each file. Perfect. Really?
No. When I extract this Project into a jar archive, this fails. All because a uri isn't "hierarchical" or some stuff like this. See this exception:
C:\Users\Administrator\Desktop>java -jar Homework.jar
java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(Unknown Source)
at homework.moonface.src.Moonface.loadSounds(Moonface.java:94)
at homework.moonface.src.Moonface.<init>(Moonface.java:55)
at control.Overview.main(Overview.java:16)
Ok, I thought, so I need to get this path and add it manual into the file object. (new File("path"); But... this doesn't work. I'm getting the known error that the input wasn't written correctly, or when i try to cut of "file:" from the resource url, it breaks because in a jar its "jar:file:" and not "file:". But also if I cut of jar:file: I'm getting null.
So, please don't mark this as a duplicate, and try to explain this shortly for me. It would help thousand other, who don't understand other solutions who aren't solutions.
Try this :
URL jarResourceURL = getClass().getResource("/home/res/");
JarURLConnection jarURLConnection = (JarURLConnection) jarResourceURL.openConnection();
Enumeration<JarEntry> entries = jarURLConnection.getJarFile().entries();
while (entries.hasMoreElements()){
entries.nextElement(); // iterate over entries and do something
}
UPD: I was thinking about how spring framework's ClassPathXmlApplicationContext resolves the resources from jars. So i investigated the source code and foud that there is an utility class org.springframework.core.io.ClassPathResource which have a convenient interface (moreover there is a possibility to get the corresponding java.io.File instance using it) and can help you to solve the problem. Here is the doc :
http://docs.spring.io/spring/docs/2.5.x/api/org/springframework/core/io/ClassPathResource.html

Java: find current working JAR

I know that the system property "user.dir" returns the current working directory; the directory containing that file that is currently running.
I am wondering, how would I be able to go one step farther? I need to find the current working file. I am writing a little app that is kind of like an auto-updater, and I need to know the file that needs to be updated. For example, if I run a file from C:/test.jar I want to actually know, in code, that the current location of the file that is running is C:/test.jar so that I can write (new) data to it.
I've tried an approach like this:
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("Test.class"));
However, it prints out:
3/5/12 7:50:16.914 PM [0x0-0x31031].com.apple.JarLauncher: rsrc:Test.class
(I am running this on a Mac - I got that line from the Console).
Any help is greatly appreciated. Thanks!
With credits to Fab in the following post:
Jar path+name from currently running jar
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
This will print the current file's path.
File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
System.out.println(f.getPath());

Categories

Resources