Java HTMLUnit MalformedURLException - java

I'm trying to execute this code from the HTMLUnit tutorial:
final WebClient webClient = new WebClient();
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
but I get the MalformedURLException in the second line when saving it in Eclipse (if I compile and run the code, I get it too). What's the problem? TIA
PS: I'm new to Java
Up:
Here's the stack trace:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/httpclient/auth/CredentialsProvider
at Tester.main(Tester.java:12)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.httpclient.auth.CredentialsProvider
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)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 1 more

I tried this in Eclipse 3.5 and it is working correctly, and the test is passing. I assume that you have included the necessary HTMLUnit JARs into your project? I took all the JARs from the HTMLUnit lib directory and added them to the build path of my project.
Also, can you catch the exception and post the stack trace here?
try {
final WebClient webClient = new WebClient();
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
}
catch (Exception e) {
e.printStackTrace();
}

package com.project.test;
import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class Practice1 {
public static void main(String[] args) {
final WebClient webClient = new WebClient();
HtmlPage page;
try {
page = (HtmlPage) webClient.getPage("http://htmlunit.sourceforge.net");
System.out.println("Title="+ page.getTitleText());
} catch (FailingHttpStatusCodeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Since in your stacktrace you have
Caused by: java.lang.ClassNotFoundException: org.apache.commons.httpclient.auth.CredentialsProvider
this isn't a malformed URL exception.
As confirmed by JARFinder, org.apache.commons.httpclient.auth.CredentialsProvider class should come from commons-httpclient-3.*.jar. Thus the cause of the problem must be that you don't have Commons HTTPClient 3.x JARs in your classpath.

Related

btrace visualvm interfaces require ASM 5

When I run this simple Java8 program
package test;
public class TraceInt {
public static void main(String args[]) throws InterruptedException{
TraceInt ti = new TraceInt();
while(true){
Integer.valueOf((int)System.currentTimeMillis());
ti.sleep(1000);
//System.getProperty("user.dir");
}
}
public void sleep(int millis){
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And run this btrace script against it
#OnMethod(
clazz = "/.*/",
method = "/java.lang.*/",
location = #Location(value = Kind.ENTRY, where = Where.BEFORE)
)
public static void onEntry(Object obj) {
println(Strings.strcat("on entry: ", identityStr(obj)));
}
I get this error in the program
java.lang.IllegalArgumentException: INVOKESPECIAL/STATIC on interfaces require ASM 5
at com.sun.btrace.org.objectweb.asm.MethodVisitor.visitMethodInsn(Unknown Source)
at com.sun.btrace.util.templates.TemplateExpanderVisitor.visitMethodInsn(TemplateExpanderVisitor.java:85)
at com.sun.btrace.org.objectweb.asm.MethodVisitor.visitMethodInsn(Unknown Source)
at com.sun.btrace.org.objectweb.asm.ClassReader.a(Unknown Source)
at com.sun.btrace.org.objectweb.asm.ClassReader.b(Unknown Source)
at com.sun.btrace.org.objectweb.asm.ClassReader.accept(Unknown Source)
at com.sun.btrace.org.objectweb.asm.ClassReader.accept(Unknown Source)
at com.sun.btrace.runtime.InstrumentUtils.accept(InstrumentUtils.java:66)
at com.sun.btrace.runtime.InstrumentUtils.accept(InstrumentUtils.java:62)
at com.sun.btrace.agent.Client.instrument(Client.java:392)
at com.sun.btrace.agent.Client.doTransform(Client.java:213)
at com.sun.btrace.agent.Client.transform(Client.java:165)
at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:428)
at sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
at sun.instrument.InstrumentationImpl.retransformClasses(InstrumentationImpl.java:144)
at com.sun.btrace.agent.Main$4.run(Main.java:464)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Any help appreciated
After a while I realised I was using an old version of btrace against Java8. As soon as I moved to the latest version everything was fine.

Apache POI ClassNotFoundException

I am using eclipse to try and get a list of sheets from an excel spreadsheet but when I go to run it Java throws exceptions.
here is the code;
File myFile = new File("excel.xlsx");
Workbook wb = null;
try {
wb = WorkbookFactory.create(myFile);
} catch (EncryptedDocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> sheetNames = new ArrayList<String>();
for (int i=0; i<wb.getNumberOfSheets(); i++) {
sheetNames.add( wb.getSheetName(i) );
}
System.out.println(sheetNames);
here is the log;
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:293)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:252)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:231)
at com.cogentautomation.view.View.main(View.java:19)
Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject
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)
... 4 more
I have included the following in the eclipse java build path as libraries;
commons-codec
commons-logging
junit
log4j
poi
poi-ooxml
poi-scratchpad
I know the solution is something simple but my mind is blanking. I am not using maven.
You will need to add XMLBeans dependency.You can include the dependency from here https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans/2.6.0
As the exception message is telling you, you need the XMLBeans library. Poi probably depends on it.
If you were using a dependency management tool such as Gradle or Maven, it would have automatically been included.

