1

I'm in need of some help regarding a Web Service that has to retrieve and check a valid element from a XML file. The web service method should look like this - translate ("flower","english","russian") and the client should be able to allow you to enter the desired word, the original Language and the target Language. If these exist in the XML file the translation of it will be displayed on the client side, if not, it will display an error message.

I've create a standard web service method - add(int a, int b) and created also the client part using a normal java application, added a swing GUI, connected with the wsdl link and the method works nicely. How would it be best for me to make this program work? Please advice.

The service looks like this:

@WebMethod(operationName = "translate")
    public String translate(@WebParam(name = "word") String word, 
            @WebParam(name = "originalLanguage") String originalLanguage, 
            @WebParam(name = "targetLanguage") String targetLanguage) 
            throws Exception {

        XMLSource dataLSource = new XMLSource();
        return dataLSource.getTranslation(word);

    }

Considering that the XML file should look like this: translation.xml

<?xml version="1.0" encoding="UTF-8"?>
<translation>
    <word>
        <english>car</english>
        <russian>avtomobil</russian>    
    </word>
    <word>
        <english>flower</english>
        <russian>tsvetok</russian>    
    </word>
    <word>
        <english>butterfly</english>
        <russian>babochka</russian>   
    </word>
</translation>

Also the XML source class:

public class XMLSource {

    private Document readData() throws Exception{

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        File xmlFile = new File("translation.xml");
        return db.parse(new FileInputStream(xmlFile));

    }

    public String getTranslation(String original) throws Exception{

        Document doc = readData();
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xp = xpf.newXPath();
        XPathExpression xpe = xp.compile("/translation/word/russian[../english"
                + "/text()='"+original+"'] ");
        String translated = (String) xpe.evaluate(doc, XPathConstants.STRING);
        return translated;

    }    
}

The client GUI sample of the program

Kage A.
  • 15
  • 1
  • 5
  • 1
    What did you try yet? What part is not working right now? Show us some code, please. – Oleg Kurbatov Sep 19 '16 at 09:43
  • 1
    You can use a DOM parser to extract the information from your XML file and then check the values passed in to your web service. Eg check out this post on how to do that: http://stackoverflow.com/questions/5059224/which-is-the-best-library-for-xml-parsing-in-java. Alternatively you can use the SAX parser. But , more fundamentally , why not just store the translation matrix in a relational DB? Why does it need to be XML ? Parsing XML and searching it as part of a WS call sounds inefficient to me. – AHL Sep 19 '16 at 09:45
  • these are the task's requirements. how would it be best to check the values passed for the given xml file? – Kage A. Sep 19 '16 at 10:07

2 Answers2

0

You can use this as a starting point and modify to suit your need. It means you need to load your file with an InputSource object and then use an XPath to extract the data from your XML file. There are plenty of examples and tutorials on the web on how to do this. The below snippet is from Simplest way to query XML in Java.

String xml = "<resp><status>good</status><msg>hi</msg></resp>";

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

InputSource source = new InputSource(new StringReader(
xml));
String status = xpath.evaluate("/resp/status", source);

System.out.println("satus=" + status);
Community
  • 1
  • 1
AHL
  • 738
  • 3
  • 11
  • 35
  • So your suggestion would be that using XPath in this case would be better than using DOM. I will try this out and come back with a response soon. – Kage A. Sep 19 '16 at 11:14
  • I'm not saying it's better than DOM but it's a really simple way of doing what you are describing. The issue with DOM is that each time you call the code it reads and parses the entire XML file while SAX parses the file line by line and requires far less memory. Not sure how exactly the XPath code behaves re memory use but you should check if that's a consideration. Does this programming assignment have any other requirements? – AHL Sep 19 '16 at 11:42
  • The requirements go like this: You need to create translating service between two different languages. Within the service, the word's DB should be placed in a XML file with a random structure. When the client requests the translation of a single word, the service verifies if the word exists in the XML file and returns the value of the word translated. Otherwise, the service will return an error message. The client uses the described service calling the translate method with 3 string params, as described before. – Kage A. Sep 19 '16 at 14:29
  • I've tried creating a XML source class that uses the XPath parser and called it in the service but keeps throwing me an InvocationTargetException. How can I solve this other issue? – Kage A. Sep 20 '16 at 15:47
0
public class XMLSource {
    public String getTranslation(String original) throws Exception{
        Document doc;
         try {
            doc = readData();
            XPathFactory xpf = XPathFactory.newInstance();
            XPath xp = xpf.newXPath();
            XPathExpression xpe = xp.compile("/translation/word/russian[../english"
                    + "/text()='"+original+"'] ");
            String translated = (String) xpe.evaluate(doc, XPathConstants.STRING);
            if ("".equals(translated)) return " word not found"; 

            return translated;
         } catch (Exception ex) {
             Logger.getLogger(XMLSource.class.getName()).log(Level.SEVERE, null, ex);
             return "Error";
         }
     }   

    private Document readData() throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        File xmlFile = new File("translation.xml");/*enter the absolute path to the XML file.for example"C:\\Users\\User\\Documents\\NetBeansProjects\\WebServiceTranslate\\src\\java\\service\\translation.xml"*/ 
        return (Document) db.parse(new FileInputStream(xmlFile));
    }
}
logi-kal
  • 7,107
  • 6
  • 31
  • 43
  • You should not return anything like `Error` from the code, because that value can also be a value that's entirely valid translation for something else. In this case, just let it crash. – M. Prokhorov Jun 19 '17 at 12:13