Challenging token error - java

I improved the structure after a good observation from [http://stackoverflow.com/users/1690199/v-k] I am still getting a token error even though the syntax looks correct to me. More comments and critiques will be useful and acknowledged here.
import de.bezier.data.sql.*;
PostgreSQL pgsql;
Float val;
void setup()
{
size( 100, 100 );
println(val);
}
Token error identified in Processing 2 at Class Database.
Class Database
{
String user = "user";
String pass = "pass";
String database = "db";
Float val;
Database (Float col) {
val = col;
}
void database_connection( col )
{
//sets up database
pgsql = new PostgreSQL( this, "127.0.0.1", database, user, pass );
if ( pgsql.connect() )
{
pgsql.query( "SELECT col FROM table ORDER BY col DESC LIMIT 1; " );
return( pgsql.getFloat("col") );
}
else
{
println ("failed to connect to the database");
}
}
}
OLD ISSUE: Class structure addressed after a great observation from [http://stackoverflow.com/users/1690199/v-k]
import de.bezier.data.sql.*;
.....
.....
Old code removed for clarity of this issue.

Classes don't take arguments. Also it is class not Class... Am i missing something? Look, a general sample:
class Database {
String user = "user";
String pass = "pass";
String database = "db";
float val; //by convention no Caps for vars...
// a constructor, which get partameters
Database (float v) {
val = v;
}
// a method
void database_setup() {
//whateverq
}
}//end of Database class

First, you should create a new question if you have a second question. Second, you never create the variable pgsql, you just start using it immediately. Move this line:
PostgreSQL pgsql;
to this group of lines:
String user = "user";
String pass = "pass";
String database = "db";
float val;
It's a variable that gets used in that class, so put it in that class. Also, use "float" with a lowercase "f" :)

Related

SQL Update in another class

Thanks for helping me out with my problem.
So I tried to insert a SQL Update using a method in a class named Functions, the main program doesn't give any error, and whenever I use the function, it just don't change anything in the SQL table after refreshing.
Here is my updateSQL method in class Functions :
public static void updateSQL(String sql, String updatenames[])
{
Connection connected = null;
PreparedStatement prepared = null;
connected = connexionmysql.connexionDB();
try
{
prepared = connected.prepareStatement(sql);
for(int i = 1; i < updatenames.length+1 ; i++) {
prepared.setString(i, updatenames[i-1]);
}
prepared.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
And here is how I call this function in my main class :
String datan[] = { inputPASS, type1, inputEMAIL, inputNAME };
Functions.updateSQL("UPDATE users SET userPASS = ? ,userTYPE = ? ,userEMAIL = ? WHERE userNAME = ? ", datan);
I did solve the problem. The functions I did write are working as expected, but the problem was in the way I was calling the method.
Instead of calling the function in a static way, I was calling it in an "usual" way so Eclipse didn't give me any error in that line.

CommandTable Cystal Report Error

I have a Crystal Report that was written using a complex SQL and I'm trying to invoke that using the Crystal Report Java API. This report has a Command object associated with it.
I load the report and set the connection parameters.
Then I try to set the Connection information to the current JDBC Profile. Meaning Test Environment credentials.
I get an exception. I tried with Version 11. Version 12 both. None of them seems to be working.
I'm getting the exception when I invoke the following piece of code. This piece of code works just fine with reports without "Command" sqls.
try{
clientDoc.getDatabaseController().setTableLocation(
origTable, newTable);
}catch(Exception ex){
ex.printStackTrace();
}
See below for the entire code. Please reply if anyone knows how to work around this.
private static void changeDataSource(ReportClientDocument clientDoc,
String reportName, String tableName, String username,
String password, String connectionURL, String driverName,
String jndiName) throws ReportSDKException {
PropertyBag propertyBag = null;
IConnectionInfo connectionInfo = null;
ITable origTable = null;
ITable newTable = null;
// Declare variables to hold ConnectionInfo values.
// Below is the list of values required to switch to use a JDBC/JNDI
// connection
String TRUSTED_CONNECTION = "false";
String SERVER_TYPE = "JDBC (JNDI)";
String USE_JDBC = "true";
String DATABASE_DLL = "crdb_jdbc.dll";
String JNDI_OPTIONAL_NAME = jndiName;
String CONNECTION_URL = connectionURL;
String DATABASE_CLASS_NAME = driverName;
// Declare variables to hold database User Name and Password values
String DB_USER_NAME = username;
String DB_PASSWORD = password;
System.out.println("Trusted_Connection:" + TRUSTED_CONNECTION);
System.out.println("Server Type:" + SERVER_TYPE);
System.out.println("Use JDBC:" + USE_JDBC);
System.out.println("Database DLL:" + DATABASE_DLL);
System.out.println("JNDIOptionalName:" + JNDI_OPTIONAL_NAME);
System.out.println("Connection URL:" + CONNECTION_URL);
System.out.println("Database Class Name:" + DATABASE_CLASS_NAME);
System.out.println("DB_USER_NAME:" + DB_USER_NAME);
System.out.println("DB_PASSWORD:" + DB_PASSWORD);
// Obtain collection of tables from this database controller
if (reportName == null || reportName.equals("")) {
Tables tables = clientDoc.getDatabaseController().getDatabase()
.getTables();
for (int i = 0; i < tables.size(); i++) {
origTable = tables.getTable(i);
if (tableName == null || origTable.getName().equals(tableName)) {
newTable = (ITable) origTable;
newTable.setQualifiedName(origTable.getAlias());
connectionInfo = newTable.getConnectionInfo();
// Set new table connection property attributes
propertyBag = new PropertyBag();
// Overwrite any existing properties with updated values
propertyBag.put("Trusted_Connection", TRUSTED_CONNECTION);
propertyBag.put("Server Type", SERVER_TYPE);
propertyBag.put("Use JDBC", USE_JDBC);
propertyBag.put("Database DLL", DATABASE_DLL);
propertyBag.put("JNDIOptionalName", JNDI_OPTIONAL_NAME);
propertyBag.put("Connection URL", CONNECTION_URL);
propertyBag.put("Database Class Name", DATABASE_CLASS_NAME);
connectionInfo.setAttributes(propertyBag);
connectionInfo.setUserName(DB_USER_NAME);
connectionInfo.setPassword(DB_PASSWORD);
// Update the table information
try{
clientDoc.getDatabaseController().setTableLocation(
origTable, newTable);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
// Next loop through all the subreports and pass in the same
// information. You may consider
// creating a separate method which accepts
if (reportName == null || !(reportName.equals(""))) {
IStrings subNames = clientDoc.getSubreportController()
.getSubreportNames();
for (int subNum = 0; subNum < subNames.size(); subNum++) {
Tables tables = clientDoc.getSubreportController()
.getSubreport(subNames.getString(subNum))
.getDatabaseController().getDatabase().getTables();
for (int i = 0; i < tables.size(); i++) {
origTable = tables.getTable(i);
if (tableName == null
|| origTable.getName().equals(tableName)) {
newTable = (ITable) origTable;
newTable.setQualifiedName(origTable.getAlias());
// Change connection information properties
connectionInfo = newTable.getConnectionInfo();
// Set new table connection property attributes
propertyBag = new PropertyBag();
// Overwrite any existing properties with updated values
propertyBag.put("Trusted_Connection",
TRUSTED_CONNECTION);
propertyBag.put("Server Type", SERVER_TYPE);
propertyBag.put("Use JDBC", USE_JDBC);
propertyBag.put("Database DLL", DATABASE_DLL);
propertyBag.put("JNDIOptionalName", JNDI_OPTIONAL_NAME);
propertyBag.put("Connection URL", CONNECTION_URL);
propertyBag.put("Database Class Name",
DATABASE_CLASS_NAME);
connectionInfo.setAttributes(propertyBag);
connectionInfo.setUserName(DB_USER_NAME);
connectionInfo.setPassword(DB_PASSWORD);
// Update the table information
clientDoc.getSubreportController()
.getSubreport(subNames.getString(subNum))
.getDatabaseController()
.setTableLocation(origTable, newTable);
}
}
}
}
}
Add after this line of yours
connectionInfo.setPassword(DB_PASSWORD);
newTable.setConnectionInfo(connectionInfo);
//This will add connection parameters to the new table
Instead of
clientDoc.getDatabaseController().setTableLocation(origTable, newTable);
replace this with
clientDoc.getDatabaseController ().setTableLocation (newTable, tables.getTable(i));

Java Storing Multiple Rows From Select Queries

This is actually a re-do of an older question of mine that I have completely redone because my old question seemed to confuse people.
I have written a Java program that Queries a database and is intended to retrieve several rows of data. I have previously written the program in Informix-4GL and I am using a sql cursor to loop through the database and store each row into a "dynamic row of record". I understand there are no row of records in Java so I have ended up with the following code.
public class Main {
// DB CONNECT VARIABLE ===========================
static Connection gv_conn = null;
// PREPARED STATEMENT VARIABLES ==================
static PreparedStatement users_sel = null;
static ResultSet users_curs = null;
static PreparedStatement uinfo_sel = null;
static ResultSet uinfo_curs = null;
// MAIN PROGRAM START ============================
public static void main(String[] args) {
try {
// CONNECT TO DATABASE CODE
} catch(Exception log) {
// YOU FAILED CODE
}
f_prepare(); // PREPARE THE STATEMENTS
ArrayList<Integer> list_id = new ArrayList<Integer>();
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<Integer> list_info = new ArrayList<String>();
ArrayList<String> list_extra = new ArrayList<String>();
try {
users_sel.setInt(1, 1);
users_curs = users_sel.executeQuery();
// RETRIEVE ROWS FROM USERS
while (users_curs.next()) {
int lv_u_id = users_curs.getInt("u_id");
String lv_u_name = users_curs.getString("u_name");
uinfo_sel.setInt(1, lv_u_id);
uinfo_curs = uinfo_sel.executeQuery();
// RETRIEVE DATA FROM UINFO RELATIVE TO USER
String lv_ui_info = uinfo_curs.getString("ui_info");
String lv_ui_extra = uinfo_curs.getString("ui_extra");
// STORE DATA I WANT IN THESE ARRAYS
list_id.add(lv_u_id);
list_name.add(lv_u_name);
list_info.add(lv_ui_info);
list_extra.add(lv_ui_extra);
}
} catch(SQLException log) {
// EVERYTHING BROKE
}
// MAKING SURE IT WORKED
System.out.println(
list_id.get(0) +
list_name.get(0) +
list_info.get(0) +
list_extra.get(0)
);
// TESTING WITH ARBITRARY ROWS
System.out.println(
list_id.get(2) +
list_name.get(5) +
list_info.get(9) +
list_extra.get(14)
);
}
// PREPARE STATEMENTS SEPARATELY =================
public static void f_prepare() {
String lv_sql = null;
try {
lv_sql = "select * from users where u_id >= ?"
users_sel = gv_conn.prepareStatement(lv_sql);
lv_sql = "select * from uinfo where ui_u_id = ?"
uinfo_sel = gv_conn.prepareStatement(lv_sql)
} catch(SQLException log) {
// IT WON'T FAIL COZ I BELIEEEVE
}
}
}
class DBConn {
// connect to SQLite3 code
}
All in all this code works, I can hit the database once, get all the data I need, store it in variables and work with them as I please however this does not feel right and I think it's far from the most suited way to do this in Java considering I can do it with only 15 lines of code in Informix-4GL.
Can anyone give me advice on a better way to achieve a similar result?
In order to use Java effectively you need to use custom objects. What you have here is a lot of static methods inside a class. It seems that you are coming from a procedural background and if you try to use Java as a procedural language, you will not much value from using it. So first off create a type, you can plop it right inside your class or create it as a separate file:
class User
{
final int id;
final String name;
final String info;
final String extra;
User(int id, String name, String info, String extra)
{
this.id = id;
this.name = name;
this.info = info;
this.name = name;
}
void print()
{
System.out.println(id + name + info + extra);
}
}
Then the loop becomes:
List<User> list = new ArrayList<User>();
try {
users_sel.setInt(1, 1);
users_curs = users_sel.executeQuery();
// RETRIEVE ROWS FROM USERS
while (users_curs.next()) {
int lv_u_id = users_curs.getInt("u_id");
String lv_u_name = users_curs.getString("u_name");
uinfo_sel.setInt(1, lv_u_id);
uinfo_curs = uinfo_sel.executeQuery();
// RETRIEVE DATA FROM UINFO RELATIVE TO USER
String lv_ui_info = uinfo_curs.getString("ui_info");
String lv_ui_extra = uinfo_curs.getString("ui_extra");
User user = new User(lv_u_id, lv_u_name, lv_ui_info, lv_ui_extra);
// STORE DATA
list.add(user);
}
} catch(SQLException log) {
// EVERYTHING BROKE
}
// MAKING SURE IT WORKED
list.get(0).print();
This doesn't necessarily address the number of lines. Most people who use Java don't interact with databases with this low-level API but in general, if you are looking to get down to the fewest number of lines (a questionable goal) Java isn't going to be your best choice.
Your code is actually quite close to box stock JDBC.
The distinction is that in Java, rather than having a discrete collection of arrays per field, we'd have a simple Java Bean, and a collection of that.
Some examples:
public class ListItem {
Integer id;
String name;
Integer info;
String extra;
… constructors and setters/getters ellided …
}
List<ListItems> items = new ArrayList<>();
…
while(curs.next()) {
ListItem item = new ListItem();
item.setId(curs.getInt(1));
item.setName(curs.getString(2));
item.setInfo(curs.getInfo(3));
item.setExtra(curs.getString(4));
items.add(item);
}
This is more idiomatic, and of course does not touch on the several frameworks and libraries available to make DB access a bit easier.

Bugged by de'bug

An unexpected token error occurs near the Class Database, yet everything in the syntax looks fine. I guess I made the error in the way I called the value from the class?
import de.bezier.data.sql.*;
PostgreSQL pgsql;
Database
void setup()
{
size( 100, 100 );
String user = "user";
String pass = "pass";
String database = "db";
pgsql = new PostgreSQL( this, "127.0.0.1", database, user, pass );
println ("ok");
}
void draw()
{
val1.update();
}
Token error here
Class Database
{
Float val;
database (Float col) {
val = col;
}
void update( )
{
//sets up database
pgsql = new PostgreSQL( this, "127.0.0.1", database, user, pass );
if ( pgsql.connect() )
{
pgsql.query( "SELECT col FROM table ORDER BY col DESC LIMIT 1; " );
return( pgsql.getFloat("col") );
}
else
{
return float (col = 0);
}
}
}
Some text here....
This line
pgsql = new PostgreSQL( this, "127.0.0.1", database, user, pass )
is invoking a constructor. From the documentation you need to extend processing.core.PApplet. "this" refers to the current instance of "this" class.

Hibernate query restrictions using URL key/value style parameters

I'm using Tapestry5 and Hibernate. I'm trying to build a criteria query that uses dynamic restrictions generated from the URL. My URL context is designed like a key/value pair.
Example
www.mywebsite.com/make/ford/model/focus/year/2009
I decode the parameters as followed
private Map<String, String> queryParameters;
private List<Vehicle> vehicles;
void onActivate(EventContext context) {
//Count is 6 - make/ford/model/focus/year/2009
int count = context.getCount();
if (count > 0) {
int i;
for (i = 0; (i + 1) < count; i += 2) {
String name = context.get(String.class, i);
String value = context.get(String.class, i + 1);
example "make"
System.out.println("name " + name);
example "ford"
System.out.println("value " + value);
this.queryParameters.put(name, value);
}
}
this.vehicles = this.session.createCriteria(Vehicle.class)
...add dynamic restrictions.
}
I was hoping someone could help me to figure out how to dynamically add the list of restrictions to my query. I'm sure this has been done, so if anybody knows of a post, that would be helpful too. Thanks
Exactly as the other answer said, but here more spelt out. I think the crux of your question is really 'show me how to add a restriction'. That is my interpretation anyhow.
You need to decode each restriction into its own field.
You need to know the Java entity property name for each field.
Then build a Map of these 2 things, the key is the known static Java entity property name and the value is the URL decoded data (possibly with type conversion).
private Map<String, Object> queryParameters;
private List<Vehicle> vehicles;
void onActivate(EventContext context) {
//Count is 6 - make/ford/model/focus/year/2009
int count = context.getCount();
queryParameters = new HashMap<String,Object>();
if (count > 0) {
int i;
for (i = 0; (i + 1) < count; i += 2) {
String name = context.get(String.class, i);
String value = context.get(String.class, i + 1);
Object sqlValue = value;
if("foobar".equals(name)) {
// sometime you don't want a String type for SQL compasition
// so convert it
sqlValue = UtilityClass.doTypeConversionForFoobar(value);
} else if("search".equals(name) ||
"model".equals(name) ||
"year".equals(name)) {
// no-op this is valid 'name'
} else if("make".equals(name)) {
// this is a suggestion depends on your project conf
name = "vehicleMake.name";
} else {
continue; // ignore values we did not expect
}
// FIXME: You should validate all 'name' values
// to be valid and/or convert to Java property names here
System.out.println("name " + name);
System.out.println("value " + value);
this.queryParameters.put(name, sqlValue);
}
}
Criteria crit = this.session.createCriteria(Vehicle.class)
for(Map.Entry<String,Object> e : this.queryParameters.entrySet()) {
String n = e.getKey();
Object v = e.getValue();
// Sometimes you don't want a direct compare 'Restructions.eq()'
if("search".equals(n))
crit.add(Restrictions.like(n, "%" + v + "%"));
else // Most of the time you do
crit.add(Restrictions.eq(n, v));
}
this.vehicles = crit.list(); // run query
}
See also https://docs.jboss.org/hibernate/orm/3.5/reference/en/html/querycriteria.html
With the above there should be no risk of SQL injection, since the "name" and "n" part should be 100% validated against a known good list. The "value" and "v" is correctly escaped, just like using SQL position placeholder '?'.
E&OE
I would assume you would just loop over the parameters Map and add a Restriction for each pair.
Be aware that this will open you up to sql injection attacks if you are not careful. the easiest way to protect against this would be to check the keys against the known Vehicle properties before adding to the Criteria.
Another option would be to create an example query by building an object from the name/value pairs:
Vehicle vehicle = new Vehicle();
int count = context.getCount();
int i;
for (i = 0; (i + 1) < count; i += 2) {
String name = context.get(String.class, i);
String value = context.get(String.class, i + 1);
// This will call the setter for the name, passing the value
// So if name is 'make' and value is 'ford', it will call vehicle.setMake('ford')
BeantUtils.setProperty(vehicle, name, value);
}
// This is using a Hibernate example query:
vehicles = session.createCriteria(Vehicle.class).add(Example.create(vehicle)).list();
See BeanUtils.setProperty and Example Queries for more info.
That assumes you are allowing only one value per property and that the query parameters map to the property names correctly. There may also be conversion issues to think about but I think setProperty handles the common ones.
If they are query paramaters you should treat them as query parameters instead of path parameters. Your URL should look something like:
www.mywebsite.com/vehicles?make=ford&model=focus&year=2009
and your code should look something like this:
public class Vehicles {
#ActivationRequestParameter
private String make;
#ActivationRequestParameter
private String model;
#ActivationRequestParameter
private String year;
#Inject
private Session session;
#OnEvent(EventConstants.ACTIVATE)
void activate() {
Criteria criteria = session.createCriteria(Vehicle.class);
if (make != null) criteria.add(Restrictions.eq("make", make));
if (model != null) criteria.add(Restrictions.eq("model", model));
if (year != null) criteria.add(Restrictions.eq("year", year));
vehicles = criteria.list();
}
}
Assuming you are using the Grid component to display the vehicles I'd highly recommend using the HibernateGridDataSource instead of making the query in the "activate" event handler.
public class Vehicles {
#ActivationRequestParameter
private String make;
#ActivationRequestParameter
private String model;
#ActivationRequestParameter
private String year;
#Inject
private Session session;
#OnEvent(EventConstants.ACTIVATE)
void activate() {
}
public GridDataSource getVehicles() {
return new HibernateGridDataSource(session, Vehicles.class) {
#Override
protected void applyAdditionalConstraints(Criteria criteria) {
if (make != null) criteria.add(Restrictions.eq("make", make));
if (model != null) criteria.add(Restrictions.eq("model", model));
if (year != null) criteria.add(Restrictions.eq("year", year));
}
};
}
}

Categories