How to set relaxedQueryChars of tomcat from the application level - java

Allowing special characters in request URL is possible in tomcat_folder/conf/server.xml as far as I know, but I am somewhat required to find another way to set these special characters from the application side (if it is possible), I mean using web.xml or any other way. Here, I have enabled "[" (opening square bracket) and "]" (closing square bracket) in the query:
<Connector port="8080" protocol="HTTP/1.1" relaxedQueryChars='|[]'
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
This works pretty fine and I would appreciate it if anyone can help me to set without touching server.xml.
Info about the application environment:
Tomcat version: 7.0.96,
Spring: 4.1.7.RELEASE

I agree with #M.Deinum.
It is not recommended to touch server.xml of the tomcat using java code as it can stop other application from working properly.
But still you want to do, you can take the risk.
Sample Java code :
import java.io.File;
import java.util.Arrays;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class RelaxedQueryCharsExample {
public static void main(String[] args)
throws ParserConfigurationException, SAXException, TransformerException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
File file = new File("D:/tomcat/conf/server.xml");
Document document = documentBuilder.parse(file);
NodeList list = document.getElementsByTagName("Connector");
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
NamedNodeMap map = node.getAttributes();
if (map.getNamedItem("port").getNodeValue().equalsIgnoreCase("8080")
&& map.getNamedItem("protocol").getNodeValue().equalsIgnoreCase("HTTP/1.1")) {
map.getNamedItem("relaxedQueryChars").setNodeValue("|[]");
}
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
document.setXmlStandalone(true);
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(file);
transformer.transform(source,result);
}
}
Note: Run this code before running tomcat server. In between running this may crash the server.

Related

Creating simple document with JDOM

I am trying to create a simple Document with Jdom.
I strictly followed the instructions given on
https://www.tutorialspoint.com/java_xml/java_dom_create_document.htm
I cannot understand why, no matter what I do, I end up with a [document:null].
This is my code :
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.*;
import org.jdom2.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Network {
public Document SetToXml() throws Exception {
Document doc = null;
try {
DocumentBuilderFactory DBF =
DocumentBuilderFactory.newInstance();
DocumentBuilder DB = DBF.newDocumentBuilder();
doc = DB.newDocument();
Element root = doc.createElement("network");
root.setAttribute("name", Name);
doc.appendChild(root);
}
}
}
When I inspect the doc variable, it always contains [document:null].
Is there any way out or should I give up ?
Thanks
I would say, no need to worry :)
The "[document:null]" string which your debugger is showing you is only the toString() - representation of the document object. I do not yet understand, why it actually looks like this, but I verified that regardless of this, the document actually has the "netwrok" element you specified and also the name attribute you are assigning to it.

Xpath 2.0 functions not working in Java using Saxon

I'm writing a simple code to scrape data from the web page using selenium and xpath2.0 function.
Since Selenium supports only xpath1.0 functions, I am trying to use Saxon.jar
I have downloaded and extracted the Saxon9he.jar files into the path "C:\Program Files\Java\jre1.8.0_111\lib\ext"
I have created a file "jaxp.properties" with the following lines:
javax.xml.transform.TransformerFactory = net.sf.saxon.TransformerFactoryImpl
javax.xml.xpath.XPathFactory","net.sf.saxon.xpath.XPathFactoryImpl
Also included my jar files in the eclipse library.
But, I am not able to fetch the values with the Xpath2.0 functions.
In my code, if I use
XPathFactory factory = XPathFactory.newInstance();
instead of
XPathFactory factory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
I am able to use the xpath1.0 functions. But I need Xpath2.0 function. please guide me in this.
My code is:
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathFactoryConfigurationException;
import javax.xml.xpath.XPathFunctionResolver;
import javax.xml.xpath.XPathVariableResolver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import net.sf.saxon.lib.NamespaceConstant;
import net.sf.saxon.xpath.XPathFactoryImpl;
public class XpathCheckClass {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathFactoryConfigurationException, XPathExpressionException{
WebDriver dr = new FirefoxDriver();
dr.get("http://s15.a2zinc.net/clients/hartenergy/midstream17/Public/eBooth.aspx?Nav=False&BoothID=137384");
try {
Thread.sleep(3000);
} catch (Exception e) {
}
String source = dr.getPageSource();
Document doc = null;
try {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = db.parse( new InputSource( new StringReader(source)));
} catch (Exception e) {
e.printStackTrace();
}
System.setProperty("javax.xml.xpath.XPathFactory:"+NamespaceConstant.OBJECT_MODEL_SAXON, "net.sf.saxon.xpath.XPathFactoryImpl");
XPathFactory factory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
// XPathFactory factory = XPathFactory.newInstance(); ---> default xpath factory
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("if(//h2) then //h2 else //h1");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
System.out.println(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getTextContent());
}
dr.close();
}
}
Recent releases of Saxon no longer advertise themselves as JAXP XPath services, so you need to instantiate the XPath factory explicitly:
XPathFactory xf = new net.sf.saxon.XPathFactoryImpl();

can any body provide a link for downloading wordnet ontology 2.0??

