Building Wikipedia query forms in java using jena - java

#!/usr/local/bin/python
import sys
sys.path.append('/usr/home/bobd/lib/python/') # needed for hosted version
from SPARQLWrapper import SPARQLWrapper, JSON
import string
import urllib
import cgi
def main():
form = cgi.FieldStorage()
dir1name = form.getvalue('dir1')
dir2name = form.getvalue('dir2')
sparql = SPARQLWrapper("http://data.linkedmdb.org/sparql")
queryString = """
PREFIX m: <http://data.linkedmdb.org/resource/movie/>
SELECT DISTINCT ?actorName WHERE {
?dir1 m:director_name "DIR1-NAME".
?dir2 m:director_name "DIR2-NAME".
?dir1film m:director ?dir1;
m:actor ?actor.
?dir2film m:director ?dir2;
m:actor ?actor.
?actor m:actor_name ?actorName.
}
"""
queryString = queryString.replace("DIR1-NAME",dir1name)
queryString = queryString.replace("DIR2-NAME",dir2name)
sparql.setQuery(queryString)
sparql.setReturnFormat(JSON)
try:
ret = sparql.query()
results = ret.convert()
requestGood = True
except Exception, e:
results = str(e)
requestGood = False
print """Content-type: text/html
<html>
<head>
<title>results</title>
<link href="simple.css" type="text/css" rel="stylesheet" />
</head>
<body>
"""
if requestGood == False:
print "<h1>Problem communicating with the server</h1>"
print "<p>" + results + "</p>"
elif (len(results["results"]["bindings"]) == 0):
print "<p>No results found.</p>"
else:
for result in results["results"]["bindings"]:
print "<p>" + result["actorName"]["value"] + "</p>"
print "</body></html>"
main()
i got the above code from http://www.ibm.com/developerworks/xml/library/x-wikiquery/#download
Now,i want to do the same thing in java with servlets instead of cgi script.
so,how do i pass the query from servlet to http://data.linkedmdb.org/sparql endpoint using jena ?
and how should i get the result back and display it in a html form ?
PLease,HELP

Here's some example code. Note that I wouldn't actually do it this way for real: the presentation code and the back-end query handling are all mixed up in one class. Real apps don't do this! The example is faithful to your sample, except that rather than string-bash the query, I use Jena's facility to pre-bind some of the query variables (so DIR1-NAME becomes ?dir-1-name). I think this is much cleaner, and gives you more flexibility as to which of the query parameters are passed in from the client.
package example;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.model.*;
public class ServletExample
extends HttpServlet
{
/***********************************/
/* Constants */
/***********************************/
private static final long serialVersionUID = 1L;
public static final String SPARQL_ENDPOINT = "http://data.linkedmdb.org/sparql";
public static final String QUERY = "PREFIX m: <http://data.linkedmdb.org/resource/movie/>\n" +
"SELECT DISTINCT ?actorName WHERE {\n" +
" ?dir1 m:director_name %dir_name_1%.\n" +
" ?dir2 m:director_name %dir_name_2%.\n" +
" ?dir1film m:director ?dir1;\n" +
" m:actor ?actor.\n" +
" ?dir2film m:director ?dir2;\n" +
" m:actor ?actor.\n" +
" ?actor m:actor_name ?actorName.\n" +
"}\n" +
"";
private static final String HEADER = "<html>\n" +
" <head>\n" +
" <title>results</title>\n" +
" <link href=\"simple.css\" type=\"text/css\" rel=\"stylesheet\" />\n" +
" </head>\n" +
" <body>\n" +
"";
private static final String FOOTER = "</body></html>";
/**
* Respond to HTTP GET request. Will need to be mounted against some URL
* pattern in web.xml
*/
#Override
protected void doGet( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
String dir1 = req.getParameter( "dir1" );
String dir2 = req.getParameter( "dir2" );
if (dir1 == null || dir2 == null || dir1.isEmpty() || dir2.isEmpty()) {
noInput( resp );
}
else {
runQuery( resp, dir1, dir2 );
}
}
protected void noInput( HttpServletResponse resp )
throws IOException
{
header( resp );
resp.getWriter().println( "<p>Please select director names as query params <code>dir1</code> and <code>dir2</code></p>" );
footer( resp );
}
protected void footer( HttpServletResponse resp ) throws IOException {
resp.getWriter().println( FOOTER );
}
protected void header( HttpServletResponse resp ) throws IOException {
resp.getWriter().println( HEADER );
}
protected void runQuery( HttpServletResponse resp, String dir1, String dir2 )
throws IOException
{
PrintWriter out = resp.getWriter();
// Set up the query
String q = QUERY.replace( "%dir_name_1%", "\"" + dir1 + "\"" )
.replace( "%dir_name_2%", "\"" + dir2 + "\"" );
Query query = QueryFactory.create( q ) ;
QueryExecution qexec = QueryExecutionFactory.sparqlService( SPARQL_ENDPOINT, query );
// perform the query
ResultSet results = qexec.execSelect();
// generate the output
header( resp );
if (!results.hasNext()) {
out.println( "<p>No results, sorry.</p>" );
}
else {
out.println( "<h1>Results</h1>" );
while (results.hasNext()) {
QuerySolution qs = results.next();
String actorName = qs.getLiteral( "actorName" ).getLexicalForm();
out.println( String.format( "<div>Actor named: %s</div>", actorName ) );
}
}
footer( resp );
}
}
This code works as far as I can tell, but I don't know which queries you're using that should return some results.

