Problems connecting with Dbpedia Lookup web service - java

I'm trying to use the Lookup web service from DBpedia, but I'm finding difficulties because there's very little information on the web. I found a code example, but when I execute it, I get errors:
java.lang.NullPointerException
at tutorial.DBpediaLookupClient.containsSearchTerms(DBpediaLookupClient.java:111)
at tutorial.DBpediaLookupClient.endElement(DBpediaLookupClient.java:87)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:195)
at tutorial.DBpediaLookupClient.<init>(DBpediaLookupClient.java:56)
at tutorial.DBpediaLookupClient.main(DBpediaLookupClient.java:126)
HERE IS THE CODE:
package tutorial;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import com.sun.org.apache.bcel.internal.classfile.Attribute;
public class DBpediaLookupClient extends DefaultHandler {
/**
* #param args
*/
private List<Map<String, String>> variableBindings = new ArrayList<Map<String, String>>();
private Map<String, String> tempBinding = null;
private String lastElementName = null;
private String query = "";
public DBpediaLookupClient( String query ) throws Exception {
this.query = query;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryClass=place&QueryString="+query);
try{
client.executeMethod(method);
System.out.println(method);
InputStream ins = method.getResponseBodyAsStream();
SAXParserFactory factory = SAXParserFactory.newInstance();
javax.xml.parsers.SAXParser sax = factory.newSAXParser();
sax.parse(ins, this);
}catch (HttpException he) {
System.err.println("Http error connecting to lookup.dbpedia.org");
}catch (IOException ioe) {
System.err.println("Unable to connect to lookup.dbpedia.org");
}catch (ParserConfigurationException e) {
System.out.println("O parser não foi configurado corretamente.");
e.printStackTrace();
}catch (SAXException e) {
System.out.println("Problema ao fazer o parse do arquivo.");
e.printStackTrace();
}
method.releaseConnection();
}
public void startElement(String uri, String localName, String qName, Attribute attributes) throws SAXException {
if (qName.equalsIgnoreCase("result")) {
tempBinding = new HashMap<String, String>();
}
lastElementName = qName;
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("result")) {
System.out.println("Qname:" + qName);
if (!variableBindings.contains(tempBinding) && containsSearchTerms(tempBinding))
variableBindings.add(tempBinding);
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
String s = new String(ch, start, length).trim();
if (s.length() > 0) {
if ("Description".equals(lastElementName)) tempBinding.put("Description", s);
if ("URI".equals(lastElementName)) tempBinding.put("URI", s);
if ("Label".equals(lastElementName)) tempBinding.put("Label", s);
}
}
public List<Map<String, String>> variableBindings() {
return variableBindings;
}
private boolean containsSearchTerms(Map<String, String> bindings) {
StringBuilder sb = new StringBuilder();
for (String value : bindings.values()){
sb.append(value); // do not need white space
}
String text = sb.toString().toLowerCase();
StringTokenizer st = new StringTokenizer(this.query);
while (st.hasMoreTokens()) {
if (text.indexOf(st.nextToken().toLowerCase()) == -1) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try {
DBpediaLookupClient client = new DBpediaLookupClient("berlin");
} catch (Exception e) {
e.printStackTrace();
}
}
}
If anybody has any idea of what's wrong please help me. Or if any of you has any other code example it will help a lot too.

I talked to the author of the code and he corrected some minor bugs.
Here is the code:
Here is the link to the corrected code: https://github.com/mark-watson/java_practical_semantic_web/blob/master/src/com/knowledgebooks/info_spiders/DBpediaLookupClient.java
Thats a really good example of the use of the Dbpedia Lookup Service with Jena.
It works perfectly!

Just be careful about the SAX paserhandler which maybe gives you wrong length in characters method
so re structure the linked java code like following:
private StringBuffer fechaiBuffer;
public void startElement(...) {
fechaiBuffer = new StringBuffer();
}
public void characters(char ch[], int start, int length) {
fechaiBuffer.append(ch, start, length);
}
public void endElement(...) {
s = fechaiBuffer.toString();
// and so on
}

Related

REST Streaming JSON Output

We have JAX RS implementation which needs to send back JSON output. But the response size is huge. And the client expects the same synchronously.
Hence I tried to use StreamingOutput... but the client is not really getting the data in chunks.
Below is sample snippet:
Server Side
streamingOutput = new StreamingOutput() {
#Override
public void write(OutputStream out) throws IOException, WebApplicationException {
JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(out);
jsonGenerator.writeStartArray();
for(int i=0; i < 10; i++) {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("Response_State", "Response State - " + i);
jsonGenerator.writeStringField("Response_Report", "Response Report - " + i);
jsonGenerator.writeStringField("Error_details", "Error Details - " + i);
jsonGenerator.writeEndObject();;
jsonGenerator.flush();
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
jsonGenerator.writeEndArray();
jsonGenerator.close();
}
};
return Response.status(200).entity(streamingOutput).build();
Client
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("http://localhost:8080/AccessData/FetchReport");
post.setHeader("Content-type", "application/json");
ResponseHandler<HttpResponse> responseHandler = new BasicResponseHandler();
StringEntity entity = new StringEntity(jsonRequest); //jsonRequest is request string
post.setEntity(entity);
HttpResponse response = client.execute(post);
BufferedReader buffReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
JsonParser jsonParser = new JsonFactory().createParser(buffReader);
while(jsonParser.nextToken() != JsonToken.END_OBJECT) {
System.out.println(jsonParser.getCurrentName() + ":" + jsonParser.getCurrentValue());
}
String output;
while((output = buffReader.readLine()) != null) {
System.out.println(output);
}
In the server side code, I am putting sleep call just to simulate a gap between chunks of data. What I need is that the client should receive chunks of data as and when it is thrown back by the server.
But here the client gets the response in entirety always.
Any possible solution?
Thanks in advance.
It looks like the client side is not implemented correctly: reading the array of the objects using the parser.
Also, I would like to recommend reading and writing a data transfer object instead of low level field-by-field reading and writing.
For the sake of completeness, here is a complete draft example that uses: Jersey 2.25.1, Jetty 9.2.14.v20151106.
Common
ResponseData class
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ResponseData {
private final String responseState;
private final String responseReport;
private final String errorDetails;
#JsonCreator
public ResponseData(
#JsonProperty("Response_State") final String responseState,
#JsonProperty("Response_Report") final String responseReport,
#JsonProperty("Error_details") final String errorDetails) {
this.responseState = responseState;
this.responseReport = responseReport;
this.errorDetails = errorDetails;
}
public String getResponseState() {
return this.responseState;
}
public String getResponseReport() {
return this.responseReport;
}
public String getErrorDetails() {
return this.errorDetails;
}
#Override
public String toString() {
return String.format(
"ResponseData: responseState: %s; responseReport: %s; errorDetails: %s",
this.responseState,
this.responseReport,
this.errorDetails
);
}
}
Service
ServerProgram class
import java.net.URI;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.jetty.JettyHttpContainerFactory;
import org.glassfish.jersey.server.ResourceConfig;
public class ServerProgram {
public static void main(final String[] args) {
final URI uri = URI.create("http://localhost:8080/");
final ResourceConfig resourceConfig = new ResourceConfig(TestResource.class);
resourceConfig.register(JacksonFeature.class);
JettyHttpContainerFactory.createServer(uri, resourceConfig);
}
}
TestResource class
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.OutputStream;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
#Path("/")
public class TestResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getData() {
final StreamingOutput streamingOutput = new JsonStreamingOutput();
return Response.status(200).entity(streamingOutput).build();
}
private static class JsonStreamingOutput implements StreamingOutput {
#Override
public void write(final OutputStream outputStream) throws IOException, WebApplicationException {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonFactory jsonFactory = objectMapper.getFactory();
try (final JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream)) {
jsonGenerator.writeStartArray();
for (int i = 0; i < 10; i++) {
final ResponseData responseData = new ResponseData(
"Response State - " + i,
"Response Report - " + i,
"Error Details - " + i
);
jsonGenerator.writeObject(responseData);
jsonGenerator.flush();
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
jsonGenerator.writeEndArray();
}
}
}
}
Client
ClientProgram class
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;
import org.glassfish.jersey.client.ClientProperties;
public class ClientProgram {
public static void main(final String[] args) throws IOException {
Client client = null;
try {
client = ClientBuilder.newClient();
client.property(ClientProperties.READ_TIMEOUT, 10000);
try (final InputStream inputStream = client
.target("http://localhost:8080/")
.request(MediaType.APPLICATION_JSON)
.get(InputStream.class);
final BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
processStream(bufferedInputStream);
}
} finally {
if (client != null) {
client.close();
}
}
}
private static void processStream(final InputStream inputStream) throws IOException {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonFactory jsonFactory = objectMapper.getFactory();
try (final JsonParser jsonParser = jsonFactory.createParser(inputStream)) {
final JsonToken arrayToken = jsonParser.nextToken();
if (arrayToken == null) {
// TODO: Return or throw exception.
return;
}
if (!JsonToken.START_ARRAY.equals(arrayToken)) {
// TODO: Return or throw exception.
return;
}
// Iterate through the objects of the array.
while (JsonToken.START_OBJECT.equals(jsonParser.nextToken())) {
final ResponseData responseData = jsonParser.readValueAs(ResponseData.class);
System.out.println(responseData);
}
}
}
}
Hope this helps.

How to access a xml file from a .jar for execute jar from shell_exec php function

jar from a apache server with php.
I use shell_exec and a give her my jar file.
But because i parse an xml file on my java class i have problem. Jar can't access xml.
Files
SampleSax.java
package phpJavaPack;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class SampleSAX {
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
/*int i=0;
MyBufferedReaderWriter f = new MyBufferedReaderWriter();
f.openRFile("dblp.xml");
String sLine="";
while ((i<10) && (sLine=f.readLine()) != null) {
System.out.println(sLine);
i++;
}*/
int i=0;
while(i<args.length){
System.out.println("Argument's: " + args[0]);
System.setProperty("entityExpansionLimit", "1000000");
SAXParserFactory spfac = SAXParserFactory.newInstance();
spfac.setNamespaceAware(true);
SAXParser saxparser = spfac.newSAXParser();
MyHandler handler = new MyHandler(args[i]);
InputSource is = new InputSource("dblpmini.xml");
is.setEncoding("ISO-8859-1");
System.out.println("Please wait...");
saxparser.parse(is, handler);
System.out.println("---->" + handler.getprofessorsPublications());
i++;
}
//System.out.println("#####################################################################################################");
//System.out.println("List of George A. Vouros: " + handler.getprofessorsPublicationsValue("George A. Vouros"));
//System.out.println(handler.getProfessors());
//handler.createHtmlPage();//emfanizei mia html selida me ta apotelesmata
}
}
MyHandler.java
package phpJavaPack;
import java.util.ArrayList;
import java.util.Hashtable;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyHandler extends DefaultHandler {
private Publication publication;
protected Hashtable<String, ArrayList<Publication>> professorsPublications = new Hashtable<String, ArrayList<Publication>>();
private String temp ;
private ArrayList<Publication> al;
//private EntryLd entry = new EntryLd();
// public MyHandler() {
// super();
//
// String[] namesTable = entry.getNamesInput();
//
//
// for (String name: namesTable) {
//
// al = new ArrayList<Publication>();
// professorsPublications.put(name, al);
// }
//
// System.out.println("HashTable: " + professorsPublications);
// }
public MyHandler(String authorForSearch){
super();
String name = authorForSearch;
al = new ArrayList<Publication>();
professorsPublications.put(name, al);
System.out.println("HashTable: " + professorsPublications);
}
public Hashtable<String, ArrayList<Publication>> getprofessorsPublications() {
return professorsPublications;
}
public ArrayList<Publication> getprofessorsPublicationsValue(String author) {
return professorsPublications.get(author);
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
temp = "";
if (qName.equalsIgnoreCase("article") || qName.equalsIgnoreCase("inproceedings")
|| qName.equalsIgnoreCase("proceedings") || qName.equalsIgnoreCase("book")
|| qName.equalsIgnoreCase("incollection") || qName.equalsIgnoreCase("phdthesis")
|| qName.equalsIgnoreCase("mastersthesis") || qName.equalsIgnoreCase("www")) {
publication = new Publication();
}
}
public void characters(char[] ch, int start, int length) {
temp = new String(ch, start, length);
System.out.println("----->>>" + temp);
//System.out.print(" <--- My temp's start: " + temp + " :My temp's end --> ");
}
public void endElement(String uri, String localName, String qName) throws SAXException
{
if (qName.equalsIgnoreCase("article") || qName.equalsIgnoreCase("inproceedings")
|| qName.equalsIgnoreCase("proceedings") || qName.equalsIgnoreCase("book")
|| qName.equalsIgnoreCase("incollection") || qName.equalsIgnoreCase("phdthesis")
|| qName.equalsIgnoreCase("mastersthesis") || qName.equalsIgnoreCase("www"))
{
for(int i=0; i<publication.getAuthors().size(); i++) {
String authorName = publication.getAuthors().get(i);
if(this.professorsPublications.containsKey(authorName)) {
this.publication.setType(localName);
this.professorsPublications.get(authorName).add(publication);
}
}
}
if(qName.equalsIgnoreCase("author")) {
publication.addAuthor(temp);
}
else if(qName.equalsIgnoreCase("title")) {
publication.setTitle(temp);
}
else if(qName.equalsIgnoreCase("year")) {
publication.setYear(Short.parseShort(temp));
}
else if(qName.equalsIgnoreCase("booktitle")) {
publication.setBooktitle(temp);
}
//String xl = publication.toString();
//System.out.println(xl);
}
}
How can give right the xml on a runnable jar?
Thnx
see PHP exec() command: how to specify working directory? - most probably the proc_open suggestion/example there is the best one
see the other suggestions at that thread too, like chdir

