I can't throws Exception and IOException in Java - java

I can't throws Exceptions such as IOException and Exception. I need to add dependencies of these but I couldn't find it.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException; > It throws error: Cannot resolve symbol 'java' - Add Maven dependency
public class JsoupTest {
public static void main(String[] args) throws IOException { > Cannot resolve symbol 'IOException'
// download the HTML from wikipedia and parses it
final Document document = Jsoup.connect("http://en.wikipedia.org/").get();
// Select a bunch of a tags
final Elements newsHeadLines = document.select("#mp-itn b a");
// Prints to console
for(Element headline : newsHeadLines) { > foreach not applicable to type 'org.jsoup.select.Elements'
System.out.println(headline); > Cannot resolve symbol 'System'
}
}
}
My question can be basic but I'm pretty new on this sorry. If you give my answer please add these:
Where did you find this that dependency?
How can I find dependencies, because I checked Maven repository but I couldn't find.
Compiler throws error even for System.out.println method as I showed above, why is that?
Compiler throws error which I showed on belove, foreach not applicable to type 'org.jsoup.select.Elements'
Thank you for your all answers. I don't want directly dependency. I want it to know why. Thanks

You do not need to add a dependency to use IOException or System.
You probably did not use the compiler correctly or your IDE shows non-existent errors.

Related

Loading and executing jar file using custom ClassLoader

I want to load and execute jar file using custom ClassLoader.
My code:
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
public class Main {
private static JarClassLoader customClassLoader;
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IOException {
customClassLoader = new JarClassLoader(new File(args[0]).toURI().toURL());
customClassLoader.invokeClass(customClassLoader.getMainClassName(), new String[]{});
}
}
Everything works great with simple jars but when I want execute more complicated jars, they not always work properly. For example if program is using apache logging service I will see
"ERROR StatusLogger Unable to locate a logging implementation, using SimpleLogger"
How to get around this.

Method undefined for type Java

Having real trouble figuring out where i'm going wrong on this one. Building a system using WEKA in java to study associations and am trying to implement the Apriori algorithm. Currently this is the code:
package model;
import weka.associations.*;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
public class Apriori {
public static void main(String args[]) throws Exception {
String dataset = "/Users/andrew/workspace/Movies/src/data/tagsfinal.arff";
DataSource dsource = new DataSource(dataset);
Instances dapriori = dsource.getDataSet();
Apriori apriori = new Apriori();
apriori.buildAssociations(dapriori);
System.out.println(apriori);
}
}
From looking at several implementations across the web this seems to be a widely accepted method of doing this however i receive an error on the "apriori.buildAssociations" line telling me that the method is undefined for the type Apriori. Furthermore, the import statement i use for the associations only works as the package type and when trying to extend it to :
import weka.associations.Apriori;
this throws an error message that "The import weka.associations.Apriori conflicts with a type defined in the same file". I have scoured StackOverflow alongside other resources and realize there is a lot of type undefined questions out there however have yet to find a solution to this problem. Any help/pointers would be greatly appreciated.
Your class is also named Apriori, so you are experiencing a name clash.
You should change the name of your own class to a different name (e.g. AprioriTest). In the unprobable case where you would really need your class to be named Apriori, then you would have to refer to the library's implementation by it's full name:
weka.associations.Apriori apriori = new weka.associations.Apriori();
apriori.buildAssociations(dapriori);

Why is my import of the containsString method not working?