Why driver is still missing?

I am trying to use Java DB for app only storage.
Environment Variables:
CLASSPATH:
%JAVA_HOME%\jre\lib;%DERBY_HOME%\lib\derby.jar
DERBY_HOME:
C:\Program Files\Java\jdk1.7.0_25\db
Path:
%DERBY_HOME%\bin
No changes in eclipse configurations was done and i cannot include it to build path(it somehow will be considered as third party library, which is not allowed)
When i type "sysinfo" in cmd it tells me Db is instaled and list packages and other info.
Code:
public class Main {
private static String dbURL = "jdbc:derby:AssertDB;user=me;password=mine;create=true";
private static Connection con = null;
public static void main(String[] args) {
setDBSystemDir();
createConnection();
CookiesTable pTable = new CookiesTable(con);
try {
pTable.createTable();
pTable.populateTable();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
// load files
// parse files to tables
// retrive SQL statment
// print result
}
private static void setDBSystemDir() {
// Decide on the db system directory: <userhome>/.addressbook/
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.asertdb";
// Set the db system directory.
System.setProperty("derby.system.home", systemDir);
}
private static void createConnection() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
// Get a connection
con = DriverManager.getConnection(dbURL);
} catch (Exception except) {
System.out.println("DRIVER DRROOOOOP");
except.printStackTrace();
}
}
}
Exception:
java.lang.ClassNotFoundException: org.apache.derby.jdbc.EmbeddedDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at com.tuto.p4.Main.createConnection(Main.java:44)
at com.tuto.p4.Main.main(Main.java:13)
Exception in thread "main" java.lang.NullPointerException
at com.tuto.p4.CookiesTable.createTable(CookiesTable.java:29)
at com.tuto.p4.Main.main(Main.java:16)
Refering to the documentation there are two things to do in case you get a java.lang.ClassNotFoundException: org.apache.derby.jdbc.EmbeddedDriver if you run the SampleApp.
Configure Embedded Derby
Verify Derby
As you said that you checked sysinfo I would try it with adding derby.jar and derbytools.jar even if the tools are optional.
Or you can compare the SampleApp to your App....
Include derbytools.jar, derbyclient.jar as well.
Try putting System.out.println(System.getProperty("java.class.path"));
before Class.forName(...).newInstance()
The output must contain a valid path to derby.jar.

Exception java.lang.NoClassDefFoundError android/app/Activity

