I'm having an error while using the apache PDFBox jar. It seems like somehow it is calling a method on the AFMParser class which is non-existent. AFAIK I have included fontbox properly. pdfbox,fontbox,commons and gson are all in my build path.
I guess the error must have something to do with referencing, but this is my first JAVA project and no real clue how to debug this further. If anyone has an idea, please advice.
Error log:
2018-03-16 14:26:50.020 java[1898:217675] java.lang.NoSuchMethodError: org.apache.fontbox.afm.AFMParser.parse()V
at org.apache.pdfbox.pdmodel.font.PDFont.addAdobeFontMetric(PDFont.java:166)
at org.apache.pdfbox.pdmodel.font.PDFont.addAdobeFontMetric(PDFont.java:152)
at org.apache.pdfbox.pdmodel.font.PDFont.getAdobeFontMetrics(PDFont.java:122)
at org.apache.pdfbox.pdmodel.font.PDFont.<clinit>(PDFont.java:114)
at org.apache.pdfbox.pdmodel.font.PDFontFactory.createFont(PDFontFactory.java:108)
at org.apache.pdfbox.pdmodel.PDResources.getFonts(PDResources.java:213)
at org.apache.pdfbox.util.PDFStreamEngine.getFonts(PDFStreamEngine.java:612)
at org.apache.pdfbox.util.operator.SetTextFont.process(SetTextFont.java:69)
at org.apache.pdfbox.util.PDFStreamEngine.processOperator(PDFStreamEngine.java:562)
at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:269)
at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:236)
at org.apache.pdfbox.util.PDFStreamEngine.processStream(PDFStreamEngine.java:216)
at org.apache.pdfbox.pdfviewer.PageDrawer.drawPage(PageDrawer.java:139)
at org.apache.pdfbox.pdmodel.PDPage.print(PDPage.java:890)
at java.desktop/sun.lwawt.macosx.CPrinterJob$6.run(CPrinterJob.java:757)
at java.desktop/sun.lwawt.macosx.CPrinterJob.printAndGetPageFormatArea(CPrinterJob.java:767)
at java.desktop/sun.lwawt.macosx.CPrinterJob.printLoop(Native Method)
at java.desktop/sun.lwawt.macosx.CPrinterJob.print(CPrinterJob.java:334)
at java.desktop/sun.print.RasterPrinterJob.print(RasterPrinterJob.java:1443)
at org.apache.pdfbox.pdmodel.PDDocument.print(PDDocument.java:1545)
at org.apache.pdfbox.pdmodel.PDDocument.silentPrint(PDDocument.java:1531)
at com.xlshopgroup.printingpc.WatchFolder.printPDFFromURL(WatchFolder.java:83)
at com.xlshopgroup.printingpc.WatchFolder.main(WatchFolder.java:118)
Exception: Error: End-of-File, expected line
My code:
import java.nio.file.*;
import java.io.*;
import java.net.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.awt.print.PrinterJob;
import java.awt.print.PageFormat;
import java.awt.print.Book;
import java.awt.print.*;
import java.awt.print.PrinterJob;
import javax.print.PrintService;
import javax.net.ssl.HttpsURLConnection;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.PrintPDF;
import org.apache.commons.*;
import org.apache.fontbox.*;
import com.google.gson.*;
public class WatchFolder {
public static JsonObject sendPost(
String APIURL
) throws Exception {
String APIBASEURL = "http://example.com";
URL obj = new URL(APIBASEURL+APIURL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JsonObject convertedObject = new Gson().fromJson(response.toString(), JsonObject.class);
return convertedObject;
}
public static void printPDFFromURL(
String pdfURL,
String printerName
) throws IOException,PrinterException {
PDDocument document = null;
try {
document = PDDocument.load(new URL(pdfURL));
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setJobName(pdfURL);
if(printerName != null ) {
PrintService[] printService = PrinterJob.lookupPrintServices();
boolean printerFound = false;
for(int i = 0;!printerFound && i < printService.length; i++) {
if(printService[i].getName().indexOf(printerName) != -1) {
printJob.setPrintService(printService[i]);
printerFound = true;
System.out.println("Printer found: " + printService[i].getName());
}
}
}
document.silentPrint( printJob );
}catch(Exception e) {
System.out.println("Exception: "+e.getMessage());
}finally {
if(document != null) {
document.close();
}
}
}
public static void main(
String[] args
) throws Exception {
JsonObject toBePrinted = sendPost("gettoprint");
JsonObject response = toBePrinted.getAsJsonObject("response");
JsonArray results = response.getAsJsonArray("results");
for (JsonElement result : results) {
JsonObject resultObj = result.getAsJsonObject();
String PackingSlipURL = resultObj.get("packing_slip_url").getAsString();
String StickerURL = resultObj.get("sticker_url").getAsString();
String ShippingPartner = resultObj.get("shipping_partner").getAsString();
String id = resultObj.get("id").getAsString();
printPDFFromURL(PackingSlipURL, "HP-idealbetalingen-printer");
printPDFFromURL(StickerURL, "Zebra?");
//JsonObject deletedFromQueue = sendPost("deletefromqueue/"+id);
}
}
}
#self; indeed as John Kane suggested, it had to do with version numbering. I was trying to use a 2.x.x version of fontbox with a 1.8.x version of pdfbox.
Related
I want to print the values in the url but I'm new can you help me?
......................................................
import java.util.*;
import java.io.*;
import java.net.*;
class Main {
public static void main (String[] args) {
System.setProperty("http.agent", "Chrome");
try {
URL url = new URL("https://coderbyte.com/api/challenges/json/rest-get-simple");
try {
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
System.out.println(inputStream);
} catch (IOException ioEx) {
System.out.println(ioEx);
}
} catch (MalformedURLException malEx) {
System.out.println(malEx);
}
}
}
try 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;
public class UrlConnectionReader {
public static void main(String[] args) throws MalformedURLException, IOException {
InputStream in = null;
System.setProperty("http.agent", "Chrome");
try {
in = new URL("https://coderbyte.com/api/challenges/json/rest-get-simple").openStream();
InputStreamReader inR = new InputStreamReader(in);
BufferedReader buf = new BufferedReader(inR);
String line;
while ((line = buf.readLine()) != null) {
System.out.println(line);
}
} finally {
in.close();
}
}
}
I would like to process JSON data started with an object that I don't need.
Here you have the URL:
http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819
I have been trying to adapt next code, but I don't know how to avoid the first object (summary) and take the second one (resources).
If I want to take one by one all the data inside from each object of "resources" (for example, showing "nombre-calle", "tipo-via"...).
package leerjson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class LeerJSON {
public static void main(String[] args) throws ParseException {
JSONParser parser = new JSONParser();
try {
URL oracle = new URL("http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819"); // URL to Parse
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
in.readLine();
while ((inputLine = in.readLine()) != null) {
JSONArray a = (JSONArray) parser.parse(inputLine);
// Loop through each item
for (Object o : a) {
JSONObject datos = (JSONObject) o;
System.out.println(datos);
}
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
UPDATED:
Once seen Enra64's answer, I don't know how to use getJSONArray and getJSONObject because it is not a method. I have included json-simple-1.1.1.jar to my project, but it doesn't work. Thank you in advance! This is my new code:
URL oracle = new URL("http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819"); // URL to Parse
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine = in.readLine();
JSONObject a = (JSONObject) parser.parse(inputLine);
JSONArray resources = a.getJSONArray("resources");
for (int i = 0; i < resources.length(); i++) {
resources.getJSONObject(i);
}
Select the resources object as follows:
JSONObject a = (JSONObject) parser.parse(inputLine);
JSONArray resources = a.getJSONArray("resources");
And then loop through it:
for (int i = 0; i < resources.length(); i++) {
resources.getJSONObject(i);
}
I'm using com.sun.net.HttpServer class to build a http server with java like the following:
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8989), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
//Read the request
InputStream in = httpExchange.getRequestBody();
StringWriter writer = new StringWriter();
IOUtils.copy(in, writer);
String inputString = writer.toString();
//prepare the response
httpExchange.sendResponseHeaders(200, "Hi my faithful client".length());
OutputStream os = httpExchange.getResponseBody();
os.write("Hi my faithful client".getBytes());
os.close();
}
}
}
I'm communicating with this server using this client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String argv[]) throws IOException{
String urlstr = "http://127.0.0.1:8989";
URL url = new URL(urlstr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("Hello HTTP server!! I'm your client1");
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
System.out.println(result.toString());
}
}
}
and it'fine working.
but what I want now is that the server allows the client to communicate with him for a session that means a sequence of request/response not just only one. So it will be a loop of request/response. For this purpose I tried to add as a first step just one request to the client by adding to it those two lines:
writer.flush();
writer.write("Hello HTTP server!! I'm your client2");
But it doesn't work. Just the first request is caught by the server.
How can I change the code to achieve my purpose?
Please check the code below:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Test1 {
static String urlstr = "http://127.0.0.1:8989";
public static void main(String argv) throws IOException{
URL url = new URL(urlstr);
Test1 t = new Test1();
for (int i = 0; i < 10; i++) {
t.sendRequest("Hello HTTP server!! I'm your client" + i, url);
}
}
private void sendRequest(String strToSend, URL url) throws IOException{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(strToSend);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
System.out.println(result.toString());
}
}
}
I just started learning android few days ago and I have a problem with uploading my JSON data to server. I manage to retrieve it via following code:
Edit: I did manage to retrieve files using external OKHTTP library but I would like to do this without using external libraries.
package cc.demorest;
import android.os.AsyncTask;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("myserver.com");
}
//Downloadtask
public class DownloadTask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection=null;
try {
url = new URL(urls[0]);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data=reader.read();
while (data !=-1){
char current=(char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//After download task
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray jArray=new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(1);
//Logging data
Log.i("Podatci: ", "Id: " + json_data.getInt("Id") +
", Name: " + json_data.getString("Name") +
", Years: " + json_data.getString("Age") +
", Email address: " + json_data.getString("Email")
);
TextView textView = (TextView) findViewById(R.id.textViewName);
textView.setText("ID: "+", Name: "+ json_data.getInt("Id")+json_data.getString("Name")+json_data.getString("Age")+json_data.getString("Email"));
/*
String data = jsonObject.getString("Name");
Log.i("Website content", data);
*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I am now trying to send my data to same server with same fields. I searched internet but most things that I found are outdated.. I would really appriciate some help or example.
Best Regards
Use HttpURLConnection, it does not use external libraries. If you're going to use an HttpURLConnection, it needs to be an AsyncTask.
Here is my code from a project I completed. Hope it helps.
First, put this in your manifest.xml file before :
<uses-permission android:name="android.permission.INTERNET" />
Calling the AsyncTask:
(Ignore the this, SinceTime, and GoesAddress. They are just variables I passed in)
URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
new ReceiveData(this, SinceTime, GoesAddress).execute(url);
The Class:
package com.ryan.scrapermain;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class ReceiveData extends AsyncTask<URL, Integer, Long> {
String response = "";
String SinceTime;
String GoesAddress;
Context myContext;
ReceiveData(Context context, String since, String goes) {
this.myContext = context;
SinceTime = since;
GoesAddress = goes;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder feedback = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
feedback.append("&");
feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
feedback.append("=");
feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return feedback.toString();
}
public void getData() throws IOException {
HashMap<String, String> params = new HashMap<>();
params.put("DCPID", GoesAddress);
params.put("SINCE", SinceTime);
URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
HttpURLConnection client = null;
try {
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
// You need to specify the context-type. In this case it is a
// form submission, so use "multipart/form-data"
client.setRequestProperty("multipart/form-data", "https://eddn.usgs.gov/fieldtest.html;charset=UTF-8");
client.setDoInput(true);
client.setDoOutput(true);
OutputStream os = client.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = client.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
}
else {
response = "";
}
}
catch (MalformedURLException e){
e.printStackTrace();
}
finally {
if(client != null) // Make sure the connection is not null.
client.disconnect();
}
}
#Override
protected Long doInBackground(URL... params) {
try {
getData();
} catch (IOException e) {
e.printStackTrace();
}
// This counts how many bytes were downloaded
final byte[] result = response.getBytes();
Long numOfBytes = Long.valueOf(result.length);
return numOfBytes;
}
protected void onPostExecute(Long result) {
System.out.println("Downloaded " + result + " bytes");
// This is just printing it to the console for now.
System.out.println(response);
// In the following two line I pass the string elsewhere and decode it.
InputCode input = new InputCode();
input.passToDisplay(myContext, response);
}
}
Use Volley as defined here. It's far more easier.
I'm trying to make a class that gets the source code from a URL. I dont understand why I get a "cannot find symbol error" on this line:
catch (MalformaedURLException e)
If someone could explain whats wrong that would be wonderful...Thanks
Here is my whole code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.MalformedURLException;
public class SourceCode
{
private String source;
public SourceCode(String url)
{
try
{
URL page = new URL(url);
this.source = getSource(page);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
}
public String getSource(URL url) throws Exception
{
URLConnection spoof = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(spoof.getInputStream()));
String strLine = "";
spoof.setRequestProperty( "User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)" );
while ((strLine = in.readLine()) != null)
{
strLine = strLine + "\n";
}
return strLine;
}
}
There are multiple problems with this code.
You are missing the import for java.net.MalformedURLException
getSource() is not returning anything, you need to return a string from the method.
You are setting spoof.setRequestProperty after starting to read from the source
Your constructor is ignoring the exception instead of throwing it out
There is no getter for source
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class SourceCode {
private String source;
public SourceCode(URL pageURL) throws IOException {
this.source = getSource(pageURL);
}
public String getSource() {
return source;
}
private String getSource(URL url) throws IOException {
URLConnection spoof = url.openConnection();
StringBuffer sb = new StringBuffer();
spoof.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)");
BufferedReader in = new BufferedReader(new InputStreamReader(spoof.getInputStream()));
String strLine = "";
while ((strLine = in.readLine()) != null) {
sb.append(strLine);
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
SourceCode s = new SourceCode(new URL("https://www.google.co.in/"));
System.out.println(s.getSource());
}
}