I am developing an desktop application which reads specific XML Elements using XPath and displays them in text fields in a JFrame.
So far, the program ran smoothly until I decided to pass a String variable in the File class.
public void openNewFile(String filePath) {
//file path C:\\Documents and Settings\\tanzim.hasan\\my documents\\xcbl.XML
//is passed as a string from another class.
String aPath = filePath;
//Path is printed on screen before entering the try & catch.
System.out.println("File Path Before Try & Catch: "+filePath);
try {
//The following statement works if the file path is manually written.
// File xmlFile = new File ("C:\\Documents and Settings\\tanzim.hasan\\my documents\\xcbl.XML");
//The following statement prints the actual path
File xmlFile = new File(aPath);
System.out.println("file =" + xmlFile);
//From here the document does not print the expected results.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
XPath srcPath = XPathFactory.newInstance().newXPath();
XPathShipToAddress shipToPath = new XPathShipToAddress(srcPath, doc);
XPathBuyerPartyAddress buyerPartyPath = new XPathBuyerPartyAddress(srcPath, doc);
} catch (Exception e) {
//
}
}
If I define the xmlFile with a static path (i.e. manually write it) then the program works as expected. However, instead of writing a static path, if I pass the path as a string variable aPath it does not print the expected results.
I have done a bit of googling but failed to find anything concrete.
Just use the builtin object methods:
System.out.println("file = "+xmlFile.toString());
You could also use:
System.out.println("f = " + f.getAbsolutePath());
Also, if you're having issues wit hthe file not existing, check first then proceed:
File file = new File (aPath);
if(file.exists()) {
//Do your work
}
If you are using replaceAll() like this path.replaceAll("\\", "/") to remove the backslashes, it will fail because the replaceAll() method expects a regex as the first parameter and a single backslash (coded as "\\") is an invalid regex. To make it work using replaceAll(), you would need double-escape the backslash (once for the String, again for the regex) like this path.replaceAll("\\\\", "/").
However, you don't need a regex! Instead, use the plain-text based replace() method like this:
path.replace("\\", "/")
Note that the names "replace" and "replaceAll" are misleading: "replace" still replaces all occurrences... the moron that decided on the name "replaceAll" should have chosen "replaceRegex" or something similar
Edit
Try:
path = path.replace("\\\\", "/");
it is too late to answer this but...removing "" from my config file helped
I mean
pathVariable=c:\\some\\path\\here
not this
pathVariable="c:\\some\\path\\here"
Related
This is a non-xpages application.
I have inherited some code that I need to tweak....this code is used in a drag&drop file attachment subform. Normally, this will create a document in a separate dedicated .nsf that stores only attachments, and uses the main document's universalid as a reference to link the two....I need to change what the reference is to the value in a field already on the main document (where the subform is).
Java is challenging to me, but all I need to do is GET the value of the field from the main document (which has not necessarily been saved yet) and write that string value onto the attachment doc in that storage database, so I think I am just needing help with one line of code.
I will paste the relevant function here and hopefully someone can tell me how I get that value, or what else they need to see what is going on here.
You can see my commented-out attempt to write the field 'parentRef' in this code
...
private void storeUploadedFile( UploadedFile uploadedFile, Database dbTarget) {
File correctedFile = null;
RichTextItem rtFiles = null;
Document doc = null;
String ITEM_NAME_FILES = "file";
try {
if (uploadedFile==null) {
return;
}
doc = dbTarget.createDocument();
doc.replaceItemValue("form", "frmFileUpload");
doc.replaceItemValue("uploadedBy", dbTarget.getParent().getEffectiveUserName() );
Utils.setDate(doc, "uploadedAt", new Date() );
doc.replaceItemValue("parentUnid", parentUnid);
//doc.replaceItemValue("parentRef", ((Document) dbTarget.getParent()).getItemValue("attachmentDocKey"));
//get uploaded file and attach it to the document
fileName = uploadedFile.getClientFileName();
File tempFile = uploadedFile.getServerFile(); //the uploaded file with a cryptic name
fileSize = tempFile.length();
targetUnid = doc.getUniversalID();
correctedFile = new java.io.File( tempFile.getParentFile().getAbsolutePath() + java.io.File.separator + fileName );
//rename the file on the OS so we can embed it with the correct (original) name
boolean success = tempFile.renameTo(correctedFile);
if (success) {
//embed original file in target document
rtFiles = doc.createRichTextItem(ITEM_NAME_FILES);
rtFiles.embedObject(lotus.domino.EmbeddedObject.EMBED_ATTACHMENT, "", correctedFile.getAbsolutePath(), null);
success = doc.save();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
com.gadjj.Utils.recycle(rtFiles, doc);
try {
if (correctedFile != null) {
//rename the temporary file back to its original name so it's automatically
//removed from the os' file system.
correctedFile.renameTo(uploadedFile.getServerFile());
}
} catch(Exception ee) { ee.printStackTrace(); }
}
}
}
...
dbTarget.getParent does not do what you think it does. It returns a Session object that is the parent session containing all your objects. Casting it to (Document) won't give you your main document.
I don't see the declaration for it, but you appear to have a variable available called parentUNID. You can use it to get a handle on the main document.
You need to use the parentUNID value in a call to getDocumentByUNID() in order to retrieve the Document object representing your main document. But in order to do that, you need the Database object for the nsf file containing the main document, and if I understand you correctly, that is a different database than targetDb.
I'm going to have to assume that you already have that Database object in a variable called parentDb, or that you know the path to the NSF and can open it. In either case, your code would look like this (without error handling):
Document parentDoc = parentDb.getDocumentByUNID(parentUNID);
doc.replaceItemvalue("parentRef", parentDoc.getItemValue("attachmentDocKey"));
i have multiple xml files named media01.xml, media02.xml and so on.
I have written one java code which parses this xml file and fetches its table name and renames xml file. eg: media01--> Records.xml, media02 --> Info.xml and so on.
Part of that code is as follows:
File inputFile = new File(path+File.separator+"media0"+xmlval+".xml");
if(inputFile.exists())
{
try{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
aaaa a= new aaaa();
saxParser.parse(inputFile, a);
String abc = aaaa.nsList();
File dest = new File(path+File.separator+abc+".xml");
inputFile.renameTo(dest);
xmlval++;
}
catch(Exception e)
{
System.err.println(""+e);
}
}
and the function which i am calling is:
class aaaa extends DefaultHandler {
boolean bFirstName = false;
boolean bLastName = false;
boolean loc = false;
String name = null;
static String ans;
#Override
public void startElement(String uri,String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("table")) {
name = attributes.getValue("name");
}
if(qName.equalsIgnoreCase("row")){
}
ans=name;
}
public static String nsList(){
return ans;
}
}
i deployed my project on server and when i run the project from ubuntu OS then the xml file names are getting changed but the same when i am running from windows then its not renaming the files. what might be the issue?
Pls help me out. Thanks in advance.
i don't thin it is a Parser problem since there is no problem and SAXParser is used by so many projects that depend on SAX to parse their configuration file such as Spring , jsf i think and so many others so it is unlikely to be a saxproblem so the problem can be i your call to
File dest = new File(path+File.separator+abc+".xml");
inputFile.renameTo(dest);
which is platform dependent instruction you better check if the renaming was done successfully by doing like this
File dest = new File(path+File.separator+abc+".xml");
boolean renameSuccess=inputFile.renameTo(dest);
System.out.println("renaming "+renameSuccess?"succeeded":"failed");
One of the problems I could encounter when deploying an application tested on a system to another system is that path and file names are case sensitive on Unix-like system. It is possible that your file already existed on your target system but with a different case. Anyway, as achabahe mentioned it, you should check your return value when you rename a file.
Another remark, path separators are system dependent but generally Java doesn't make any problem. You can for example use '/' in a Windows path. I just would suggest you to instantiate File objects this way:
File myFile = new File(myPath, myFileName);
This is so easier to read and system-independent.
I also suggest you to trace if you actually open the source file. By the way can't you run it in debug mode?
I have to modify some attributes in an XML file with Java.
The input XML has all attribute values surrounded with single quotes.
But after making all the changes in the document, when I save the document into a XML file all the attribute values are surrounded by double quotes.
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.output(doc, new FileWriter(path));
Is there any way that I can make the outputter use single quotes??
Thanks
Technically, yes.... but.... There is nothing semantically different between single and double quotes.... (the resulting document from JDOM is just as valid).... Is there a really good reason why you need to do this? If there is, I would be interested to know, and perhaps introduce it as a 'native' feature of JDOM....
But, you can change the format of it with (only) a little bit of work - 15 lines of code or so... The JDOM2 API in theory makes this a fair amount easier. You can create your own XMLOutputProcessor, using a subclass of the AbstractXMLOutputProcessor and override the printAttribute() method... for example (getting rid of some code paths that your are not likely to need (like non-escaped output):
private static final XMLOutputProcessor CUSTOMATTRIBUTEQUOTES = new AbstractXMLOutputProcessor() {
#Override
protected void printAttribute(final Writer out, final FormatStack fstack,
final Attribute attribute) throws IOException {
if (!attribute.isSpecified() && fstack.isSpecifiedAttributesOnly()) {
return;
}
write(out, " ");
write(out, attribute.getQualifiedName());
write(out, "=");
write(out, "'"); // Changed from "\""
// JDOM Code used to do this:
// attributeEscapedEntitiesFilter(out, fstack, attribute.getValue());
// Now we instead change to quoting the ' instead of "
String value = Format.escapeAttribute(fstack.getEscapeStrategy(), value);
// undo any " escaping that the Format may have done.
value = value.replaceAll(""", "\"");
// do any ' escaping that needs to be done.
value = value.replaceAll("'", "'");
write(out, value);
write(out, "'"); // Changed from "\""
}
};
Now that you have this cusome outputter, you can use it like:
XMLOutputter xmlOutput = new XMLOutputter(CUSTOMATTRIBUTEQUOTES);
xmlOutput.output(doc, new FileWriter(path));
I want to add a help screen to my Codename One App.
As the text is longer as other strings, I would like put it in a separate file and add it to the app-package.
How do I do this? Where do I put the text file, and how can I easily read it in one go into a string?
(I already know how to put the string into a text area inside a form)
In the Codename One Designer go to the data section and add a file.
You can just add the text there and fetch it using myResFile.getData("name");.
You can also store the file within the src directory and get it using Display.getInstance().getResourceAsStream("/filename.txt");
I prefer to have the text file in the filesystem instead of the resource editor, because I can just edit the text with the IDE. The method getResourceAsStream is the first part of the solution. The second part is to load the text in one go. There was no support for this in J2ME, you needed to read, handle buffers etc. yourself. Fortunately there is a utility method in codename one. So my working method now looks like this:
final String HelpTextFile = "/helptext.txt";
...
InputStream in = Display.getInstance().getResourceAsStream(
Form.class, HelpTextFile);
if (in != null){
try {
text = com.codename1.io.Util.readToString(in);
in.close();
} catch (IOException ex) {
System.out.println(ex);
text = "Read Error";
}
}
The following code worked for me.
//Gets a file system storage instance
FileSystemStorage inst = FileSystemStorage.getInstance();
//Gets CN1 home`
final String homePath = inst.getAppHomePath();
final char sep = inst.getFileSystemSeparator();
// Getting input stream of the file
InputStream is = inst.openInputStream(homePath + sep + "MyText.txt");
// CN1 Util class, readInputStream() returns byte array
byte[] b = Util.readInputStream(is);
String myString = new String(b);
I'm developing Java code to get data from a website and store it in a file. I want to store the result of xpath into a file. Is there any way to save the output of the xpath? Please forgive for any mistakes; this is my first question.
public class TestScrapping {
public static void main(String[] args) throws MalformedURLException, IOException, XPatherException {
// URL to be fetched in the below url u can replace s=cantabil with company of ur choice
String url_fetch = "http://www.yahoo.com";
//create tagnode object to traverse XML using xpath
TagNode node;
String info = null;
//XPath of the data to be fetched.....use firefox's firepath addon or use firebug to fetch the required XPath.
//the below XPath will display the title of the company u have queried for
String name_xpath = "//div[1]/div[2]/div[2]/div[1]/div/div/div/div/table/tbody/tr[1]/td[2]/text()";
// declarations related to the api
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = new CleanerProperties();
props.setAllowHtmlInsideAttributes(true);
props.setAllowMultiWordAttributes(true);
props.setRecognizeUnicodeChars(true);
props.setOmitComments(true);
//creating url object
URL url = new URL(url_fetch);
URLConnection conn = url.openConnection(); //opening connection
node = cleaner.clean(new InputStreamReader(conn.getInputStream()));//reading input stream
//storing the nodes belonging to the given xpath
Object[] info_nodes = node.evaluateXPath(name_xpath);
// String li= node.getAttributeByName(name_xpath);
//checking if something returned or not....if XPath invalid info_nodes.length=0
if (info_nodes.length > 0) {
//info_nodes[0] will return string buffer
StringBuffer str = new StringBuffer();
{
for(int i=0;i<info_nodes.length;i++)
System.out.println(info_nodes[i]);
}
/*str.append(info_nodes[0]);
System.out.println(str);
*/
}
}
}
You can "simply" print the nodes as strings, to console/or a file --
example in Perl:
my $all = $XML_OBJ->find('/'); # selecting all nodes from root
foreach my $node ($all->get_nodelist()) {
print XML::XPath::XMLParser::as_string($node);
}
note: this output however may not be nicely xml-formatted/indented
The output of an XPath in Java is a nodeset, so yes, once you have a nodeset you can do anything you want with it, save it to a file, process it some more.
Saving it to a file would involve the same steps in java that saving anything else to a file involve, there is no difference between that and and any other data. Select the nodeset, itterate through it, get the parts you want from it and write them to some kind of file stream.
However, if you mean is there a Nodeset.SaveToFile(), then no.
I would recommend you to take the NodeSet, which is a collection of Nodes, iterate on it, and add it to a created DOM document object.
After this, you can use the TransformerFactory to get a Transformer object, and to use its transform method. You should transform from a DOMSource to a StreamResult object which can be created based on FileOutputStream.