I would ultimately like to make a HTTP request to the NCBI Entrez database to retrieve some accession numbers. I'm starting out small here, so I wanted to make a functional HTTP request, regardless of the endpoint. But no matter the endpoint I use, a Unknown Host Exception is thrown. Why?
I have included all of my code, but the problem only happens in the method getEntireSubject.
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Subject {
private String id;
private String sequence;
// Position on ref sequence where alignment with query begins, inclusive
private int start;
// Position on ref sequence where alignment with query ends, inclusive
private int end;
public Subject(String accessNum, int hitFrom, int hitTo, String seq) {
id = accessNum;
sequence = seq;
start = hitFrom;
end = hitTo;
getEntireSubject();
}
// Getters
public String getSequence() {
return sequence;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
// Fetches accession number from NCBI
private void getEntireSubject() {
try {
String link = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/einfo.fcgi";
link = "https://jsonplaceholder.typicode.com/posts/1";
InputStream response = new URL(link).openStream();
try (Scanner scanner = new Scanner(response)) {
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println(responseBody);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Related
I want to create a method calculate the percent change of population growth from the years 1994-2013, and prints out each percentage change. I have the data all stored in, but I am not sure how to iterate the ArrayList to accomplish this
import java.io.*;
import java.util.*;
public class USCrimeClass
{
public int year;
public int population;
public int violentCrime;
public double violentCrimeRate;
public int manslaughter;
public double manslaughterRate;
public int rape;
public double rapeRate;
public int robbery;
public double robberyRate;
public int assault;
public double assaultRate;
public int propertyCrime;
public double propertyCrimeRate;
public int burglary;
public double burglaryRate;
public int larcenyTheft;
public double larcenyTheftRate;
public int vehicleTheft;
public double vehicleTheftRate;
public USCrimeClass(String line)
{
String[]split=line.split(",");
year=Integer.parseInt(split[0]);
population=Integer.parseInt(split[1]);
violentCrime=Integer.parseInt(split[2]);
violentCrimeRate=Double.parseDouble(split[3]);
manslaughter=Integer.parseInt(split[4]);
manslaughterRate=Double.parseDouble(split[5]);
rape=Integer.parseInt(split[6]);
rapeRate=Double.parseDouble(split[7]);
robbery=Integer.parseInt(split[8]);
robberyRate=Double.parseDouble(split[9]);
assault=Integer.parseInt(split[10]);
assaultRate=Double.parseDouble(split[11]);
propertyCrime=Integer.parseInt(split[12]);
propertyCrimeRate=Double.parseDouble(split[13]);
burglary=Integer.parseInt(split[14]);
burglaryRate=Double.parseDouble(split[15]);
larcenyTheft=Integer.parseInt(split[16]);
larcenyTheftRate=Double.parseDouble(split[17]);
vehicleTheft=Integer.parseInt(split[18]);
vehicleTheftRate=Double.parseDouble(split[19]);
}
Scanner read = null;
{
try
{
read=new Scanner(new File("C:\\Crime.csv"));
}
catch(FileNotFoundException e)
{
System.out.println("The file can't be opened");
System.exit(0);
}
List<USCrimeClass> crimeClasses = new ArrayList<>();
read.nextLine();
while(read.hasNextLine())
{
crimeClasses.add(new USCrimeClass(read.nextLine()));
}
read.close();
}
}
Some of the items I'm going to point out are more code review items that aren't specifically related to the business logic of what you're trying to do, however, in the long run your code will be more readable and maintainable.
First, it's a good idea to separate your data model from your controller logic. The controller handles the business logic whereas the data model stores the data and provides methods to access and change the data. You should also name the class appropriately - using the name USCrimeClass could be improved because it's obvious that this is a class, you don't have to use the word "class" in the name. You should also create getter and setter methods for your class member variables rather than allowing direct access. In the code sample below I have created a single getter and setter pair for the population field as an example.
public class USCrimeData {
private int year;
private int population;
private int violentCrime;
private double violentCrimeRate;
private int manslaughter;
private double manslaughterRate;
private int rape;
private double rapeRate;
private int robbery;
private double robberyRate;
private int assault;
private double assaultRate;
private int propertyCrime;
private double propertyCrimeRate;
private int burglary;
private double burglaryRate;
private int larcenyTheft;
private double larcenyTheftRate;
private int vehicleTheft;
private double vehicleTheftRate;
public USCrimeData(String line) {
String[] split = line.split(",");
year = Integer.parseInt(split[0]);
population = Integer.parseInt(split[1]);
violentCrime = Integer.parseInt(split[2]);
violentCrimeRate = Double.parseDouble(split[3]);
manslaughter = Integer.parseInt(split[4]);
manslaughterRate = Double.parseDouble(split[5]);
rape = Integer.parseInt(split[6]);
rapeRate = Double.parseDouble(split[7]);
robbery = Integer.parseInt(split[8]);
robberyRate = Double.parseDouble(split[9]);
assault = Integer.parseInt(split[10]);
assaultRate = Double.parseDouble(split[11]);
propertyCrime = Integer.parseInt(split[12]);
propertyCrimeRate = Double.parseDouble(split[13]);
burglary = Integer.parseInt(split[14]);
burglaryRate = Double.parseDouble(split[15]);
larcenyTheft = Integer.parseInt(split[16]);
larcenyTheftRate = Double.parseDouble(split[17]);
vehicleTheft = Integer.parseInt(split[18]);
vehicleTheftRate = Double.parseDouble(split[19]);
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}
Next let's talk about the controller. This is where the business logic will reside. This is where you will use your data model to arrive at the results you desire. Since you want to determine the percent population change you would use the list of crime data to get the population from the year 1994 (I assume this is the first entry in the list - index 0) and then get the last entry in the list (I assume the final entry is 2013) then calculate the value you want. If these assumptions are not correct or if you want to calculate growth for different years you would want to implement a getYear() method in your data model and then loop through your list of data until you find the object with the year you want.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Controller {
public static void main(String[] args) {
Scanner read = null;
try {
// Replace the "..." below with actual path to your data file.
read = new Scanner(new File("..."));
} catch (FileNotFoundException e) {
System.out.println("The file can't be opened");
System.exit(0);
}
List<USCrimeData> crimeClasses = new ArrayList<>();
while (read.hasNextLine()) {
crimeClasses.add(new USCrimeData(read.nextLine()));
}
read.close();
int initialPopulation = crimeClasses.get(0).getPopulation();
System.out.println("initialPopulation: "+initialPopulation);
int latestPopulation = crimeClasses.get(crimeClasses.size()-1).getPopulation();
System.out.println("latestPopulation: "+latestPopulation);
double percentGrowth = (double)(latestPopulation - initialPopulation) / initialPopulation * 100;
System.out.println("percentGrowth: "+percentGrowth);
}
}
You can iterate list like :
Iterator<USCrimeClass> iterator = crimeClasses.iterator();
while(iterator.hasNext()) {
USCrimeClass currentCrime = iterator.next();
// use currentCrime object to calcuate percent increase/decrease.
}
I am getting an IndexOutOfBoundsExpetion when reading a string from a flatbuffer for some reason.
my schema:
namespace com.busalarmclock.flatbuffers;
table Message {
routes:[Route];
stops:[Stop];
trips:[Trip];
}
table Route {
route_id:string;
route_name:string;
route_description:string;
trips:[Trip];
}
table Trip {
trip_id:string;
op_days:int;
stops:[TripStop];
}
table Stop {
stop_id:int;
stop_name:string;
stop_lon:double;
stop_lat:double;
}
table TripStop {
stop:Stop;
arrival_time:long;
departure_time:long;
dropoff_type:short;
}
root_type Message;
this is how I'm writing my buffer:
public static byte[] createStopMessage(TopDocs hits, IndexSearcher indexSearcher) throws IOException {
FlatBufferBuilder builder = new FlatBufferBuilder(1);
int[] stopData = new int[hits.totalHits];
for (int i = 0; i < hits.totalHits; i++)
stopData[i] = createStopObject(indexSearcher.doc(hits.scoreDocs[i].doc), builder);
int stopsOffset = Message.createStopsVector(builder, stopData);
Message.startMessage(builder);
Message.addStops(builder, stopsOffset);
int root = Message.endMessage(builder);
builder.finish(root);
return builder.sizedByteArray();
}
public static byte[] createTripStopsMessage(TripModel trip, IndexSearcher indexSearcher) {
FlatBufferBuilder builder = new FlatBufferBuilder(1);
int[] tripStopData = new int[trip.tripStopModels.length];
for (int i = 0; i < trip.tripStopModels.length; i++)
tripStopData[i] = createTripStopObject(trip.tripStopModels[i], builder);
System.out.printf("tripId:%s", trip.tripId);
int tripIdOffset = builder.createString(trip.tripId);
int tripStopsOffset = Trip.createStopsVector(builder, tripStopData);
Trip.startTrip(builder);
Trip.addTripId(builder, tripIdOffset);
Trip.addStops(builder, tripStopsOffset);
int tripOffset = Trip.endTrip(builder);
Message.startMessage(builder);
Message.addTrips(builder, tripOffset);
int messageOffset = Message.endMessage(builder);
builder.finish(messageOffset);
return builder.sizedByteArray();
}
public static int createTripStopObject(TripStopModel tripStopModel, FlatBufferBuilder builder) {
int stopOffset = createStopObject(tripStopModel.stop, builder);
return TripStop.createTripStop(builder, stopOffset, tripStopModel.arrivalTime,
tripStopModel.departureTime, tripStopModel.dropoffType);
}
and these are my models:
public class TripModel {
public String tripId;
public int opDays;
public TripStopModel[] tripStopModels;
public TripModel() {
}
public TripModel(String tripId) {
this.tripId = tripId;
}
public TripModel(String tripId, TripStopModel[] tripStationHits) {
this.tripStopModels = tripStationHits;
this.tripId = tripId;
}
public TripModel(String tripId, int opDays, TripStopModel[] tripStationHits) {
this.tripId = tripId;
this.opDays = opDays;
this.tripStopModels = tripStationHits;
}
import org.apache.lucene.document.Document;
/**
* Created by User on 09/07/2016.
*/
public class TripStopModel {
public long arrivalTime;
public long departureTime;
public short dropoffType;
public Document stop;
public TripStopModel() {
}
public TripStopModel(long arrivalTime, long departureTime, short dropoffType, Document stop) {
this.arrivalTime = arrivalTime;
this.departureTime = departureTime;
this.dropoffType = dropoffType;
this.stop = stop;
}
}
I have a lucene database, and I am trying to get some data from it to a flatbuffer message.
when creating the buffer I get no errors, but I get an IndexOutOfBoundsExeption when reading the buffer, from the first one.
I checked, and the String is not null when parsing.
There doesn't appear anything wrong with how you you create the buffer.
If you get an IndexOutOfBoundsException, that typically means the buffer got corrupted between when it got created and read. Can you check just before you read the buffer, that the size and the bytes it contains are the same compared to when you just created it? Are you sure you are using a binary file or transfer protocol?
fixed it :)
I was adding the tripOffset as the tripVector offset by mistake!
For what it's worth, I got a similar error when my ByteBuffer was too small. The write seemingly went fine, but, in reality, it got truncated. The read threw an IOOBE. When I increased the size of the buffer, everything worked fine.
I am building a Jersey Server with Maven Project and I have everything working fine except when I attempt to send a Request from a C# program I have that the user will be interacting with the array whose JSON appears as:
[{"Weight":0.0,"RFIDCode":0},{"Weight":55.5,"RFIDCode":1}]
When I send the code to the server I end up with an empty Java Array
My C# code is below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
using RestSharp;
namespace POSTJSONList
{
class Program
{
static void Main(string[] args)
{
List<ExampleMen> people = new List<ExampleMen>();
JsonSerializer ser = new JsonSerializer();
for (int i = 0; i < 5; i++)
{
ExampleMen person1 = new ExampleMen(i, i * 55.5);
people.Add(person1);
}
string json = JsonConvert.SerializeObject(people);
Console.WriteLine(json);
Console.ReadLine();
var client = new RestClient("http://localhost:9998");
var request = new RestRequest("/trash", Method.POST);
request.AddJsonBody(json);
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
Console.ReadLine();
}
}
}
My Java Code is below
#POST
#Produces("application/json")
#Consumes(MediaType.APPLICATION_JSON)
//#Param recycleList a list of all of the data that we have collected
public String createtrash_records(trashpickup_type trashList[]){
System.out.println("Im Here Guys!!!!");
// TODO update this to take the information we pass through to it and create individual objects based on it.
// TODO modify to return success code
billing billSystem = billing.getInstance();
systemTotalsTrash sysTotalsTrashSystem = systemTotalsTrash.getInstance();
int i = 1;
for(trashpickup_type alpha : trashList)
{
System.out.println(alpha.getRFIDCode() + alpha.getWeight());
i++;
/*try {
billSystem.updateBillingRecord(rec.getUserName(), 0, rec.getWeight());
sysTotalsTrashSystem.updateSystemTotals(rec.getWeight());
getDao().createIfNotExists(rec);
} catch (SQLException e) {
e.printStackTrace();
}
*/
}
return "It worked";
}
The Model Code (that which the JSON is mapped to) is Here
package com.gallup.gethip.model;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
#XmlRootElement
#DatabaseTable(tableName="trash_records")
public class trashpickup_type {
#DatabaseField(columnName = "RFIDCode")
private int RFIDCode;
#DatabaseField(columnName = "Weight")
private double Weight;
#DatabaseField(columnName = "PickedUp")
private Date PickedUp;
public trashpickup_type()
{
}
public void setRFIDCode(int RFIDCode)
{
this.RFIDCode = RFIDCode;
}
public void setWeight(double Weight)
{
this.Weight = Weight;
}
public void setPickedUP(Date PickedUp)
{
this.PickedUp = PickedUp;
}
public double getWeight()
{
return Weight;
}
public double getRFIDCode()
{
return RFIDCode;
}
public Date getPickedUp()
{
return PickedUp;
}
}
Any Suggestions are appreciated. I will post more information upon request if needed.
You serialize the people list to json and then use request.AddJsonBody to add it to the request. But AddJsonBody will again serialize the argument to json, so you end up with a double serialized value which - on the server side - cannot be parsed into trashList[]. Therefore remove the client-side serialization code and simply write
request.AddJsonBody(people);
Hi I'm having some trouble getting started with a problem in a Java course learning Swing and starting on JTables and getting data into them. It's going to be hard to explain so I'm just going to post the code I was given, along with the question.
The question is:
The getData() method needs to return an Object[][] containing the data represented by the class.
The first class is MusicAlbum
class MusicAlbum {
private String id;
private String name;
private String genre;
private boolean isCompilation;
private int track_count;
public MusicAlbum(String id, String name, String genre, boolean isCompilation, int track_count) {
this.id = id;
this.name = name;
this.genre = genre;
this.isCompilation = isCompilation;
this.track_count = track_count;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getGenre() {
return genre;
}
public boolean isCompilation() {
return isCompilation;
}
public int getTrackCount() {
return track_count;
}
public boolean equals(Object obj) {
if (obj instanceof MusicAlbum)
return this.id.equalsIgnoreCase(((MusicAlbum)obj).id);
return super.equals(obj);
}
}
The class I have to implement the methods in is MusicDataObject (at the bottom)
import java.util.Random;
import java.util.Scanner;
public class MusicDataObject {
private List<MusicAlbum> albums = new ArrayList<>();
private Random random = new Random(); // for generating IDs
public void addAlbum(MusicAlbum album) throws IllegalArgumentException {
if (searchAlbum(album.getId()) != null)
throw new IllegalArgumentException("Album ID is not new!");
albums.add(album);
}
public MusicAlbum searchAlbum(String id) {
for (MusicAlbum album : albums) {
if (album.getId().equalsIgnoreCase(id)) {
return album;
}
}
return null;
}
public MusicAlbum removeAlbum(String id) {
MusicAlbum album = searchAlbum(id);
albums.remove(album);
return album;
}
public void updateAlbum(MusicAlbum album)
throws IllegalArgumentException {
if (removeAlbum(album.getId()) == null)
throw new IllegalArgumentException("Album ID does not exist!");
addAlbum(album);
}
public String generateID() {
String formatter = "A%0" + (int)Math.ceil(Math.log10(albums.size() * 2) + 1) + "d";
String ID;
do {
ID = String.format(formatter, random.nextInt(albums.size() * 2 + 1));
} while (searchAlbum(ID) != null);
return ID;
}
public void saveData(String fileName) throws IOException {
// make sure that the file exists or try to create it
File fout = new File(fileName);
if (!fout.exists() && !fout.createNewFile())
return;
PrintWriter out = new PrintWriter(fout);
for (MusicAlbum album: albums) {
out.println(serializeAlbum(album));
}
out.close();
}
public String serializeAlbum(MusicAlbum album) {
return String.format(
"%s;%s;%s;%b;%d",
album.getId(),
album.getName(),
album.getGenre(),
album.isCompilation(),
album.getTrackCount());
}
public void loadFile(String fileName) throws FileNotFoundException {
albums = new ArrayList<>();
Scanner in = new Scanner(new File(fileName));
while (in.hasNext()) {
// --- split the next line with the character ";"
String line = in.nextLine();
String[] tokens = line.split(";");
// --- construct a new MusicAlbum using the resulting tokens. NOTE: This isn't very robust.
// If a line doesn't contain enough data or the data is invalid, this will crash
albums.add(new MusicAlbum(
tokens[0],
tokens[1],
tokens[2],
Boolean.parseBoolean(tokens[3]),
Integer.parseInt(tokens[4])
));
}
}
// ----- these methods need to be implemented
public Object[][] getData() {
// TODO
}
public String[] getColumnNames() {
// TODO
}
}
The sample data being used is in a txt file, formatted as so:
A01;Defiance;Soundtrack;true;24
A02;Insomniac;Punk Rock;false;14
A03;A Great Day For The Race;Gypsy Jazz;false;10
A04;Viva La Internet;Ska;false;31
A05;New Surrender;Rock;false;17
So basically it's this getData() method they want me to implement that is giving me grief. I don't fully understand what they want me to do, nor do I fully understand what the Object[][] does.
I hope I have been clear enough, and I will appreciate all help given. Also please try to explain things as best you can and dumb them down as much as possible, I'm new to a lot of this :)
Thanks for your time.
Object[][] is a 2-dimensional array. Each of its element is an Object[], a one-dimensional array.
Your task is to create a 2 dimensional array, having one element (Object[]) for each of your MusicAlbum. An Object[] should hold the properties of a MusicAlbum like id, name, genre, isCompilation and track_count.
You can create an object array like this:
Object[] arr = new Object[] { "some", "values", 23, true };
You can create a 2 dimensional array like this:
Object[][] arr2d = new Object[size][];
And you can iterate over all your MusicAlbums, create an Object[] for each of them containing the properties of that music album, and set it in the arr2d.
You can set/get elements of a 2-dimensional array just like any other arrays:
// Set first element:
arr2d[0] = arr;
// Get first element:
Object[] firstElement = arr2d[0];
The getColumnNames() method should just return a String[] (a String array) containing the column names, the names of the properties.
And it might be obvious but note that the order you return the column names and the order of the property values (in the elements of the Object[]) should be the same.
I have a JSF application using hibernate.
I load a set of points for a polygon and want to update the points.
I update the point information, but when I attempt to commit the changes, I get the following error:
WARNING: SQL Error: 8114, SQLState: S0005
SEVERE: Error converting data type nvarchar to decimal.
SEVERE: Could not synchronize database state with session
org.hibernate.exception.SQLGrammarException: could not update: [hibernate.TbPolygonPoint#937]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
I am confused, since I do not have any character information in the object I am attempting to update.
Does anyone know why I get this error and how can I resolve it?
Thanks.
Here is the update code. I get the error when attempting to do the commit:
public int updatePolygonPoint( long polyPointId, int sGroup, int group, double lat, double lon )
{
int stat = 0;
TbPolygonPoint point = null;
try
{
BigDecimal bdLat = new BigDecimal(lat);
BigDecimal bdLon = new BigDecimal(lon);
org.hibernate.Transaction tx = session.beginTransaction();
point = (TbPolygonPoint)session.get(TbPolygonPoint.class, polyPointId);
point.setIsuperGroupId(sGroup);
point.setIgroupId(group);
point.setDcLatitude(bdLat);
point.setDcLongitude(bdLon);
try
{
session.update(point);
tx.commit();
this.session = HibernateUtil.getSessionFactory().openSession();
stat = 1;
}
catch(Exception e)
{
tx.rollback();
e.printStackTrace();
status = e.getMessage();
stat = -1;
}
}
catch( Exception ex )
{
ex.printStackTrace();
status = ex.getMessage();
stat = -1;
}
return stat;
}
Here is the java code for the object.
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
/**
* TbPolygonPoint generated by hbm2java
*/
public class TbPolygonPoint implements java.io.Serializable {
private long biPolygonPointId;
private TbPolygonLoadFile tbPolygonLoadFile;
private int isuperGroupId;
private int igroupId;
private BigDecimal dcLatitude;
private BigDecimal dcLongitude;
private Set<TbPolygonHasPoints> tbPolygonHasPointses = new HashSet<TbPolygonHasPoints>(0);
public TbPolygonPoint() {
}
public TbPolygonPoint(long biPolygonPointId, int isuperGroupId, int igroupId, BigDecimal dcLatitude, BigDecimal dcLongitude) {
this.biPolygonPointId = biPolygonPointId;
this.isuperGroupId = isuperGroupId;
this.igroupId = igroupId;
this.dcLatitude = dcLatitude;
this.dcLongitude = dcLongitude;
}
public TbPolygonPoint(long biPolygonPointId, TbPolygonLoadFile tbPolygonLoadFile, int isuperGroupId, int igroupId, BigDecimal dcLatitude, BigDecimal dcLongitude, Set<TbPolygonHasPoints> tbPolygonHasPointses) {
this.biPolygonPointId = biPolygonPointId;
this.tbPolygonLoadFile = tbPolygonLoadFile;
this.isuperGroupId = isuperGroupId;
this.igroupId = igroupId;
this.dcLatitude = dcLatitude;
this.dcLongitude = dcLongitude;
this.tbPolygonHasPointses = tbPolygonHasPointses;
}
public long getBiPolygonPointId() {
return this.biPolygonPointId;
}
public void setBiPolygonPointId(long biPolygonPointId) {
this.biPolygonPointId = biPolygonPointId;
}
public TbPolygonLoadFile getTbPolygonLoadFile() {
return this.tbPolygonLoadFile;
}
public void setTbPolygonLoadFile(TbPolygonLoadFile tbPolygonLoadFile) {
this.tbPolygonLoadFile = tbPolygonLoadFile;
}
public int getIsuperGroupId() {
return this.isuperGroupId;
}
public void setIsuperGroupId(int isuperGroupId) {
this.isuperGroupId = isuperGroupId;
}
public int getIgroupId() {
return this.igroupId;
}
public void setIgroupId(int igroupId) {
this.igroupId = igroupId;
}
public BigDecimal getDcLatitude() {
return this.dcLatitude;
}
public void setDcLatitude(BigDecimal dcLatitude) {
this.dcLatitude = dcLatitude;
}
public BigDecimal getDcLongitude() {
return this.dcLongitude;
}
public void setDcLongitude(BigDecimal dcLongitude) {
this.dcLongitude = dcLongitude;
}
public Set<TbPolygonHasPoints> getTbPolygonHasPointses() {
return this.tbPolygonHasPointses;
}
public void setTbPolygonHasPointses(Set<TbPolygonHasPoints> tbPolygonHasPointses) {
this.tbPolygonHasPointses = tbPolygonHasPointses;
}
}
I found the answer here:
http://dertompson.com/2008/01/03/bigdecimal-and-jdbc-since-java-5-0-2/
Apparently the conversion process converts the double to a string that may contain too many values behind the decimal. That is then converted to the BigDecimal. This conversion process is where the error comes from.
I solved this by using decimalFormat() to retain the number of significant digits I wanted and using that string in the new BigDecimal() conversion.
edejong 2014-08-20: Old url was dead, rewrote to new url