Print Report from JasperReports Server Repository

I would like ask your help for some solutions.
I want to know how can I print report from jasperserver repository.
I spent time googling for a period of time, but still cannot get it solve.
I got this source, but it does not work. Can someone fix it?
Any idears? Please help me.
1.Here is the source code:
package com.src.report;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor;
import com.jaspersoft.jasperserver.irplugin.JServer;
import com.jaspersoft.jasperserver.irplugin.wsclient.WSClient;
public class PrintService {
private static JServer server = null;
public static void ConnectionString(String webServiceUrl, String username, String password){
server = new JServer();
server.setUsername(username);
server.setPassword(password);
server.setUrl(webServiceUrl);
}
public static void runReports(String webServiceUrl, String username, String password) throws Exception{
ConnectionString(webServiceUrl, username, password);
WSClient client = new WSClient(server);
ResourceDescriptor resourceDescriptor = new ResourceDescriptor();
resourceDescriptor.setUriString ("/reports/samples/EmployeeAccounts");
Map<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put("MY_PARAMETER_NAME", "myparametervalue");
JasperPrint printer = client.runReport(resourceDescriptor, parameterMap);
JasperViewer.viewReport(printer, false, Locale.ENGLISH);
}
public static void main(String[] args) throws Exception {
String webServiceUrl = "http://localhost:8080/jasperserver-pro/services/repository";
String username = "jasperadmin";
String password = "jasperadmin";
runReports(webServiceUrl, username, password);
}
}
2.And here is the error message:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xerces/parsers/AbstractDOMParser
at com.jaspersoft.jasperserver.irplugin.wsclient.WSClient.<init>(WSClient.java:73)
at com.src.report.PrintService.runReports(PrintService.java:37)
at com.src.report.PrintService.main(PrintService.java:51)
Caused by: java.lang.ClassNotFoundException: org.apache.xerces.parsers.AbstractDOMParser
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 3 more
u can make use of the rest api of jasper
it is as simple as:
http://<host>:8080/jasperserver-pro/rest_v2/reports/pathofReport/reportID.format?j_username=username&j_password=password
Refer to this
As I googled for a period of time, I have found some solution related to my question above. My purpose here is not for reputation or anything else, but just wanna tell someone who get the same issue as I did.
My solution is here:
1/ Requirement Jar Files:
activation-1.1.jar
axis-1.3.jar
activation-1.1.jar axis-1.3.jar
commons-codec-1.5.jar
commons-collections-3.2.jar
commons-digester-1.7.jar
commons-discovery-0.4.jar
commons-logging-1.1.3.jar
commons-logging-1.1.3-javadoc.jar
commons-logging-1.1.3-sources.jar
commons-logging-adapters-1.1.3.jar
commons-logging-api-1.1.3.jar
jasperreports-5.2.0.jar
jasperserver-common-ws-5.2.0.jar
jasperserver-ireport-plugin-2.0.1.jar
jaxrpc.jar
mail-1.4.jar
saaj.jar
wsdl4j-1.5.1.jar
2/ Coding:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jaspersoft.src.jasperprint;
import net.sf.jasperreports.engine.JasperPrint;
import com.jaspersoft.jasperserver.irplugin.JServer;
import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.export.JRPrintServiceExporter;
import net.sf.jasperreports.engine.export.JRPrintServiceExporterParameter;
/**
*
* #author Administrator
*/
public class JasperPrintTest {
private static JServer server = null;
public JasperPrintTest(String webServiceUrl, String username, String password){
server = new JServer();
server.setUsername(username);
server.setPassword(password);
server.setUrl(webServiceUrl);
}
public List list(String uri) throws Exception{
ResourceDescriptor rd = new ResourceDescriptor();
rd.setWsType(ResourceDescriptor.TYPE_FOLDER);
rd.setUriString(uri);
return server.getWSClient().list(rd);
}
public ResourceDescriptor get(String uri) throws Exception{
return get(uri, null);
}
public ResourceDescriptor get(String uri, List arg) throws Exception{
ResourceDescriptor rd = new ResourceDescriptor();
rd.setWsType(ResourceDescriptor.TYPE_REPORTUNIT);
rd.setUriString(uri);
return server.getWSClient().get(rd, null,arg);
}
public JasperPrint runReports(String reportUnit, Map params) throws Exception{
ResourceDescriptor rd = new ResourceDescriptor();
rd.setWsType(ResourceDescriptor.TYPE_REPORTUNIT);
rd.setUriString(reportUnit);
return server.getWSClient().runReport(rd, params);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
String webServiceUrl="http://localhost:8080/jasperserver-pro/services/repository";
String username= "jasperadmin";
String password = "jasperadmin";
String printer = "Foxit Reader PDF Printer";
String reporturi = "/reports/samples/AllAccounts";
JasperPrintTest object = new JasperPrintTest(webServiceUrl,username,password);
JasperPrint jasperPrint = new JasperPrint();
Map parameterMap = new HashMap();
try {
jasperPrint = object.runReports(reporturi, parameterMap);
} catch (Exception ex) {
Logger.getLogger(ClassForm.class.getName()).log(Level.SEVERE, null, ex);
}
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
PrintService printService = null;
for(PrintService ps : printServices){
if(ps.getName().equals(printer)){
printService = ps;
break;
}
}
if(printService !=null)
{
JRExporter jrExporter = new JRPrintServiceExporter();
jrExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
jrExporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, printService);
jrExporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET,
printService.getAttributes());
jrExporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
jrExporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.TRUE);
try {
jrExporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(ClassForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
System.out.println("Printer is not defined");
}
}
}
3/ Result:
Note: but everything is still not dynamic. Please notice.