Related

Get value from non valid SOAP 1.1 Message with Java

My previous question was closed and marked as duplicate, but the suggested asnwer does not answer my problem, and as suggested, I'm asking a new question.
Let's work with the suggested answer.
Here's the code:
String strMsg = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">" +
" <soap:Header>" +
" <context xmlns=\"urn:zimbra\"/>" +
" </soap:Header>" +
" <soap:Body>" +
" <soap:Fault>" +
" <soap:Code>" +
" <soap:Value>soap:Sender</soap:Value>" +
" </soap:Code>" +
" <soap:Reason>" +
" <soap:Text>no valid authtoken present</soap:Text>" +
" </soap:Reason>" +
" <soap:Detail>" +
" <Error xmlns=\"urn:zimbra\">" +
" <Code>service.AUTH_REQUIRED</Code>" +
" <Trace>qtp1027591600-6073:1588614639199:4eacbd0257a457b6</Trace>" +
" </Error>" +
" </soap:Detail>" +
" </soap:Fault>" +
" </soap:Body>" +
"</soap:Envelope>";
InputStream is = new ByteArrayInputStream(strMsg.getBytes());
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(is);
//Envelope
xsr.nextTag();
QName name = xsr.getName();
//Header
xsr.nextTag();
name = xsr.getName();
//Context
xsr.nextTag();
name = xsr.getName();
//Context again
xsr.nextTag();
name = xsr.getName();
//Header again
xsr.nextTag();
name = xsr.getName();
//Body
xsr.nextTag();
name = xsr.getName();
//Fault
xsr.nextTag();
name = xsr.getName();
/* IM COMMENTING THE FOLLOWING CODE BECAUSE I'M INTERESTED IN THE FAULT CONTENT
* AND EVEN IF IT TRY TO GO DEEPER I CAN'T GO PASS "VALUE" NODE
*
//Code
xsr.nextTag();
name = xsr.getName();
//Value
xsr.nextTag();
name = xsr.getName();
//throws exception, no more elements for some reason
xsr.nextTag();
name = xsr.getName();
*/
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringWriter stringWriter = new StringWriter();
transformer.transform(new StAXSource(xsr), new StreamResult(stringWriter));
StringReader sr = new StringReader(stringWriter.toString());
JAXBContext jaxbContext = JAXBContext.newInstance(Fault.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Fault fault = (Fault) unmarshaller.unmarshal(sr); //THROWS EXCEPTION
//"unexcpected element (URI:"http://www.w3.org/2003/05/soap-envelope", local:"Fault"). Expected elements are <{}Fault>
My Fault class:
#XmlRootElement(name = "Fault")
#XmlAccessorType(XmlAccessType.FIELD)
public static class Fault {
#XmlElement(name = "Code")
private String code;
#XmlElement(name = "Reason")
private String reason;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
}
I suspected it wasn't going to work, since the elements directly inside "Fault" don't have values themselves, they have more elements inside, and also all elements are prefixed with "soap", my envelope isn't exactly structured as the one in the suggested answer.
But still, I couldn't fetch the "Fault" node, as an exception was thrown:
unexcpected element (URI:"http://www.w3.org/2003/05/soap-envelope", local:"Fault"). Expected elements are <{}Fault>
I'm interested in getting the value of:
<soap:Text>no valid authtoken present</soap:Text>"
Also, this is only for this type of error, there might be other errors, also, when the answer is positive, I get a whole different response.
What I'm really insterested in is, finding a way to explore the envelope in the following way:
//pseudo code
(envelope->body->fault->reason->text != null) {reasonText = envelope->body->fault->reason->text)
But whatever way I'm able to reach Reason->Text will do, then I can adapt script to other bodies.
Thank you in advance.
A friend of mine who didn't want to answer here, found a solution, and even better, he found it using the way I wanted to:
//pseudo code
(envelope->body->fault->reason->text != null) {reasonText = envelope->body->fault->reason->text)
For anyone else in the futures who stumbles upon this problem, here it is a solution:
String strMsg = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">" +
" <soap:Header>" +
" <context xmlns=\"urn:zimbra\"/>" +
" </soap:Header>" +
" <soap:Body>" +
" <soap:Fault>" +
" <soap:Code>" +
" <soap:Value>soap:Sender</soap:Value>" +
" </soap:Code>" +
" <soap:Reason>" +
" <soap:Text>no valid authtoken present</soap:Text>" +
" </soap:Reason>" +
" <soap:Detail>" +
" <Error xmlns=\"urn:zimbra\">" +
" <Code>service.AUTH_REQUIRED</Code>" +
" <Trace>qtp1027591600-6073:1588614639199:4eacbd0257a457b6</Trace>" +
" </Error>" +
" </soap:Detail>" +
" </soap:Fault>" +
" </soap:Body>" +
"</soap:Envelope>";
strMsg = strMsg.replaceAll("soap:",""); //Had to replace soap:, not fancy but it works.
is = new ByteArrayInputStream(strMsg.getBytes());
InputSource xml = new InputSource(is);
XPath xPath = XPathFactory.newInstance().newXPath();
Object exprEval = xPath.compile("/Envelope/Body/Fault/Reason/Text/text()").evaluate(xml, XPathConstants.STRING);
if ( exprEval != null ) {
System.out.println( "Fault reason text: " + exprEval );
// This prints what's expected:
// Fault reason text: no valid authtoken present
}
There you go.

Problems with Adobe Flash Player blocking HTTP Response

I have a project that I have been working on part - time and it is now due to be submitted. I am connected to an external plc via ethernet and trying to retrieve data from the device using HTTP requests. I had this working, with the data being received back in XML format and I was able to parse this data and submit it to a database.
I am only now submitting the project and what was working is no longer working!! Instead of getting the data back in XML format I am getting a message to install Adobe Flash Player. On investigating the problem, Google and the other browsers have disabled some of the abilities of how to control how the flash player can be used. Previously when I had the program running I had to enable flash player on all sites and this worked. Now I am only allowed to enable it on specified sites and no matter what option I input I am still getting the same error.
In relation to the HTTP connection I am getting a code 200 response which shows that the connection is working but I cannot get back the data that I was always getting.
Has anyone else had this problem since Chrome has changed its policy? I have tried other browsers but the same problem. I have tried back tracking with an older version of Chrome but have only been able to get a .exe file to run individually rather than installed on the computer so Netbeans doesn't recognise it. I have tried Firefox and their extended version which is meant to allow for these issues until March/April 2018 but I am getting the same problem with this also.
Any insight or help would be appreciated.
This is the server information
This is the result from the request for information
'<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<!--
Smart developers always View Source.
This application was built using Apache Flex, an open source framework
for building rich Internet applications that get delivered via the
Flash Player or to desktops and mobile phones via Adobe AIR.
Learn more about Flex at http://flex.apache.org
// -->
<head>
<title></title>
<meta name="google" value="notranslate" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Include CSS to eliminate any default margins/padding and set the height of the html element and
the body element to 100%, because Firefox, or any Gecko based browser, interprets percentage as
the percentage of the height of its parent container, which has to be set explicitly. Fix for
Firefox 3.6 focus border issues. Initially, don't display flashContent div so it won't show
if JavaScript disabled.
-->
<style type="text/css" media="screen">
html, body { height:100%; }
body { margin:0; padding:0; overflow:auto; text-align:center;
background-color: #ffffff; }
object:focus { outline:none; }
#flashContent { display:none; }
</style>
<!-- Enable Browser History by replacing useBrowserHistory tokens with two hyphens -->
<!-- BEGIN Browser History required section -->
<link rel="stylesheet" type="text/css" href="history/history.css" />
<script type="text/javascript" src="history/history.js"></script>
<!-- END Browser History required section -->
<script type="text/javascript" src="451swfob.js"></script>
<script type="text/javascript">
// For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection.
var swfVersionStr = "12.0.0";
// To use express install, set to playerProductInstall.swf, otherwise the empty string.
var xiSwfUrlStr = "451inst.swf";//"expressInstall.swf";
var flashvars = {};
var params = {};
params.quality = "high";
params.bgcolor = "#ffffff";
params.allowscriptaccess = "sameDomain";
params.allowfullscreen = "true";
var attributes = {};
attributes.id = "WebApp";
attributes.name = "WebApp";
attributes.align = "middle";
swfobject.embedSWF(
"WebApp.swf", "flashContent",
"100%", "100%",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
// JavaScript enabled so display the flashContent div in case it is not replaced with a swf object.
swfobject.createCSS("#flashContent", "display:block;text-align:left;");
</script>
</head>
<body>
<!-- SWFObject's dynamic embed method replaces this alternative HTML content with Flash content when enough
JavaScript and Flash plug-in support is available. The div is initially hidden so that it doesn't show
when JavaScript is disabled.
-->
<div id="flashContent">
<p>
To view this page ensure that Adobe Flash Player version
12.0.0 or greater is installed.
</p>
<script type="text/javascript">
var pageHost = ((document.location.protocol == "https:") ? "https://" : "http://");
document.write("<a href='http://www.adobe.com/go/getflashplayer'><img src='"
+ pageHost + "www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>" );
</script>
</div>
<noscript>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" id="WebApp">
<param name="movie" value="WebApp.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="true" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="WebApp.swf" width="100%" height="100%">
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="true" />
<!--<![endif]-->
<!--[if gte IE 6]>-->
<p>
Either scripts and active content are not permitted to run or Adobe Flash Player version
12.0.0 or greater is not installed.
</p>
<!--<![endif]-->
<a href="http://www.adobe.com/go/getflashplayer">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" />
</a>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
</noscript>
</body>
</html>`
This is basically telling me to install Adobe Flash Player as far as I can see which is already done!
The following is code from the servlet.
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.ByteArrayInputStream;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.xml.sax.*;
import javax.xml.parsers.*;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.*;
/**
*
* #author ******
*/
#WebServlet(urlPatterns = {"/DeviceReadDateTime"})
public class DanfossDeviceReadDateTime extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
String userName;
String userPassword;
String siteAddress;
String tagReference;
String reportType;
String danfossResponseXMLReturned;
String danfossReadDateTimeYear;
String danfossReadDateTimeMonth;
String danfossReadDateTimeDay;
String danfossReadDateTimeHour;
String danfossReadDateTimeMinute;
String danfossReadDateTimeSecond;
String danfossReadDateTimeEpoch;
String danfossReadDateTimeTimeZone;
String danfossReadDateTimeDayLightSavings;
Connection conn;
PreparedStatement prepStat;
Statement stat;
ResultSet rs = null;
/**
*
* #throws ServletException
*/
#Override
public void init() throws ServletException
{
String connectionUrl ="jdbc:sqlserver://localhost:***;" +
"databaseName=*******************;user=**;password=*****";
try{
// establishing the connection
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(connectionUrl);
System.out.println("You are connected to SQLServer 2014");
// stat = (Statement) conn.createStatement();
// retrieve data
/* Statement st = (Statement) conn.createStatement();
ResultSet rs1 = st.executeQuery("select * from danfossDateTime");
while(rs1.next()){
danfossReadDateTimeYear = rs1.getString(1);
danfossReadDateTimeMonth = rs1.getString(2);
danfossReadDateTimeDay = rs1.getString(3);
danfossReadDateTimeHour = rs1.getString(4);
danfossReadDateTimeMinute = rs1.getString(5);
danfossReadDateTimeSecond = rs1.getString(6);
danfossReadDateTimeEpoch = rs1.getString(7);
danfossReadDateTimeTimeZone = rs1.getString(8);
danfossReadDateTimeDayLightSavings = rs1.getString(9);
System.out.println("danfossReadDateTimeYear = " + danfossReadDateTimeYear + "\n"
+ "danfossReadDateTimeMonth = " + danfossReadDateTimeMonth + "\n"
+ "danfossReadDateTimeDay = " + danfossReadDateTimeDay
+ "danfossReadDateTimeHour = " + danfossReadDateTimeHour + "\n"
+ "danfossReadDateTimeMinute = " + danfossReadDateTimeMinute + "\n"
+ "danfossReadDateTimeSecond = " + danfossReadDateTimeSecond + "\n"
+ "danfossReadDateTimeEpoch = " + danfossReadDateTimeEpoch + "\n"
+ "danfossReadDateTimeTimeZone = " + danfossReadDateTimeTimeZone + "\n"
+ "danfossReadDateTimeDayLightSavings = " + danfossReadDateTimeDayLightSavings + "\n");
}
System.out.println("Data retrieved from MS SQL");
*/
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(DanfossDeviceReadDateTime.class.getName()).log(Level.SEVERE, null, ex);
}
}// end of init method// end of init method// end of init method// end of init method
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Cookie cookie = null;
Cookie cookiesArray[] = null;
//get an array of cookies associated with this domain
cookiesArray = request.getCookies();
if(cookiesArray != null)
{
for(int i = 0; i<cookiesArray.length; i++)
{
cookie = cookiesArray[i];
switch (cookie.getName()) {
case "userName":
userName = cookie.getValue();
break;
case "userPassword":
userPassword = cookie.getValue();
break;
case "siteAddress":
siteAddress = cookie.getValue();
siteAddress = ("http:\\").concat(siteAddress);
break;
}
}
}
//Code requesting that data from the danfoss unit
XPath path;
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<cmd action=\"read_date_time\" node =\"1\"/>\r\n\r\n";
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/octet-stream");
RequestBody body = RequestBody.create(mediaType, xmlString);
Request danfossRequest = new Request.Builder()
.url(siteAddress)
.post(body)
.build();
System.out.println("danfossRequest = " + danfossRequest);
Response danfossResponse = client.newCall(danfossRequest).execute();
System.out.println("danfossResponse = " + danfossResponse);
// converting string to xml and parsing
danfossResponseXMLReturned = danfossResponse.body().string();
System.out.println("danfossResponseXMLReturned = " + danfossResponseXMLReturned);
XMLReader parser;
try {
Document dbfactory =DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new ByteArrayInputStream(danfossResponseXMLReturned.getBytes("utf-8"))));
XPathFactory xpfactory = XPathFactory.newInstance();
path = xpfactory.newXPath();
danfossReadDateTimeYear = path.evaluate("/resp/year", dbfactory);
danfossReadDateTimeMonth = path.evaluate("/resp/month", dbfactory);
danfossReadDateTimeDay = path.evaluate("/resp/day", dbfactory);
danfossReadDateTimeHour = path.evaluate("/resp/hour", dbfactory);
danfossReadDateTimeMinute = path.evaluate("/resp/minute", dbfactory);
danfossReadDateTimeSecond = path.evaluate("/resp/second", dbfactory);
danfossReadDateTimeEpoch = path.evaluate("/resp/epoch", dbfactory);
danfossReadDateTimeTimeZone = path.evaluate("/resp/timezone", dbfactory);
danfossReadDateTimeDayLightSavings = path.evaluate("/resp/daylightsavings", dbfactory);
//print results
System.out.println("danfossReadDateTimeYear = " + danfossReadDateTimeYear);
System.out.println("danfossReadDateTimeMonth = " + danfossReadDateTimeMonth);
} catch (FactoryConfigurationError err) {
System.err.println ("can't create JAXP SAXParserFactory, "
+ err.getMessage ());
} catch (ParserConfigurationException err) {
System.err.println ("can't create XMLReader with namespaces, "
+ err.getMessage ());
} catch (SAXException err) {
System.err.println ("Hmm, SAXException, " + err.getMessage ());
} catch (XPathExpressionException ex) {
Logger.getLogger(DanfossDeviceReadDevices.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(danfossReadDateTimeYear);
System.out.println(danfossReadDateTimeMonth);
System.out.println(danfossReadDateTimeDay);
System.out.println(danfossReadDateTimeHour);
System.out.println(danfossReadDateTimeMinute);
System.out.println(danfossReadDateTimeSecond);
System.out.println(danfossReadDateTimeEpoch);
System.out.println(danfossReadDateTimeTimeZone);
System.out.println(danfossReadDateTimeDayLightSavings);
// submit data to database
/* try{
String query = "INSERT INTO danfossDateTime VALUES (?,?,?,?,?,?,?,?,?)";
prepStat = (PreparedStatement) conn.prepareStatement(query);
prepStat.setString(1,danfossReadDateTimeYear);
prepStat.setString(2,danfossReadDateTimeMonth);
prepStat.setString(3,danfossReadDateTimeDay);
prepStat.setString(4,danfossReadDateTimeHour);
prepStat.setString(5,danfossReadDateTimeMinute);
prepStat.setString(6,danfossReadDateTimeSecond);
prepStat.setString(7,danfossReadDateTimeEpoch);
prepStat.setString(8,danfossReadDateTimeTimeZone);
prepStat.setString(9,danfossReadDateTimeDayLightSavings);
prepStat.executeUpdate();
}catch(Exception e)
{
}
*/
//html page output
response.setContentType("text/html;charset=UTF-8");
// out = response.getWriter();
String title = "***";
String docType = "<!doctype html>";
out.println(docType + "<html>\n" +
"<head>\n" +
" <title>***</title>\n" +
" <link rel=\"stylesheet\" type=\"text/css\" href=\"***RemoteSiteDataCheckerCSS2.css\"/>\n" +
"</head>\n" +
"<body>\n" +
" \n" +
" \n" +
" <section id=\"logo\">\n" +
" <!-- Introduction on the company -->\n" +
" <header>\n" +
" <center><h1>**************</h1></center>\n" +
" \n" +
" <center><h3>Remote Site Data Checker</h3></center>\n" +
" </header>\n" +
" </section>\n" +
" \n" +
" \n" +
" \n" +
" <section>\n" +
" <form action=\"SubmitTestData\" method=\"POST\">\n" +
" <label>User Name</label> <input type=\"text\" name=\"userName\" value=\"" + userName + "\">\n" +
" <br>\n" +
" <label>Password</label> <input type=\"password\" name=\"userPassword\" value=\"" + userPassword + "\">\n" +
" <br>\n" +
" <label>Site Address</label> <input type=\"text\" name=\"siteAddress\" value=\"" + siteAddress + "\">\n" +
" <br>\n" +
" <label></label><input type=\"submit\" value=\"Submit Test Data\"/>\n" +
" \n" +
" </form>\n" +
" </section> \n" +
" \n" +
" <section>\n" +
" <form>\n" +
" <label>Results:</label>\n" +
" \n" +
" <textarea name=\"resultsTextBox\" rows=\"10\" cols=\"80\" wrap=\"hard\">\n" +
" Results now here...\n" + danfossResponseXMLReturned +
" \nFrom XML Dom BUilder - year = " + danfossReadDateTimeYear +
" \nFrom XML Dom BUilder - month = " + danfossReadDateTimeMonth +
" \nFrom XML Dom BUilder - day = " + danfossReadDateTimeDay +
" \nFrom XML Dom BUilder - hour = " + danfossReadDateTimeHour +
" \nFrom XML Dom BUilder - minute = " + danfossReadDateTimeMinute +
" \nFrom XML Dom BUilder - second = " + danfossReadDateTimeSecond +
" \nFrom XML Dom BUilder - epoch = " + danfossReadDateTimeEpoch +
" \nFrom XML Dom BUilder - timezone = " + danfossReadDateTimeTimeZone +
" \nFrom XML Dom BUilder - daylightsavings = " + danfossReadDateTimeDayLightSavings +
" </textarea>\n" +
" </form>\n" +
" </section> \n" +
" \n<section>\n" +
" <button onclick=\"location.href='index.html'\">Home Page</button>\n" +
" <button onclick=\"location.href='DanfossDeviceHome.html'\">Generate New Report</button>\n" +
" \n" +
" </section>" +
" \n" +
" <footer>\n" +
" <!-- Footer -->\n" +
" <hr>\n" +
" \n" +
" <p>**********************</p>\n" +
" </footer>\n" +
" \n" +
"</body>\n" +
"</html>\n" +
"\n");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(DanfossDeviceReadDateTime.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(DanfossDeviceReadDateTime.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Could current approach to TDD in Servlets be optimized?

The current approach is creating HTML in a ServletTest, run the test, change the Servlet until the test turns into green. However, it feels like that this approach to TDD in Servlets is devious and more time-consuming than TDD ordinary Java classes as HTML created in the ServletTest is copied to the Servlet for the most part and subsequently changed regarding the format (e.g. removing backslashes) instead of testing the output in a Test for ordinary Java Classes and writing most of the code in the main.
ServletTest:
HttpServletRequest mockedHttpServletRequest = mock(HttpServletRequest.class);
HttpServletResponse mockedHttpServletResponse = mock(HttpServletResponse.class);
HttpSession mockedHttpSession = mock(HttpSession.class);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
private final String doGetHtmlStringPartOne = "<html><body><table>"
+ "<tr><td><h1>";
private final String doGetHtmlStringPartTwo = "<\\/h1><\\/td>"
+ "<form method=\"post\">"
+ "<input type=\"hidden\" name=\"randomDigitRange\" value=\"1\" \\/>"
+ "<input type=\"hidden\" name=\"randomMathematicalOperator\""
+ " value=\"1\" \\/><input type=\"hidden\" name=\"fractionBoolean\""
+ " value=\"";
private final String doGetHtmlStringPartThree = "<td><input type=\"radio\" name=\"userInput\" value=\"(\\d)+.(\\d)+\">(\\d)+(\\s\\/\\s(\\d)+)?<\\/td>";
private final String doGetHtmlStringPartFour = "<\\/tr><tr><td>"
+ "<input type=\"submit\" value=\"Submit\" "
+ "onclick='this.form.action=\"ToBeDefinedServlet\";' \\/>"
+ "<\\/td><\\/tr><\\/table><\\/form><\\/body><\\/html>"
+ "<form action=\"\\/tobedefinedservlet\">"
+ "<input type=\"submit\" value=\"Home\"><\\/form>";
#Test
public void testBooleanFractionTrue() throws IOException, ServletException {
mockDoGet();
assertTrue(stringWriter.getBuffer().toString().trim().matches(expectedDoGetHtmlString("1 \\/ 1 \\+ 1 \\/ 1", true)));
}
public String expectedDoGetHtmlString(String assignment,
Boolean fractionBoolean) {
return doGetHtmlStringPartOne + assignment + doGetHtmlStringPartTwo
+ "" + fractionBoolean + "" + "\" \\/>" + "\\n"
+ doGetHtmlStringPartThree + "\\n" + doGetHtmlStringPartFour;
}
public void mockDoGet() throws IOException, ServletException {
when(mockedHttpServletRequest.getSession()).thenReturn(
mockedHttpSession);
when(mockedHttpServletResponse.getWriter()).thenReturn(printWriter);
when(mockedHttpServletRequest.getParameter("fractionBoolean"))
.thenReturn("true");
when(mockedHttpServletRequest.getParameter("randomDigitRange"))
.thenReturn("1");
when(
mockedHttpServletRequest
.getParameter("randomMathematicalOperator"))
.thenReturn("1");
when(mockedHttpServletRequest.getSession()).thenReturn(
mockedHttpSession);
new ToBeDefinedServlet().doGet(mockedHttpServletRequest,
mockedHttpServletResponse);
}
Servlet:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
calculation.setFractionBoolean(Boolean.parseBoolean(request
.getParameter("fractionBoolean")));
calculation.setAssignment(Double.parseDouble(request
.getParameter("randomDigitRange")), Double.parseDouble(request
.getParameter("randomMathematicalOperator")));
PrintWriter out = response.getWriter();
out.println("<html><body><table>"
+ "<tr><td><h1>"
+ calculation.getAssignment()
+ "</h1></td>"
+ "<form method=\"post\">"
+ "<input type=\"hidden\" name=\"randomDigitRange\" value=\""
+ request.getParameter("randomDigitRange")
+ "\" />"
+ "<input type=\"hidden\" name=\"randomMathematicalOperator\" value=\""
+ request.getParameter("randomMathematicalOperator") + "\" />"
+ "<input type=\"hidden\" name=\"fractionBoolean\" value=\""
+ request.getParameter("fractionBoolean") + "\" />");
for (double possibleAnswer : calculation.getPossibleAnswersArray()) {
String possibleAnswerFormat = Boolean.parseBoolean(request
.getParameter("fractionBoolean")) == true ? ""
+ new Fraction(possibleAnswer) + "" : "" + possibleAnswer
+ "";
out.println("<td><input type=\"radio\" name=\"userInput\" value=\""
+ possibleAnswer + "\">" + possibleAnswerFormat + "</td>");
}
out.println("</tr>"
+ "<tr><td><input type=\"submit\" value=\"Submit\" "
+ "onclick='this.form.action=\"ToBeDefinedServlet\";' /></td>"
+ "</tr></table></form></body></html>"
+ "<form action=\"/tobedefinedservlet\"><input type=\"submit\" value=\"Home\"></form>");
}
I think the main problem here is that you are building your html page by manually putting the html elements together from various strings. As you have experienced, this leads to code that is hard to test and maintain.
Try using JSF or some simliar technique instead. This will enable you to focus only on the functionality on the Java side, which is much easier to test.

Is it possible to read allowed values for a datatype property of a class?

I'm using an ontology in which I created a class named "USER". This class contains a datatype property named "gender". Then I inserted two allowed values for this datatype which are "male" and "female". I wanted to extract these datatype property values in order to insert them into a web page. But I didn't find the right method to do it. I don't even know if it's possible to read these values either.
Here is a part of my ontology. I would be really thankful for any help or suggestions.
<owl:DatatypeProperty rdf:ID="Gender">
<rdfs:domain rdf:resource="#USER"/>
<rdfs:range>
<owl:DataRange>
<owl:oneOf rdf:parseType="Resource">
<rdf:first rdf:datatype="http://www.w3.org/2001/XMLSchema#string"
>male</rdf:first>
<rdf:rest rdf:parseType="Resource">
<rdf:first rdf:datatype="http://www.w3.org/2001/XMLSchema#string"
>female</rdf:first>
<rdf:rest rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"/>
</rdf:rest>
</owl:oneOf>
</owl:DataRange>
</rdfs:range>
</owl:DatatypeProperty>
ps: I'm not talking about instances, it's just about allowed values for a datatype property of a class :) and I'm using the Jena API.
Many thanks for your help, that was really awesome but i still can't get my values :( i also fixed my classe's name and my property's name as well . but i'm always gatting the following error:
Exception in thread "main" com.hp.hpl.jena.shared.NoReaderForLangException: 20 Turtle
at com.hp.hpl.jena.rdf.model.impl.RDFReaderFImpl.getReader(RDFReaderFImpl.java:98)
at com.hp.hpl.jena.rdf.model.impl.ModelCom.read(ModelCom.java:215)
at com.hp.hpl.jena.ontology.impl.OntModelImpl.read(OntModelImpl.java:2098)
at test1.SafwenExample.run(SafwenExample.java:36)
at test1.SafwenExample.main(SafwenExample.java:31)
Java Result: 1
i found 2 casting errors on the recent code so i tried to fix it. here is my code :
package test1;
import java.io.StringReader;
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
public class SafwenExample
{
public static String NS = "http://www.owl-ontologies.com/Ontology_profile.owl#";
public static String SOURCE = "#prefix : <http://www.owl-ontologies.com/Ontologyprofile.owl#> .\n" +
"#prefix owl: <http://www.w3.org/2002/07/owl#>.\n" +
"#prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.\n" +
"#prefix xsd: <http://www.w3.org/2001/XMLSchema#>.\n" +
":User a owl:Class.\n" +
":gender a owl:DatatypeProperty ;\n" +
" rdfs:domain :User ;\n" +
" rdfs:range [\n" +
" a owl:DataRange ;\n" +
" owl:oneOf ( \"male\"^^xsd:string \"female\"^^xsd:string )\n" +
"].";
public static void main( String[] args ) {
new SafwenExample().run();
}
public void run() {
OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
m.read( new StringReader( SOURCE ), null, "Turtle" );
OntProperty gender = m.getOntProperty( NS + "gender" );
DataRange genderRange = (DataRange) gender.getRange().as( DataRange.class );
for (ExtendedIterator i = genderRange.listOneOf(); i.hasNext(); ) {
Literal l = (Literal) i.next();
System.out.println( "DataRange has value " + l.getLexicalForm() +
" with datatype: " + l.getDatatype() );
}
}
}
Ps: many thanks for your answer :)
Yes, you can do this using Jena's Ontology API:
package example;
import java.io.StringReader;
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
public class SafwenExample
{
public static String NS = "http://example.com/example#";
public static String SOURCE = "#prefix : <http://example.com/example#> .\n" +
"#prefix owl: <http://www.w3.org/2002/07/owl#>.\n" +
"#prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.\n" +
"#prefix xsd: <http://www.w3.org/2001/XMLSchema#>.\n" +
":User a owl:Class.\n" +
":gender a owl:DatatypeProperty ;\n" +
" rdfs:domain :User ;\n" +
" rdfs:range [\n" +
" a owl:DataRange ;\n" +
" owl:oneOf ( \"male\"^^xsd:string \"female\"^^xsd:string )\n" +
"].";
public static void main( String[] args ) {
new SafwenExample().run();
}
public void run() {
OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
m.read( new StringReader( SOURCE ), null, "Turtle" );
OntProperty gender = m.getOntProperty( NS + "gender" );
DataRange genderRange = gender.getRange().as( DataRange.class );
for (ExtendedIterator<Literal> i = genderRange.listOneOf(); i.hasNext(); ) {
Literal l = i.next();
System.out.println( "DataRange has value " + l.getLexicalForm() +
" with datatype: " + l.getDatatype() );
}
}
}
By the way, I fixed your names: class User (leading upper case, then camel case), property gender (leading lowercase).

Java - Updating static variables

I have two classes in java that need to run at the same time - A Crawler class ( that basically implements a web crawler, and keeps printing out urls as it encounters them ), and an Indexer class, which as of now, is supposed to simply print the urls crawled.
For this, my Indexer class has a Queue :
public static Queue<String> urls = new LinkedList();
And in the toVisit() function of my Crawler class, I have the following :
Indexer.urls.add( url ) // where url is a String
The Crawler is working totally fine, since it prints out all the urls that it has encountered, but for some reason, these urls do not get added to the Queue in my Indexer class. Any idea why this may be the case ?
The toVisit() method from Crawler.java is as follows :
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String domain = page.getWebURL().getDomain();
String path = page.getWebURL().getPath();
String subDomain = page.getWebURL().getSubDomain();
String parentUrl = page.getWebURL().getParentUrl();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Domain: '" + domain + "'");
System.out.println("Sub-domain: '" + subDomain + "'");
System.out.println("Path: '" + path + "'");
System.out.println("Parent page: " + parentUrl);
Indexer.urls.add( url );
System.out.println("=============");
}
Code from my Indexer class :
public static Queue<String> urls = new LinkedList();
public static void main( String[] args )
{
while( urls.isEmpty() )
{
//System.out.println("Empty send queue");
Thread.sleep(sleepTime);
}
System.out.println( urls.poll() );
}
Okay, so I solved my problem by doing as suggested by BigMike. I implemented the Runnable interface in my two classes, and then ran those 2 classes as threads within the main function of a new third class.
Thanks everyone for all your help ! :)

Categories