Java Trouble compiling maxmind geoip LookupService class - java

I wonder if some one can please help as I am struggling to compile maxmind.geoip.LookupService.java
I have downloaded geoip-api-1.2.10.jar for inclusion in WEB-INF\lib and I have referenced it in my classes path, but it just won't compile.
I have compiled the following successfully so I'm a bit at a loss:
com.maxmind.geoip.Country
com.maxmind.geoip.DatabaseInfo
com.maxmind.geoip.Location
com.maxmind.geoip.Region
com.maxmind.geoip.timeZone
Can't seem to find a full set of compiled java classes for com.maxmind.geoip, any help would be much appreciated :-)

I resolved this by downloading the latest java files from http://dev.maxmind.com/geoip/legacy/downloadable/ unpacked the folder and then opened a command prompt and typed the following:
cd source/com/maxmind/geoip/
javac *.java
I'm using jdk1.6.0_34 and all classes compiled with no errors.
I copied the com.maxmind.geoip folder to \WEB-INF\classes and downloaded geoip-api-1.2.10.jar and placed that in the WEB-INF\lib folder.
Finally I download GeoIP.dat from http://dev.maxmind.com/geoip/legacy/geolite/ and placed it in a new folder called GeoIP under webapps so that all my applications can use it.
The following code is to obtain the country code from a users IP Address:
import com.maxmind.geoip.*;
import java.io.IOException;
class CountryLookupTest {
public static void main(String[] args) {
try {
String sep = System.getProperty("file.separator");
String dir = "C:/Program Files/Apache Software Foundation/Tomcat 7.0/GeoIP";
String dbfile = dir + sep + "GeoIP.dat";
LookupService cl = new LookupService(dbfile,LookupService.GEOIP_MEMORY_CACHE);
System.out.println(cl.getCountry("151.38.39.114").getCode());
System.out.println(cl.getCountry("151.38.39.114").getName());
System.out.println(cl.getCountry("12.25.205.51").getName());
System.out.println(cl.getCountry("64.81.104.131").getName());
System.out.println(cl.getCountry("200.21.225.82").getName());
cl.close();
}
catch (IOException e) {
System.out.println("IO Exception");
}
}
}
Hope this proves useful to others.

According to the MaxMind dev site, the API is available on the Maven Central Repository. You shouldn't need to compile anything unless you downloaded the source package.

You have to download a Jar file called geoIP-api from this link to maven repository,In case you haven't downloaded the other Jar files from go this geoIP2 also don't forget to download the .DAT file from geoIP.dat. Then add the files to your project class path from project properties and then libraries finally add Jar in netbeans.
Now use this code:
public String IpGeoLocation(String IP) {
try {
String dbfile = "C:\\Users\\User Name \\Documents\\NetBeansProjects\\IP Tools\\resources/GeoIP.dat";
String location = "";
LookupService cl = new LookupService(dbfile, LookupService.GEOIP_MEMORY_CACHE);
location = cl.getCountry(IP).getName() + " " + cl.getCountry(IP).getCode();
cl.close();
return location;
} catch (Exception e) {
return "Error";
}
}
I was able to find the country and country code only !!

Related

class file contains wrong class error while accessing jar file