I've written the simple Java script below in order to learn more about TDD, IntelliJ and Java itself.
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.both;
public class JUnit_Dummy {
private StringJoiner joiner;
private List<String> strings;
#Before
public void setUp() throws Exception {
strings = new ArrayList<String>();
joiner = new StringJoiner();
}
....
#Test
public void shouldContainBothStringsWhenListIsTwoStrings() {
strings.add("one");
strings.add("two");
assertThat(joiner.join(strings),
both(containsString("A")).
and(containsString("B")));
}
}
_____________
import java.util.List;
public class StringJoiner {
public String join(List<String> strings) {
if(strings.size() > 0) {
return (strings.get(0);
}
return "";
}
}
I'm trying to use the "containsString" method inside an assertion, but IntelliJ keeps telling me that it "cannot resolve method 'containsString(java.lang.String)". This despite the fact that the jUnit docs (http://junit.sourceforge.net/javadoc/org/junit/matchers/JUnitMatchers.html#containsString(java.lang.String)) tell me that this method does accept a String parameter.
I've tried swapping out various import statements, including the following:
import static org.hamcrest.Matcher.containsString;
import static org.hamcrest.Matcher.*;
import static org.hamcrest.CoreMatchers.*;
The best that I get is a greyed-out import statement telling me that the import statement is unused. Not sure what the problem is, any help would be appreciated.
UPDATE:
Here is the exact compiler error:
java: cannot find symbol
symbol: method containsString(java.lang.String)
location: class JUnit_Dummy
I thought I had tried every worthwhile import statement already, but this one did the trick:
import static org.junit.matchers.JUnitMatchers.*;
I faced the same issue with a Spring Boot app.
Seems like this is a dependency ordering issue.. one of the dependencies mentioned in pom.xml before the "spring-boot-starter-test" artifact was overriding the hamcrest version.
So all I did was change the order (moved this dependency up):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
I'm using Spring Boot 1.5.7.RELEASE.
We are supposed to use containsString method of hamcrest library.
My suggestion would be to stick to Junit 4 and import hamcrest library 1.3 in your build path. This would do the trick.
This will allow you to access other features of hamcrest library as well.
The solution can also be found by adding the required static imports manually. Or you can configure the required static imports in favorites tab of eclipse.
try this instead
import static org.hamcrest.CoreMatchers.*;
I'm working with MAVEN - doing a tutorial and I ran into this same issue.
I used the "import static org.hamcrest.CoreMatchers.*;" solution and that failed.
So I then moved JUNIT to be first on the list in the POM file - and that solved it.

Parsing Xml file using Java throws Exception. Why?

While I was trying to get the attribute of the root element Company I found the following problems, also some exceptions.
But I imported everything I need; then also eclipse says that remove unused import.
I want to know that why it is happening even after i have imported everything,
please give me some idea to remove the bug.
Also is it the way to do xml-parsing? is there any alternative and easy way to
do the same?
import java.io.EOFException;
import java.io.File;
import javax.lang.model.element.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import javax.lang.model.element.Element;
public class DomTest1 {
private static final String file = "test1.xml";
public static void main(String[] args) {
if (args.length>0) {
file = args[0];
}
try {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(new File(file));
Element root=document.getDocumentElement();
System.out.println(root.getTagName());
System.out.printf("name: %s%n", root.getAttribute("name"));
System.out.printf("sHortname: %s%n", root.getAttribute("sHortname"));
System.out.printf("mission : %s%n", root.getAttribute("mission"));
} catch(EOFException e) {
e.printStackTrace();
}
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Type mismatch: cannot convert from org.w3c.dom.Element to javax.lang.model.element.Element
The method getTagName() is undefined for the type Element
The method getAttribute(String) is undefined for the type Element
The method getAttribute(String) is undefined for the type Element
The method getAttribute(String) is undefined for the type Element
at DomTest1.main(DomTest1.java:23)
You have
import javax.lang.model.element.Element;
but you want
import org.w3c.dom.Element;
instead.
Also, regarding this:
also is it the way to do xml-parsing? is there any alternative and
easy way to do the same?
You are using java out of the box-provided ways to do xml parsing. There are several, better alternatives using 3rd part libraries. I'd recommend testing jdom, it is a lot simpler. See example here.
problem is because of this
import javax.lang.model.element.Element;
use this import statement
import org.w3c.dom.Element

Jruby embedded modules and classes

I have a ruby file as follows:
module Example
class Myclass
def t_st
"Hello World!"
end
end
end
now if this was just a class I would be able to use the following java code:
ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
jruby.eval(new BufferedReader(new FileReader("example.rb")));
Object example = jruby.eval("Myclass.new");
However, this class rests inside a module. Calling the same code as above produces the error:
Exception in thread "main" org.jruby.embed.EvalFailedException: uninitialized constant myclass
In addition, calling:
Object example = jruby.eval("Example");
The module returns no error. So one would assume this follows the format for Ruby.
Object example = jruby.eval("Example::myclass.new");
Again however, I get the same error as before.
Can anyone help? As there is little documentation on JRuby?
Thanks
Make sure that you do not have syntax errors. Usually I get those errors when I'm not paying attention to what I write...
Secondly, you cannot write the following:
Object example = jruby.eval("Myclass.new");
The reason being that your class is in a module. Instead, use the this:
Object example = jruby.eval("Example::Myclass.new");
Other than that, I don't know what the problem could be. For myself, I was able to run the following code under Java 1.6 and with jruby-engine.jar and jruby-complete-1.4.0.jar under my classpath.
package test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class MyJavaClass {
public static void main(String arg[]) throws ScriptException,
FileNotFoundException {
ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
jruby.eval(new BufferedReader(new FileReader("example.rb")));
Object example = jruby.eval("Example::Myclass.new");
jruby.put("a", example);
System.out.println(jruby.eval("$a.t_st"));
}
}

Categories