Get the path of my project's folder - java

In build a web application with netbeans, in some point I extract an arrayList to json format.
public void convertToJSON(ArrayList list){
ObjectMapper mapper = new ObjectMapper();
try{
mapper.writeValue(new File("C:\\temp\\data.json"), list);
}catch(JsonGenerationException e){
e.printStackTrace();
}catch(JsonMappingException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
and this creates the file C:\temp\data.json. How can I create this file inside my project folder where JSPS's exist? I tried determine the location with
String dir = System.getProperty("user.dir");
but this created the file in C:\Program Files\Apache Software Foundation\Apache Tomcat 8.0.15\bin. I want to create the file inside the projects folder in order to use it to show my data in bootstrap table. There I define the location of my data by
data-url="data.json"
I tried this data-url="C:\temp\data.json" but i got an error
XMLHttpRequest cannot load file:///C://temp//data.json?order=desc&limit=10&offset=0. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

This is cross domain problem, bootstrap table does not support file:// url, please use an web server to run your code. Here is a issue can help you: https://github.com/wenzhixin/bootstrap-table/issues/230

To get a File inside the project's folder you can use
URL resourceUrl = this.getClass().getResource("");
File file = new File(resourceUrl.toURI().toString() + "data.json");

Related

FileNotFoundException while getting file from resources folder using getResource()

I need to get this file from the resources folder in the File object, not in InputSream.
I am using below code, working file on eclipse but FoleNotFoundException on the server. )Using AWS EC2)
Code:
URL res = ResidentHelperService.class.getClassLoader().getResource("key.pem");
System.out.println("resource path2 :" + res);
File privateKeyFile = Paths.get(res.toURI()).toFile();
After printing path looks like:
:jar:file:/home/centos/myproject/microservices/user-service/target/user-service-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/project-common-utility-0.0.1-SNAPSHOT.jar!/key.pem
I have added dependency on the common jar to user service pom.
Please help me to get the file from resources of a common project.
If you have your file in resources folder, the easiest way to access it from the code is probably to use org.springframework.util.ResourceUtils class that Spring provides:
try {
final File file = ResourceUtils.getFile("classpath:key.pem");
....
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Perhaps this way can help you with your issue.

loading resource works locally but not on server

First of all i've tried my code by extracting the war file (using maven) on both eclipse and on a tomcat 8.0.33 stand alone on my mac.
I have also tried my code on a windows server 2008 with the same java version 1.8, and it works when i put some variable (which are username and password) hardcoded, but when i make the code to read them from a reousrce file, it is just working on my mac (both eclipse and tomcat stand alone), but not on the server
this is the code to read the resource
private static String getUsername() {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(MyConfiguration.class.getClassLoader()
.getResource("configuration.properties").getFile());
// load a properties file
prop.load(input);
// get the property value and print it out
return prop.getProperty("username");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
where the location of the configuration.properties is in the src/main/resources and on the server, i can see that file is in the correct directory.
i am using maven, i don't know what other information you need to help me, but if you say, i will give you
You may try
input = Thread.currentThread().getContextClassLoader().getResourceAsStream("configuration.properties");
Open your war and the jar file that contains your application. Ensure that the resource you are trying to open is in the jar (in the war) that is getting deployed. Most of the times this has happened to me, it's because I failed to tell my build process that this file needed to be copied over to the deployment. Class files go automatically, but not always resource files.

How to read the resource file? (google cloud dafaflow)

My Dataflow pipeline needs to read a resource file GeoLite2-City.mmdb. I added it to my project and ran the pipeline. I confirmed that the project package zip file exists in the staging bucket on GCS.
However, when I try to read the resource file GeoLite-City.mmdb, I get a FileNotFoundException. How can I fix this? This is my code:
String path = myClass.class.getResource("/GeoLite2-City.mmdb").getPath();
File database = new File(path);
try
{
DatabaseReader reader = new DatabaseReader.Builder(database).build(); //<-this line get a FileNotFoundException
}
catch (IOException e)
{
LOG.info(e.toString());
}
My project package zip file is "classes-WOdCPQCHjW-hRNtrfrnZMw.zip"
(it contains class files and GeoLite2-City.mmdb)
The path value is "file:/dataflow/packages/staging/classes-WOdCPQCHjW-hRNtrfrnZMw.zip!/GeoLite2-City.mmdb", however it cannot be opened.
and This is the options.
--runner=BlockingDataflowPipelineRunner
--project=peak-myproject
--stagingLocation=gs://mybucket/staging
--input=gs://mybucket_log/log.68599ca3.gz
The Goal is transform the log file on GCS, and insert the transformed data to BigQuery.
When i ran locally, it was success importing to Bigquery.
i think there is a difference local PC and GCE to get the resource path.
I think the issue might be that DatabaseReader does not support paths to resources located inside a .zip or .jar file.
If that's the case, then your program worked with DirectPipelineRunner not because it's direct, but because the resource was simply located on the local filesystem rather than within the .zip file (as your comment says, the path was C:/Users/Jennie/workspace/DataflowJavaSDK-master/eclipse/starter/target/classe‌​s/GeoLite2-City.mmdb, while in the other case it was file:/dataflow/packages/staging/classes-WOdCPQCHjW-hRNtrfrnZMw.zip!/GeoLite2-City.mmdb)
I searched the web for what DatabaseReader class you might be talking about, and seems like it is https://github.com/maxmind/GeoIP2-java/blob/master/src/main/java/com/maxmind/geoip2/DatabaseReader.java .
In that case, there's a good chance that your code will work with the following minor change:
try
{
InputStream stream = myClass.class.getResourceAsStream("/GeoLite2-City.mmdb");
DatabaseReader reader = new DatabaseReader.Builder(stream).build();
}
catch (IOException e)
{
...
}

working with files in dynamic web project

I am working on a dynamic web project.
On submit button click (present on my form)I want to create a new file and put some data inside.
I have written only these two lines and I am getting failure to create file
try{
File file = new File("C:/database.txt");
file.createNewFile();
}catch(Exception e){
return "error in creating file";
}
If I run the enire code in normal java class everything works fine. Why so?
Your web project is working on application server. The web application can manage files, which are on that server. Other files are not accessible. (of course localhost server is on your computer, but that it's path is not "C:/", so you can't write there). You can find the path of your server running this code (it also create a test file):
String pathWhereYouFindYourFile = new File("").getAbsolutePath();
System.out.println(pathWhereYouFindYourFile);
File f = new File("test.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}

Get the files of an directory in the web

I have a homepage, which has a directory for downloads.
I want to read all files of this homepage automatically, from its directory.
For example I have the homepage: www.homepage.org and the subdirectory resources/downloads with the download files I want to show.
I have a Java Server with Spring and JSPs running and tried the following, which didn't work at all:
String path = request.getContextPath();
path += DOWNLOADS;
URL url = null;
String server = request.getServerName();
try {
url = new URL("https", server, request.getLocalPort(), path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url != null) {
String externalForm = url.toExternalForm();
File directory = new File(externalForm);
String[] files = directory.list();
for (String file : files) {
;
}
}
You can use a Servlet. If your resources directory is in your web app's root directory, then use
PrintWriter writer = response.getWriter();
String path = getServletContext().getRealPath("/resources/downloads");
File directory = new File(path);
if(directory.isDirectory()){
String[] files = directory.list();
for (String file : files) {
writer.write(file + "<br/>");
}
} else writer.write(directory.getAbsolutePath() + "could not be found");
I found a solution with using a FTP manager...
You can view the code here
I hope it will help you resolve the problem.
You need to list the directory using the path to the directory not the url. Once you retrieve the files you must create your own html to put it your web if that's what you want.
There is a good example to create a directory listing and browsing with JQuery here
There is a JSP connector included in the package in the download section that you may need to tune up a bit if you don't want to use the JQuery tree.
good luck!
The HTTP protocol does not provide a way to list the "files" in a "directory". Indeed, from the perspective of the protocol spec, there is no such thing as a directory.
If the webserver you are trying to access supports WebDAV, you could use PROPFIND to find out a collection (i.e. directory)'s structure.
Alternatively, if the webserver has directory listing enabled (and there is no index.html or whatever) then you could screen-scrape the listing HTML.
Otherwise, there is no real solution ... using HTTP / HTTPS.
On rereading the question and the answers, it strikes me that the servlet that is trying to retrieve the directory listing and the servlet that hosts the directories could actually be running on the same machine. In that case, you may have the option of accessing the information via the file system. But this will entail the "client" servlet knowing how the "server" servlet represents things. The URLs don't (and cannot) provide you that information.
The answer provided by rickz is one possible approach, though it only works if the client and server servlets are in fact the same servlet.

Categories

Resources