I am trying to create a JAR file for my two source codes Serial.java and DBaccess.java.
I am doing this as a learning exercise ,the classes do not do anything,they are dummy classes.
OS - Windows 10
JDK - GraalVM
Listing of my source code.(Serial.java)
public class Serial
{
void open()
{
System.out.println("Serial Port Opened - 0");
}
}
Listing of my source code.(DBaccess.java)
public class DBaccess
{
String DBname = "MySerialDB";
void write()
{
System.out.println("Data Written to DB - W");
}
void read()
{
System.out.println("Data Read from DB - R");
}
}
I have compiled them to .class files using javac
javac DBaccess.java
javac Serial.java
I created a folder
H:\myclass\com\mydomain\util
and manually copied the class files to util directory
and created a jar file myjar.jar of this format
H:\myclass>H:\graalvm\bin\jar tf myjar.jar
META-INF/
META-INF/MANIFEST.MF
com/
com/mydomain/
com/mydomain/util/
com/mydomain/util/DBaccess.class
com/mydomain/util/Serial.class
I want my source code JMainEntry.java to access the classes in the above jar file myjar.jar.
JMainEntry.java
//Main Class of the Program
import com.mydomain.util.*;
public class JMainEntry
{
public static void main (String[] Args)
{
Serial myS = new Serial();
myS.open();
DBaccess myDB = new DBaccess();
myDB.write();
myDB.read();
}
}
When i compile the code
H:\jar-compile>H:\graalvm\bin\javac -cp myjar.jar JMainEntry.java
I am getting the error
bad class file: myjar.jar(/com/mydomain/util/Serial.class)
class file contains wrong class: Serial
Please remove or make sure it appears in the correct subdirectory of the classpath.
I am not able to understand why javac is complaining like this,Can anyone help?
bad class file: myjar.jar(/com/mydomain/util/Serial.class)
Make sure you declare
package com.mydomain.util
at the top of all .java files in the directory com/mydomain/util, including Serial.java. To understand this better, read about packages.

Unable to correctly import opencsv module for java [package com.opencsv does not exist]