In an android app, having:
public class Pars extends Activity{
public Document docout(){
InputStream is = getResources().openRawResource(R.raw.talechap01);
Document docout = null;
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = domFactory.newDocumentBuilder();
docout = builder.parse(is);
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return docout;
}
and
public class Manager {
public static String getStory(String spage, Document docs) {
XPathExpression expr;
XPath xpath = XPathFactory.newInstance().newXPath();
Object result = null;
String num = spage;
String par = null;
try {
expr = xpath.compile("//decision"+num+"/p//text()");
result = expr.evaluate(docs, XPathConstants.NODESET);
}
catch (XPathExpressionException e) {
e.printStackTrace();
}
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
par = nodes.item(i).getNodeValue();
System.out.println(par);
}
return par;
}
}
Now I want to test the code.
public class Test {
public static void main(String[] args) {
try {Pars p = new Pars();
Document doc = p.docout();
System.out.println(Manager.getStory("000", doc));
}catch (Exception e){
e.printStackTrace();
}
}
}
I run "Test" as a java application and I get:
Exception in thread "main" java.lang.NoClassDefFoundError:
android/app/Activity at java.lang.ClassLoader.defineClass1(Native
Method) at java.lang.ClassLoader.defineClass(Unknown Source) at
java.security.SecureClassLoader.defineClass(Unknown Source) at
java.net.URLClassLoader.defineClass(Unknown Source) at
java.net.URLClassLoader.access$100(Unknown Source) 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) at
com.stack.over.Test.main(Test.java:11) Caused by:
java.lang.ClassNotFoundException: android.app.Activity 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) ... 13 more
I tried to find how to fix it but cannot achieve it.
I have this answer from another question but I'm kind of noob yet and can't figure it out how to fix it.
You have defined your Pars class as extending the class Activity. The
error you are seeing is telling you that the class
android.app.Activity is not available on the classpath. Maybe you need
to check which libraries you import. – adamretter Mar 5 at 10:01
Thanks all.
The error is that you're trying to run a program that references Android classes (android.app.Activity) as a regular Java program that doesn't have Android runtime libraries in its classpath.
You should run Android apps as Android apps (on an emulator or a device) and regular Java programs as regular Java programs and not mix the two. Activity is Android; main() method is regular Java.
To learn Android app development, you can start with the developer.android.com getting started documentation.
The error message says it all. You are writing Android now. Trying to write a main method doesn't make any more sense in Android than it would if you were writing a webapp that runs in Tomcat. You are going to need to step back and read up on how Android works.

Third-party jar (Twitter4J) in Minecraft Server with Bukkit

I have seen many errors with Twitter4j with Android, but I am not using it for Android. I am using it for Bukkit (Minecraft Plugin). For some reason, when I add twitter4j-core-3.0.3.jar to my project, I get a error when loading in the server console:
[SEVERE] Could not load 'plugins\Test.jar' in folder 'plugins'
org.bukkit.plugin.InvalidPluginException: java.lang.NoClassDefFoundError: twitter4j/TwitterException
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:184)
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:305)
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:230)
at org.bukkit.craftbukkit.v1_6_R2.CraftServer.loadPlugins(CraftServer.java:239)
at org.bukkit.craftbukkit.v1_6_R2.CraftServer.<init>(CraftServer.java:217)
at net.minecraft.server.v1_6_R2.PlayerList.<init>(PlayerList.java:56)
at net.minecraft.server.v1_6_R2.DedicatedPlayerList.<init>(SourceFile:11)
at net.minecraft.server.v1_6_R2.DedicatedServer.init(DedicatedServer.java:106)
at net.minecraft.server.v1_6_R2.MinecraftServer.run(MinecraftServer.java:391)
at net.minecraft.server.v1_6_R2.ThreadServerApplication.run(SourceFile:582)
Caused by: java.lang.NoClassDefFoundError: twitter4j/TwitterException
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:173)
... 9 more
Caused by: java.lang.ClassNotFoundException: twitter4j.TwitterException
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 org.bukkit.plugin.java.PluginClassLoader.findClass0(PluginClassLoader.java:80)
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:53)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 12 more`
Since I am new to Java, I am really not getting what I am doing wrong here. This is my code (I do not think this is the issue, since the plugin fails to load ... :
String TWITTER_CONSUMER_KEY = "XXXXXXXX";
String TWITTER_SECRET_KEY = "XXXXXX";
String TWITTER_ACCESS_TOKEN = "XXXXXXXXXX";
String TWITTER_ACCESS_TOKEN_SECRET = "XXXXXX";
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey(TWITTER_CONSUMER_KEY).setOAuthConsumerSecret(TWITTER_SECRET_KEY).setOAuthAccessToken(TWITTER_ACCESS_TOKEN).setOAuthAccessTokenSecret(TWITTER_ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try {
Query query = new Query(Username);
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets)
{
String rawJSON = DataObjectFactory.getRawJSON(tweet);
try
{
BufferedWriter out = new BufferedWriter(new FileWriter((getDataFolder() + File.separator + "TwitterData.txt")));
out.write(rawJSON);
out.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.out.println("Failed to store tweets: " + ioe.getMessage());
}
}
}
while ((query = result.nextQuery()) != null);
System.exit(0);
}
catch (TwitterException te)
{
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
Why is Twitter4j not loading properly? Thanks!
EDIT: Also, the twitter4j-core-3.03.jar is in another directory on my computer. Is that a issue?
All jars needed by your Java program need to be on the classpath on the server. This includes Twitter4J in your case.

Categories

Resources