I already have downloaded wordnet2.0 full, but i am not getting how to use it as a graph because it consists of multiple RDF files. I want to use wordnet2.0 ontology as a graph in Eclipse. The following is the snippet of code that i am using for loading a ontology as a graph. I also want to know, Am i going in a right direction???
URIFactory factory = URIFactoryMemory.getSingleton();
URI graph_uri = factory.createURI("http://graph/");
G graph = new GraphMemory(graph_uri);
String fpath ="D:/Workspace/SSM/src/wordnet-wordsensesandwords.rdf";
GDataConf graphconf = new GDataConf(GFormat.RDF_XML, fpath);
GAction actionRerootConf = new GAction(GActionType.REROOTING);
GraphConf gConf = new GraphConf();
gConf.addGDataConf(graphconf);
gConf.addGAction(actionRerootConf);
// GraphLoaderGeneric.populate(graphconf, graph);
GraphLoaderGeneric.load(gConf, graph);
// General information about the graph
System.out.println(graph.toString());
http://wordnet.princeton.edu/wordnet/download/old-versions/
You can use this link to download the ontology and may use apache jena to query this
Once you have the results, you can represent it in the form of graph
You may also download wordnet in RDF format and can display it as graph using Protege tool
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import nu.xom.Builder;
import nu.xom.ParsingException;
import nu.xom.ValidityException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import edu.mit.jwi.Dictionary;
import edu.mit.jwi.IDictionary;
import edu.mit.jwi.item.IIndexWord;
import edu.mit.jwi.item.ISynset;
import edu.mit.jwi.item.IWord;
import edu.mit.jwi.item.IWordID;
import edu.mit.jwi.item.POS;
public class Main
{
public static void main(String[] args)
{
try
{
FileInputStream file = new FileInputStream(new File("c:\\employees.xml"));
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("*************************");
String expression = "/Employees/Employee[#emplid='3333']/job";
System.out.println(expression);
String job = xPath.compile(expression).evaluate(xmlDocument);
System.out.println(job);
System.out.println("*************************");
String path = "C:\\Program Files\\WordNet\\2.1\\dict";
URL url = new URL("file", null, path);
IDictionary dict = new Dictionary(url);
dict.open();
IIndexWord idxWord = dict . getIndexWord (job, POS. NOUN );
IWordID wordID = idxWord . getWordIDs ().get (0) ;
IWord word = dict . getWord ( wordID );
ISynset synset= word.getSynset();
for (IWord w : synset.getWords())
System.out.println(w.getLemma());
}
catch(Exception a)
{
System.out.println(a);
}
}
}
This is a sample code in which wornet can be queried for getting the synonyms of the word job from wordnet and using it to find similar terms like job from the RDF graph.
I have only worked with wornet for capturing related terms and hypernyms. Hope this may help

xml file is successfully parsed from netbeans but not from runnable jar

i developed a code that parses an xml file and returns result in a frame in netbeans .The code runs successfully from netbeans but when exporting the project into jar file it shows nothing .Please ,if you have ideas ,i will be thankful if you help me .Here is the code i used for parsing .
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class Parsing {
String a = null;
public static void main(String a) throws
ParserConfigurationException, SAXException, IOException,
XPathExpressionException {
a = getElem(a);
}
public static String getElem(String a) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
String file = "src/xml/read.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
XPath xpath = XPathFactory.newInstance().newXPath();
Node CustomerId = (Node) xpath.evaluate("//Operation[#name='Read' and #modifier='Customer']/ParameterList/StringParameter[#name='CustomerId']/text()",
doc.getDocumentElement(), XPathConstants.NODE);
a = CustomerId.getNodeValue();
return a;
}
}
when calling the method getElem(a) from another frame it shows me the value of a in a textbox ,but when exporting the project into a jar file it doesn't show me anything !
First thing that strikes me is the use of relative path to your XML resource. It seems you rely on existence of a file in a directory relative to your working dir.
The src directory will not exist at run time. This suggests that the XML file is an em ebbed resource, and as such, can't get accessed as a file would be if it lived on the file system.
Instead you want to use something like...
getClass().getResourceAsStream("/xml/read.xml")
And pass the resulting InputStream to DocumentBuilder. Don't forget to close it
here is the modified code that worked with jar file :)
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class Parsing {
String a = null;
private static final String TEST_XML = "/xml/read.xml";
public static void main(String a) throws
ParserConfigurationException, SAXException, IOException,
XPathExpressionException {
a = getElem(a);
}
protected static InputSource getTestXMLInputSource() {
InputStream is = Parsing.class.getResourceAsStream(TEST_XML);
is = Parsing.class.getResourceAsStream(TEST_XML);
return new InputSource(is);
}
public static String getElem(String a) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
final InputSource source = getTestXMLInputSource();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(source);
XPath xpath = XPathFactory.newInstance().newXPath();
Node CustomerId = (Node) xpath.evaluate("//Operation[#name='Read' and #modifier='Customer']/ParameterList/StringParameter[#name='CustomerId']/text()",
doc.getDocumentElement(), XPathConstants.NODE);
a = CustomerId.getNodeValue();
return a;
}
}

Java XML modifying

import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class modifyXML {
public static void modify(StringBuffer XMLBuffer) throws IOException, ParserConfigurationException, SAXException{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(XMLBuffer.toString().getBytes()));
Element rootNode = doc.getDocumentElement();
NodeList priceList = rootNode.getElementsByTagName("price");
priceList.item(0).setTextContent("190");
NodeList inStockList = rootNode.getElementsByTagName("id_product_attribute");
inStockList.item(0).setTextContent("100");
}
}
I am trying to modify an XML file and then put it all back together. I have managed with the modifying part, but I can not get the XML file back together. The result can be either a String or a StringBuffer.
What is the best/easiest way to do this?
Use a Transformer as described by WhiteFang34 in XML Document to String.
Official Java Tutorials: Writing Out a DOM as an XML File (just make StreamResult Wrap something else such as StringWriter).
Update:
Less known, shorter alternative by ykaganovich based on Load / Save objects:

Categories

Resources