why I'm getting a "cannot find symbol" error - java

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());
}
}

Related

java get data from api (I want to print the values ​in the url )

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();
}
}
}

How to read a simple playlist in java

I am trying to create a simple java command line code that will accept the URL from a playlist in command line and it should return the playlist content.
I am getting the following response back Enter playlist url here (0 to quit):
http://gv8748.lu.edu:8084/sweng987/simple-01/playlist.m3u8
java.net.MalformedURLException: no protocol: http://lu8748.lu.edu:8084/sweng987/simple-01/playlist.m3u8
at java.base/java.net.URL.<init>(URL.java:627)
at java.base/java.net.URL.<init>(URL.java:523)
at java.base/java.net.URL.<init>(URL.java:470)
at edu.lu.sweng987.SimplePlaylist.getPlaylistUrl(SimplePlaylist.java:36)
at edu.lu.sweng987.SimplePlaylist.main(SimplePlaylist.java:21)
My code is the following
package edu.psgv.sweng861;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.*;
public class SimplePlaylist {
private SimplePlaylist() {
//don't allow instances
}
// The main function returns the URL entered
public static void main(String[] args) throws IOException{
String output = getPlaylistUrl("");
System.out.println(output);
}
private static String getPlaylistUrl(String theUrl) {
String content = "";
Scanner scanner = new Scanner(System.in);
boolean validInput = false;
System.out.println("Enter playlist url here (0 to quit):");
content = scanner.nextLine();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content += line + "\n";
}
bufferedReader.close();
} catch(Exception e) {
e.printStackTrace();
}
return content;
}
}
You have incorrectly used the parameter for the method when creating the URL instance instead of the local variable actually containing the url
Change
content = scanner.nextLine();
try {
URL url = new URL(theUrl);
to
content = scanner.nextLine();
try {
URL url = new URL(content);

java.lang.NoSuchMethodError: org.apache.fontbox.afm.AFMParser.parse()V

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.

java: HTTP session between a HTTP server and a client

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());
}
}
}

extracting data using jsoup in java

I am trying to run this code and i am facing the "Null Pointer Exception" in my program.I used try and catch but i donot know how to eliminate the problem.
Here is the code:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.net.*;
import java.io.*;
import java.lang.NullPointerException;
public class WikiScraper {
public static void main(String[] args) throws IOException
{
scrapeTopic("/wiki/Python");
}
public static void scrapeTopic(String url){
String html = getUrl("http://www.wikipedia.org/"+url);
Document doc = Jsoup.parse(html);
String contentText = doc.select("#mw-content-text>p").first().text();
System.out.println(contentText);
System.out.println("The url was malformed!");
}
public static String getUrl(String url){
URL urlObj = null;
try{
urlObj = new URL(url);
}
catch(MalformedURLException e){
System.out.println("The url was malformed!");
return "";
}
URLConnection urlCon = null;
BufferedReader in = null;
String outputText = "";
try{
urlCon = urlObj.openConnection();
in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
String line = "";
while((line = in.readLine()) != null){
outputText += line;
}
in.close();
}catch(IOException e){
System.out.println("There was an error connecting to the URL");
return "";
}
return outputText;
}
}
The Error shown is:
There was an error connecting to the URL
Exception in thread "main" java.lang.NullPointerException
at hello.WikiScraper.scrapeTopic(WikiScraper.java:17)
at hello.WikiScraper.main(WikiScraper.java:11)
You have
public static String getUrl(String url){
// ...
return "";
}
What always ends in an empty String.
Try
Document doc = Jsoup.connect("http://example.com/").get();
for example.

Categories

Resources