Here is a simple java code that I wrote where I'd like to parse my csv file using the opencsv module:
import com.opencsv.CSVReader;
import java.io.FileReader;
import java.io.IOException;
public class csv_open {
public static void main(String[] args) {
String csvFile = "FebStatement.csv";
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(csvFile));
String[] line;
while ((line = reader.readNext()) != null) {
System.out.println("Expense [date= " + line[0] + ", amount= " + line[1] + " , name=" + line[2] + "]");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In my directory where I have the csv_open.java file, I also have the opencsv-4.1.jar file.
The command that I am using to compile the code on command line is:
javac -classpath opencsv-4.1.jar: csv_open.java
But that's giving me the following output:
package com.opencsv does not exist - pls see image
I'm refraining from using IntelliJ or Eclipse at the moment or to build this program with Maven or Groovy, etc.
Can I still simply compile and run the code on the command line like above by fixing what's wrong?
Any help would be greatly appreciated!
Thanks in advance!
I was having a similar issue with compiling the com.opencsv.CSVWriter. I ended up using the below code to compile in the command line and it worked! I am still learning how to set classpaths and what-not so there may be an easier way but this worked for me.
javac -classpath C:\project\lib\opencsv-4.2.jar -d C:\project\bin\ -sourcepath C:\project\src\ PrepForCPP.java
Compile code breakdown:
javac = jvm compiler
-classpath = full path of where the jar file is stored
-d = where the various class files for my program are stored
-sourcepath = where all of the different java files for my program are stored
C:\project\src\ = setting the filepath
PrepForCPP.java = file name with main method
You may not need the -d and -sourcepath since it looks like you're only using one file. If I'm understanding the info I'm finding on classpaths correctly, your environmental variable isn't set quite right so the jvm isn't able to find the opencsv-4.2.jar. I don't think I did either, but including the full file path seems to be a decent work-around for now.
**this does require that the classpath environment variable be set. Otherwise you could include the full filepath of javac.

The config.properties file is not read in java

My folder structure is as follows:
>test
>src
>org.mypackage
>myclass
>resources
>config.properties
The java class is as follows:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public myclass {
private String path = "config.properties";
public myclass() {
Properties prop = new Properties();
InputStream input = null;
try {
input = getClass().getClassLoader().getResourceAsStream(path);
prop.load(input)
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
But I get null as the value for input during debug.
In the debug mode I checked the value for getClass(), I get the class value, the value is also available for getClass().getClassLoader() but for getClass().getClassLoader().getResourceAsStream(path) it is null.
I am not sure what the issue could be.
Thanks for the help!
It seems that resources is not a source folder in your Eclipse project. Try setting resources as a source folder:
Right click > Build Path > Use as Source Folder
You should check this question right here, which should help you in answering your problem: How to add a Java Properties file to my Java Project in Eclipse
Moreover, it seems to me that your project isn't 100% Maven compliant. You should have something more like:
>src
>main
>java
>resources
>test
>java
>resources
Then Eclipse should be less lost when handling and loading your properties.
If you have any questions, feel free message me

How to add OpenCV lib to Dynamic Web Project

Currently, I am building a Java web project that use Opencv to detect images that are similar. But when I run, I always get this error
java.lang.UnsatisfiedLinkError: Expecting an absolute path of the
library: opencv_java249 java.lang.Runtime.load0(Runtime.java:806)
java.lang.System.load(System.java:1086)
com.hadoop.DriverServlet.doPost(DriverServlet.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I also search this problem but still can not find any solutions for my case. even I try this http://examples.javacodegeeks.com/java-basics/java-library-path-what-is-it-and-how-to-use/ to add to java.library path point to opencv-249 jar in eclipse but still not be resolved.
Anyone can help me? Thanks in advance.
To work with opencv you need jar file and binary file.
JAR file can be simply added by local maven repository or any other variant.
Binary file you need to add and load manually.
Something like this:
private static void addLibraryPath(String pathToAdd) throws Exception{
final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
usrPathsField.setAccessible(true);
//get array of paths
final String[] paths = (String[])usrPathsField.get(null);
//check if the path to add is already present
for(String path : paths) {
if(path.equals(pathToAdd)) {
return;
}
}
//add the new path
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
newPaths[newPaths.length-1] = pathToAdd;
usrPathsField.set(null, newPaths);
}
public void init() {
String pathToOpenCvDll = "c:\\opencv\\"; //linux path works too
try {
addLibraryPath(pathToOpenCvDll);
System.loadLibrary("opencv_java320");
} catch (Exception ignored) {
}
}
}
For web project, the lib jar file should be in the WEB-INF/lib dir.
Also make sure the jars in the dir are in the classpath

Class not found exception when trying to create web service client

I am trying to consume a web service from a Java client.
I generated the classes using wsimport:
wsimport -keep -verbose http://localhost:5382/Service1.svc?wsdl
Code looks something like:
private String CreateSalesforceIssue() {
IssueService service = new IssueService();
IIssueService binding = service.getBasicHttpBindingIIssueService();
String issueID = binding.createIssue(type, description, steps,
expected, workaround, storage,
docType, actions, tools, external,
repeatability, workaroundType, severity,
pmSeverity, products, extensions, versions,
os, status, project, resolution, fixversions);
return issueID;
}
When it hits this line:
IssueService service = new IssueService();
Stepping into the code far enough and it gets to javax.xml.ws.spi.Provider and fails there.
On
public static Provider provider() {
try {
Object provider =
FactoryFinder.find(JAXWSPROVIDER_PROPERTY,
DEFAULT_JAXWSPROVIDER);
if (!(provider instanceof Provider)) {
Class pClass = Provider.class;
String classnameAsResource = pClass.getName().replace('.', '/') + ".class";
ClassLoader loader = pClass.getClassLoader();
if(loader == null) {
loader = ClassLoader.getSystemClassLoader();
}
URL targetTypeURL = loader.getResource(classnameAsResource);
throw new LinkageError("ClassCastException: attempting to cast" +
provider.getClass().getClassLoader().getResource(classnameAsResource) +
"to" + targetTypeURL.toString() );
}
return (Provider) provider;
} catch (WebServiceException ex) {
throw ex;
} catch (Exception ex) {
throw new WebServiceException("Unable to createEndpointReference Provider", ex);
}
}
on this line:
if (!(provider instanceof Provider)) {
with a ClassNotFoundException: Provider com.sun.xml.ws.spi.ProviderImpl
I feel like I am missing something, unfortunately I am not sure what... Do I need to initialize the provider anywhere?
You should add Provider class into your classpath.
If you use IDE you can add the library easily by right click on library and choose "add Jar file" (or something like that!). But if you try to compile and run your application via terminal use the following commands:
javac -d [bin folder] -cp [jar files] [java source files]
java -classpath [jar files] [Main class]
you should split the jar files using : in Linux and MAC OS and ; in MS Windows. As you said this is a web service, I think you are using IDE and first solution may help you.
P.S. If you also added this jar file into class path and this exception occurs again, please add this jar file into your web server/container library directory. (for example lib folder in tomcat.

Categories