Why does a wildcard not work in java code below?
My request looks like http://localhost:8080/App/DataAccess?location=Dublin
rob#work:~$ ls /usr/local/CustomAppResults/Dublin/*/.history
/usr/local/CustomAppResults/Dublin/team1/.history
/usr/local/CustomAppResults/Dublin/team2/.history
/usr/local/CustomAppResults/Dublin/team3/.history
Servlet code (DataAccess.java).
(DataAccess.java:27) refers to the for loop ..
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File[] files = finder("/usr/local/CustomAppResults/" +
request.getParameter("location") + "/*/");
for (int i = 0; i < files.length; i++){
System.out.println(files[i].getName());
}
}
private File[] finder(String dirName) {
File dir = new File(dirName);
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.endsWith(".history");
}
});
}
Error:
The server encountered an internal error that prevented it
from fulfilling this request.
java.lang.NullPointerException
com.example.servlets.DataAccess.doGet(DataAccess.java:27)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
The method public File[] listFiles(FilenameFilter filter)
Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
(http://docs.oracle.com/javase/7/docs/api/java/io/File.html)
So, why do you get this situation? You are trying to use a wildcard char (*) that is evaluated by your shell, but won't be evaluated in new File(path). The new File(path) constructor only works for exact paths.
Things like DirectoryScanner (Apache Ant) or FileUtils (Apache commons-io) will solve your problem. See the comments above for further details on possible solutions, including the Java 7 NIO approach (Files.newDirectoryStream( path, glob-pattern )).
Related
My problem is, that I want to list all the images what is located
project/src/main/webapp/images
I know if I know the image(s) name(s) I can make an URL like this:
assetSource.getContextAsset(IMAGESLOCATION + imageName, currentLocale).toClientURL();
But what if I dont know all the images name?
Thanks for the answers in advance!
The web app (and tapestry as well) doesn't know/care about absolute path of files, as it could be deployed anywhere.
You can get absolute path of some file by calling getRealPath of HttpServletRequest.
#Inject
private HttpServletRequest request;
...
// get root folder of webapp
String root = request.getRealPath("/");
// get abs path from any relative path
String abs = root + '/' + relPath;
getRealPath of HttpServletRequest is deprecated, it's recommended to use ServletContext.getRealPath instead but it's not so easy to get ServletContext.
I prefer to use WebApplicationInitializer implementation
public class AbstractWebApplicationInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Here we store ServletContext in some global static variable
Global.servletContext = servletContext;
....
}
You basically need the ability to read files in a given folder. Here's some very basic code that will iterate through all of the files in a folder:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
}
// else, it's a directory
}
All of the imports should be from the java.io package.
I am using Tess4j API for performing OCR and have created a dynamic web project in eclipse. If I create a new java class directly under the Java resources folder, the code is working fine.
public static void main(String[] args){
File image = new File("Scan0008.jpg");
ITesseract instance = new Tesseract();
try{
String result = instance.doOCR(image);
System.out.println(result);
}catch(TesseractException e){
System.err.println(e.getMessage());
}
}
However I am getting an exception when I am calling the same code from my Servlets doPost method.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Validate valObj = new Validate();
valObj.validate();
}
public void validate() {
File image = new File("Scan0008.jpg");
ITesseract instance = new Tesseract();
try {
String result = instance.doOCR(image);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
I have included all the required jars under lib folder of WEB-INF. Have also added the jars in the projects build path. Could anyone please let me know what I am doing wrong.
Exception :
java.lang.IllegalStateException: Input not set
23:33:45.002 [http-bio-8080-exec-5] ERROR net.sourceforge.tess4j.Tesseract - Input not set
java.lang.IllegalStateException: Input not set
I think your current directory is different when you are calling from servlet. the current directory is you tomcat bin folder. so when you are calling like this:
File image = new File("Scan0008.jpg");
your scan0008.jpg must be put in bin folder of tomcat or you must use absolute path of your file.
Following ModifyXML Java class is used to read an XML file and to return all the values of specified tag's "name" attribute.
For below XML file it should return a ArrayList<String> that cantains tc_001 and tc_002.
<root>
<tc name="tc_001">
</tc>
<tc name="tc_002">
</tc>
</root>
First I created the class in a separate Java project in Eclipse with a main method which creates a new ModifyXML object and calls getTCs() method using that object. The file structure is this. In that project i used directly file path as "test.xml", which cause no error at run time.
public class ModifyXML {
/*
* constructor
* initializing main objects
*/
public ModifyXML() {
//this is the file path i used
filePath = "test.xml";
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
document = builder.parse(filePath);
}
/*
*getTCs method
*/
public ArrayList<String> getTCs(String tagType) {
ArrayList<String> tcList = new ArrayList<>();
String attributeName = "name";
NodeList nodes = document.getElementsByTagName(tagType);
int j = nodes.getLength();
for(int i = 0; i < j; i++){
Node tc = nodes.item(i);
if(tc.getNodeType() == Node.ELEMENT_NODE){
String tcName = tc.getAttributes().getNamedItem(attributeName).getNodeValue();
tcList.add(tcName);
}
}
Iterator<String> iter = tcList.iterator();
while(iter.hasNext())
System.out.println(iter.next());
return tcList;
}
public static void main(String[] args) {
ModifyXML a = new ModifyXML();
a.getTCs("tc");
}
Then i copied that class to a Dynamic Web Page project's src folder and test.xml file to the Dynamic Web Page project, then I removed main method of the class. File structure of Dynamic Web Page project is this. But when i call getTCs() method, in side servlet's service() method, an exception is occurred.
java.io.FileNotFoundException: /home/srinesh/test.xml (No such file or directory)
I'm using Ubuntu and /home/srinesh/ is my home directory. My project directory for Dynamic Web Page project is /home/dazz/Projects/workspace/Sanitizor/. Why that class looking for the test.xml file in my home directory only when the class is located in a Dynamic Web Page project?
Servlet class is showed below.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
ModifyXML xml = new ModifyXML("test.xml");
ArrayList<String> tc = xml.getTCs("tc");
Using relative path is not a good idea, as you see sometimes you may run the project from different directories.
So either use absolute path ("/some/path/to/your/file/file.xml") to the file, or use a classpath to read it, e.g.:
document = builder.parse(ModifyXML.class.getResourceAsStream("/" + filePath);
In the second case, you have to put the file at the root of your classpath.
I'd like to test my servlet by printing the results to the console. System.out.println does not seen to work for a servlet. Does anyone know how I can achieve this? Main purpose is for debugging at a later stage.
public class GetAllStaff extends HttpServlet {
private static final long serialVersionUID = 1L;
static StaffDAO dao = new StaffDAO();
static ArrayList<Staff> sList = null;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
sList = dao.getAllStaff();
for (int i = 0; i < sList.size(); i++)
{
}
}
You could use
ServletContext context = getServletContext( );
context.log("This is a log item");
The logs are not printed in Eclipse console but can be found at logs folder of servlet container (say Apache Tomcat)
Reference: http://www.tutorialspoint.com/servlets/servlets-debugging.htm
You may want to print everything on a browser with the following code?
PrintWriter out = res.getWriter();
out.println("Some information on the browser...");
P.S I tried System.out.println("something"); in my IDE (Intellij), the result showed up in the console.
I'm writing code for a music player in Java FX, I use the MediaPlayer class, which is initialized by a Media class. So far I think that the sources for the Media constructors must be URI in Strings, so I've writen this code for adding a list of song files to a playlist and so playing such list:
public void setPlaylist (List<File> lista) {
songsList.clear();
for (File s : lista) {
songsList.add(s.toURI());
}
}
This works fine. However, when I want to get a File containing the path of a folder, and inputing each file's name in URI format I get some trouble, this is what I've tried so far:
public void setPlaylist (File folder) {
songsList.clear();
for (String s : folder.list()) {
try {
songsList.add(new URI("file:///" + (folder + "\\" + s).replace("\\", "/").replaceAll(" ", "%20")));
} catch (URISyntaxException ex) {
Logger.getLogger(PlayList.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I'm getting error logs like this:
SEVERE: null java.net.URISyntaxException: Illegal character in path at
index 78:
file:///C:/Users/Diego%20Aguilar/Music/3%20Grandes%20de%20la%20Banda/AlbumArt_{9AEABE24-F5A2-441C-A71A-D061E000A9BA}_Large.jpg
Use File#toURI() as you were using before to avoid running into encoding issues and make use of a FilenameFilter to restrict the list to media files only. Here's how the code would look then.
public void setPlaylist (File folder) {
songsList.clear();
File[] musicFiles = folder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".m4a"));
}
});
for (File file : musicFiles) {
songsList.add(file.toURI());
}
}
See JavaDocs: FilenameFilter, File#toURI()
Instead of using String s : folder.list() use File s : folder.listFiles() ... then use the URL from the files.
Your file URI contains an angular bracket {, which is causing SEVERE: null java.net.URISyntaxException
You need to have a valid file path to create a proper URI.
Here is the link to URI RFC for referring what is allowed and what is not allowed in a URL.