Extracting links of a facebook page

How can I extract all the links of a facebook page. Can I extract it using jsoup and pass "like" link as parameter to extract all the user's info who liked that particular page
private static String readAll(Reader rd) throws IOException
{
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1)
{
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readurl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try
{
BufferedReader rd = new BufferedReader
(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
}
finally
{
is.close();
}
}
public static void main(String[] args) throws IOException,
JSONException, FacebookException
{
try
{
System.out.println("\nEnter the search string:");
#SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
JSONObject json = readurl("https://graph.facebook.com/"+s);
System.out.println(json);
}}
CAN i MODIFY THIS AND INTEGRATE THIS CODE. BELOW CODE EXTRACTS ALL LINKS OF A PARTICULAR PAGE. i TRIED TO THE ABOVE CODE BUT IT'S NOT WORKING
String url = "http://www.firstpost.com/tag/crime-in-india";
Document doc = Jsoup.connect(url).get();
Elements links = doc.getElementsByTag("a");
System.out.println(links.size());
for (Element link : links)
{
System.out.println(link.absUrl("href") +trim(link.text(), 35));
}
}
public static String trim(String s, int width) {
if (s.length() > width)
return s.substring(0, width-1) + ".";
else
return s;
}
}
you can try alternative way also like this :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
public class URLExtractor {
private static class HTMLPaserCallBack extends HTMLEditorKit.ParserCallback {
private Set<String> urls;
public HTMLPaserCallBack() {
urls = new LinkedHashSet<String>();
}
public Set<String> getUrls() {
return urls;
}
#Override
public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) {
handleTag(t, a, pos);
}
#Override
public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
handleTag(t, a, pos);
}
private void handleTag(Tag t, MutableAttributeSet a, int pos) {
if (t == Tag.A) {
Object href = a.getAttribute(HTML.Attribute.HREF);
if (href != null) {
String url = href.toString();
if (!urls.contains(url)) {
urls.add(url);
}
}
}
}
}
public static void main(String[] args) throws IOException {
InputStream is = null;
try {
String u = "https://www.facebook.com/";
URL url = new URL(u);
is = url.openStream(); // throws an IOException
HTMLPaserCallBack cb = new HTMLPaserCallBack();
new ParserDelegator().parse(new BufferedReader(new InputStreamReader(is)), cb, true);
for (String aUrl : cb.getUrls()) {
System.out.println("Found URL: " + aUrl);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
}
Kind of works, but im not sure you could use jsoup for this I would rather look into casperjs or phantomjs
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class getFaceBookLinks {
public static Elements getElementsByTag_then_FilterBySelector (String tag, String httplink, String selector){
Document doc = null;
try {
doc = Jsoup.connect(httplink).get();
} catch (IOException e) {
e.printStackTrace();
}
Elements links = doc.getElementsByTag(tag);
return links.select(selector);
}
//Test functionality
public static void main(String[] args){
// The class name for the like links on facebook is UFILikeLink
Elements likeLinks = getElementsByTag_then_FilterBySelector("a", "http://www.facebook.com", ".UFILikeLink");
System.out.println(likeLinks);
}
}

How to parse GPX files with SAXReader?

I'm trying to parse a GPX file. I tried it with JDOM, but it does not work very well.
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(filename);
Element root = document.getRootElement();
System.out.println("Root:\t" + root.getName());
List<Element> listTrks = root.getChildren("trk");
System.out.println("Count trk:\t" + listTrks.size());
for (Element tmpTrk : listTrks) {
List<Element> listTrkpts = tmpTrk.getChildren("trkpt");
System.out.println("Count pts:\t" + listTrkpts.size());
for (Element tmpTrkpt : listTrkpts) {
System.out.println(tmpTrkpt.getAttributeValue("lat") + ":" + tmpTrkpt.getAttributeValue("lat"));
}
}
I opened the example file (CC-BY-SA OpenStreetMap) and the output is just:
Root: gpx
Count trk: 0
What can I do? Should I us a SAXParserFactory (javax.xml.parsers.SAXParserFactory) and implement a Handler class?
Here is my gpx reader. It ignores some of the tags but I hope it will help.
package ch.perry.rando.geocode;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* #author perrym
*/
public class GpxReader extends DefaultHandler {
private static final DateFormat TIME_FORMAT
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
private List<Trackpoint> track = new ArrayList<Trackpoint>();
private StringBuffer buf = new StringBuffer();
private double lat;
private double lon;
private double ele;
private Date time;
public static Trackpoint[] readTrack(InputStream in) throws IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
GpxReader reader = new GpxReader();
parser.parse(in, reader);
return reader.getTrack();
} catch (ParserConfigurationException e) {
throw new IOException(e.getMessage());
} catch (SAXException e) {
throw new IOException(e.getMessage());
}
}
public static Trackpoint[] readTrack(File file) throws IOException {
InputStream in = new FileInputStream(file);
try {
return readTrack(in);
} finally {
in.close();
}
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
buf.setLength(0);
if (qName.equals("trkpt")) {
lat = Double.parseDouble(attributes.getValue("lat"));
lon = Double.parseDouble(attributes.getValue("lon"));
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("trkpt")) {
track.add(Trackpoint.fromWGS84(lat, lon, ele, time));
} else if (qName.equals("ele")) {
ele = Double.parseDouble(buf.toString());
} else if (qName.equals("")) {
try {
time = TIME_FORMAT.parse(buf.toString());
} catch (ParseException e) {
throw new SAXException("Invalid time " + buf.toString());
}
}
}
#Override
public void characters(char[] chars, int start, int length)
throws SAXException {
buf.append(chars, start, length);
}
private Trackpoint[] getTrack() {
return track.toArray(new Trackpoint[track.size()]);
}
}
To read GPX files easily in Java see: http://sourceforge.net/p/gpsanalysis/wiki/Home/
example:
//gets points from a GPX file
final List points= GpxFileDataAccess.getPoints(new File("/path/toGpxFile.gpx"));
Ready to use, open source, and fully functional java GpxParser (and much more) here
https://sourceforge.net/projects/geokarambola/
Details here
https://plus.google.com/u/0/communities/110606810455751902142
With the above library parsing a GPX file is a one liner:
Gpx gpx = GpxFileIo.parseIn( "SomeGeoCollection.gpx" ) ;
Getting its points, routes or tracks trivial too:
for(Point pt: gpx.getPoints( ))
Location loc = new Location( pt.getLatitude( ), pt.getLongitude( ) ) ;

Categories

Resources