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.
Related
Its not compiling and i have no idea why... New to sqlite and tried to follow some question's answer on stack overflow but not able to figure it out. Modal class is MainDataHelper
Code
MainDataHelper myDatabaseHelper = new MainDataHelper(getActivity());
myDatabaseHelper.openDataBase();
String text = myDatabaseHelper.getMostMessagesSent(); //this is the method to query
myDatabaseHelper.close();
mMostMessagesSent.setText(text);
mMostMessagesSent.setTextColor(Color.WHITE);
Helper
public class MainDataHelper extends Activity {
private int TotalMessagesSent;
private int TotalMessagesRecieved;
private int TotalMessages;
private String TotalTimeSpent;
private String MostMessagesSent;
private String MostMessagesRecieved;
private String MostTexted;
private String MostTimeSpent;
private int QuizTaken;
private int QuizTakers;
private int Reviewed;
private int Reviews;
public MainDataHelper() {
TotalMessagesSent = 0;
TotalMessagesRecieved = 0;
TotalMessages = 0;
TotalTimeSpent = "";
MostMessagesSent = "";
MostMessagesRecieved = "";
MostTexted = "";
MostTimeSpent = "";
QuizTaken = 0;
QuizTakers = 0;
Reviewed = 0;
Reviews = 0;
}
public MainDataHelper( int TotalMessagesSent, int TotalMessagesRecieved, int TotalMessages, String TotalTimeSpent,String MostMessagesSent, String MostMessagesRecieved, String MostTexted, String MostTimeSpent,int QuizTaken, int QuizTakers, int Reviewed, int Reviews) {
TotalMessagesSent = TotalMessagesSent;
TotalMessagesRecieved = TotalMessagesRecieved;
TotalMessages = TotalMessages;
TotalTimeSpent = TotalTimeSpent;
MostMessagesSent = MostMessagesSent;
MostMessagesRecieved = MostMessagesRecieved;
MostTexted = MostTexted;
MostTimeSpent = MostTimeSpent;
QuizTaken = QuizTaken;
QuizTakers = QuizTakers;
Reviewed = Reviewed;
Reviews = Reviews;
}
public int getTotalMessagesSent() {
return TotalMessagesSent;
}
public int getTotalMessagesRecieved() {
return TotalMessagesRecieved;
}
public int getTotalMessages() {
return TotalMessages;
}
public String getTotalTimeSpent() {
return TotalTimeSpent;
}
public String getMostMessagesSent() {
return MostMessagesSent;
}
public String getMostMessagesRecieved() {
return MostMessagesRecieved;
}
public String getMostTexted() {
return MostTexted;
}
public String getMostTimeSpent() {
return MostTimeSpent;
}
public int getQuizTaken() {
return QuizTaken;
}
public int getQuizTakers() {
return QuizTakers;
}
public int getReviewed() {
return Reviewed;
}
public int getReviews() {
return Reviews;
}
public void setTotalMessagesSent(int TotalMessagesSent) {
TotalMessagesSent = TotalMessagesSent;
}
public void setTotalMessagesRecieved(int TotalMessagesRecieved) {
TotalMessagesRecieved = TotalMessagesRecieved;
}
public void setTotalMessages(int TotalMessages) {
TotalMessages = TotalMessages;
}
public void setTotalTimeSpent(String TotalTimeSpent) { TotalTimeSpent = TotalTimeSpent; }
public void setMostMessagesSent(String MostMessagesSent) {
MostMessagesSent = MostMessagesSent;
}
public void setMostMessagesRecieved(String MostMessagesRecieved) {
MostMessagesRecieved = MostMessagesRecieved;
}
public void setMostTexted(String MostTexted) {
MostTexted = MostTexted;
}
public void setMostTimeSpent(String MostTimeSpent) { MostTimeSpent = MostTimeSpent; }
public void setQuizTaken(int QuizTaken) {
QuizTaken = QuizTaken;
}
public void setQuizTakers(int QuizTakers) {
QuizTakers = QuizTakers;
}
public void setReviewed(int Reviewed) { Reviewed = Reviewed; }
public void setReviews(int Reviews) {
Reviews = Reviews;
}
}
......................................................................................................................................................................................................................
It's not compiling due to a few reasons.
First MainDataHelper does not have a constructor that accepts/takes an Activity. MainDataHelper has two constructors one takes no parameters, the other takes 12 parameters. You have to use one of the available constructors when instantiating a MainDataHelper object.
e.g. MainDataHelper myDatabaseHelper = new MainDataHelper(); would compile.
There is no openDatabase method in MainDataHelper, you would either have to add such a method or do away with the line myDatabaseHelper.openDataBase();
There is no close method in MainDataHelper, you would either have to add such a method or do away with the line myDatabaseHelper.close();
Considering that you want to use an SQLite database then you will use a sub-class of the SQLiteOpenHelper class that would be invoked from an Activity or a Fragment (or even many of these).
Before even considering writing a line of code you would need to understand you requirements for the database and have some sort of design (schema). Ignoring that and assuming (for demonstration) that you want a simple database with one table called questions and has one column called question then the following could be such a class (in this case MainDataBaseHelper.java) :-
public class MainDatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASENAME = "question.db"; //<<<<<<<<<< name of the database
public static final int DATABASEVERSION = 1; //<<<<<<<<<< version number of the database
public static final String TABLE_QUESTION = "question"; //<<<<<<<<<< name of the quiz table
public static final String COLUMN_QUESTION_QUESTION = "question";
public MainDatabaseHelper(Context context) {
super(context, DATABASENAME, null, DATABASEVERSION);
}
//<<<<<<<<<< Called ONCE when the database is first created (first time an attempt is made to open if)
#Override
public void onCreate(SQLiteDatabase db) {
String crt_questiontable_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUESTION + "(" +
COLUMN_QUESTION_QUESTION + " TEXT" +
")";
db.execSQL(crt_questiontable_sql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addQuestion(String question) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_QUESTION_QUESTION,question);
return this.getWritableDatabase().insert(TABLE_QUESTION,null,cv);
}
public Cursor getAllQuestions() {
return this.getWritableDatabase().query(TABLE_QUESTION,null,null,null,null,null,null);
}
}
With the above class existing your code could then be (as a simple example) :-
MainDatabaseHelper myDBHlpr = new MainDatabaseHelper(getActivity()); // Instantiate a MainDatabasehelper object called myDBHlpr
// Add some questions to the questions table
myDBHlpr.addQuestion("This is the first question");
myDBHlpr.addQuestion("This is another question");
myDBHlpr.addQuestion("Yet another question");
// Now get all of the questions
Cursor csr = myDBHlpr.getAllQuestions();
Log.d("DBINFO","There are " + String.valueOf(csr.getCount()) + " questions in the database.");
// Loop through all the questions
while (csr.moveToNext()) {
Log.d("DBINFO",
"Question " +
String.valueOf(csr.getPosition() + 1) +
" is " + csr.getString(csr.getColumnIndex(MainDatabaseHelper.COLUMN_QUESTION_QUESTION))
);
mMostMessagesSent.setText(csr.getString(csr.getColumnIndex(MainDatabaseHelper.COLUMN_QUESTION_QUESTION));
}
csr.close(); //<<<<<<<<<< Should always close Cursor when done with it.
//mMostMessagesSent.setText(text); //<<<<<<<<<< done in the loop through the cursor (for demonstration very likely only the last question will be seen)
mMostMessagesSent.setTextColor(Color.WHITE);
When run (for the first time) the log would then include :-
11-12 20:17:16.345 1376-1376/? D/DBINFO: There are 3 questions in the database.
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 1 is This is the first question
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 2 is This is another question
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 3 is Yet another question
Additionally the last question (which may or may not be the last question added) will be displayed in the TextView.
Note 3 rows would be added to the table each time the above is run.
Note this is purely intended as an introduction/demonstration there is a great deal more that needs to be done, such as designing the database.
I have the following code in my flink project:
public class Test {
public static void main(String[] args) throws Exception {
// set up the execution environment
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Event> events =
env.readCsvFile(args[0]).pojoType(
Event.class,
"time",
"vid",
"speed",
"xWay",
"lane",
"dir",
"seg",
"pos"
);
System.out.println("----> " + events.count());
}
}
And this is the class Event:
class Event {
public int time;
public int vid;
public int speed;
public int xWay;
public int lane;
public int dir;
public int seg;
public int pos;
public Event() { }
public Event(int time_in, int vid_in, int speed_in, int xWay_in, int lane_in, int dir_in, int seg_in, int pos_in) {
this.time = time_in;
this.vid = vid_in;
this.speed = speed_in;
this.xWay = xWay_in;
this.lane = lane_in;
this.dir = dir_in;
this.seg = seg_in;
this.pos = pos_in;
}
}
The project compiles but when I run it, there is an error:
java.lang.ClassCastException: org.apache.flink.api.java.typeutils.GenericTypeInfo cannot be cast to org.apache.flink.api.java.typeutils.PojoTypeInfo
The CSV file has 8 integer values separated by a comma in each line.
The documentation has the following example:
DataSet<Person>> csvInput = env.readCsvFile("hdfs:///the/CSV/file")
.pojoType(Person.class, "name", "age", "zipcode");
I don't know if the POJO definition is wrong, surely it is. I achieved what I wanted using map and readTextFile but this could be more expensive.
The ClassCastException is a bug that will be fixed soon and replaced by a more meaningful exception. Event is a GenericType instead of a PojoType. I think the reason might be that Event is member class instead of a global accessible class. Adding the static modifier should solve the problem.
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);
}
}
}
I am trying to create a class that will create matrices by taking an array as an input (among other things). This array will be assigned to a record (Record9). However I am getting this error when trying to compile. You can find my code below:
public class Matrix3x3flat {
private class Record9 {
public long r1c1;
public long r1c2;
public long r1c3;
public long r2c1;
public long r2c2;
public long r2c3;
public long r3c1;
public long r3c2;
public long r3c3;
}
private Record9 mat;
public Record9(long[] arr) {
Record9 this.mat = new Record9();
this.mat.r1c1 = arr[0];
this.mat.r1c2 = arr[1];
this.mat.r1c3 = arr[2];
this.mat.r2c1 = arr[3];
this.mat.r2c2 = arr[4];
this.mat.r2c3 = arr[5];
this.mat.r3c1 = arr[6];
this.mat.r3c2 = arr[7];
this.mat.r3c3 = arr[8];
return this.mat;
}
}
I don't understand the problem but I do suspect it has something to do with me not properly referencing this.mat in the return statement.
Well, few things I notice. Edit: as mentioned below, constructor name needs to be the same as class name.
2) Why are you re declaring mat as a type of Record9. You already set it up top as a type of Record9, no need to define it again, you can just say this.mat = whatever it needs to be
My idea is you want to create instance of Record9 on public Record9(long[] arr), currently you use return statement i side of constructor it is not allow. so you need to convert that to a method.
try like this :
public class Matrix3x3flat {
private class Record9 {
public long r1c1;
public long r1c2;
public long r1c3;
public long r2c1;
public long r2c2;
public long r2c3;
public long r3c1;
public long r3c2;
public long r3c3;
}
private Record9 mat;
public Record9 instance(long[] arr) {
this.mat = new Record9();
this.mat.r1c1 = arr[0];
this.mat.r1c2 = arr[1];
this.mat.r1c3 = arr[2];
this.mat.r2c1 = arr[3];
this.mat.r2c2 = arr[4];
this.mat.r2c3 = arr[5];
this.mat.r3c1 = arr[6];
this.mat.r3c2 = arr[7];
this.mat.r3c3 = arr[8];
return this.mat;
}
}
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