eventhough i change the environmental variables and classpath, while running sqlite jdbc program i get the error stating no class definition doun - sqlitejdbc

im running a jdbc program on Sqlite. though i change the environmental variables or define the classpath of the jar file sqlite-jdbc-3.7.2.jar, i get an error stating ClassNotFoundException: org.sqlite.JDBC... how to rectify it?
my code is`
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args)throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(1, 'leo')");
statement.executeUpdate("insert into person values(2, 'yui')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}`
my jar file is sqlite-jdbc-3.7.2.jar
my class path is D:\jdk1.6.0_45\sqlite-jdbc-3.7.2.jar
my environmental variable is also the same
what should i do?
help pls

i found the solution to my problem...
the class path should be like
`javac Sample.java
java -classpath "D:\jdk1.6.0_45\sqlite-jdbc-3.7.2.jar";. Sample`
the problem is solved:)

Related

cursor program generating sqlexception ordinal binding and named binding cannot be combined

I have created a program using CallableStatement and Cursors to fetch the records from a table named Student with names starting from 'A' with pl/sql procedures.The program is giving an SQLException: java.sql.SQLException: operation not allowed: Ordinal binding and Named binding cannot be combined!
please help me out to resolve this..
the procedure is:
create or replace procedure get_StudDetails(mycur out sys_refcursor,cond in varchar)
as
begin
open mycur for
select * from Student where stname like cond;
end;
/
the java program is:
import java.sql.*;
import oracle.jdbc.driver.*;
class CursorTest
{
public static void main(String s[])
{
try
{
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl","rt","pwdd");
CallableStatement cs=con.prepareCall("{call get_StudDetails(?,?)}");
cs.getString(2+"A%");
cs.registerOutParameter(1,OracleTypes.CURSOR);
cs.execute();
System.out.println("procedure invoked");
ResultSet rs=(ResultSet)cs.getObject(1);
while(rs.next())
{
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Don't use getString but setString instead:
CallableStatement cs=con.prepareCall("{call get_StudDetails(?,?)}");
cs.registerOutParameter(1,OracleTypes.CURSOR);
cs.setString(2, "A%");
cs.execute();

Verifying the attribute in DynamoDB without using scan?

How to verify an attribute whether it present in table or not without using scan in dynamodb?
In my usecase, From client side, The customer request with their Customer_id for knowing the values of the product. In server side, have to check whether the entered customer_id already present in DynamoDB table or not. If not, have to make a new entry.
How can I implement this case without using SCAN operation to the table?
It sounds to me that you want to do a conditional PutItem on this table: put the item into the table if there is not another item with the same customer_id. This is easy enough to do because the customer_id is the hash key of the table. From the PutItem documentation:
Note
To prevent a new item from replacing an existing item, use a conditional put operation with ComparisonOperator set to NULL for the
primary key attribute, or attributes.
Here is a quick example I coded up using the Dynamo DB document API in the Java SDK and running against DynamoDB Local:
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Expected;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.util.Tables;
public class StackOverflow {
private static final String EXAMPLE_TABLE_NAME = "example_table";
public static void main(String[] args) {
AmazonDynamoDB client = new AmazonDynamoDBClient(new BasicAWSCredentials("accessKey", "secretKey"));
client.setEndpoint("http://localhost:4000");
DynamoDB dynamoDB = new DynamoDB(client);
if (Tables.doesTableExist(client, "example_table")) client.deleteTable(EXAMPLE_TABLE_NAME);
// Create table with hash key 'customer_id'
CreateTableRequest createTableRequest = new CreateTableRequest();
createTableRequest.withTableName(EXAMPLE_TABLE_NAME);
createTableRequest.withKeySchema(new KeySchemaElement("customer_id", KeyType.HASH));
createTableRequest.withAttributeDefinitions(new AttributeDefinition("customer_id", ScalarAttributeType.S));
createTableRequest.withProvisionedThroughput(new ProvisionedThroughput(15l, 15l));
dynamoDB.createTable(createTableRequest);
Tables.waitForTableToBecomeActive(client, EXAMPLE_TABLE_NAME);
Table exampleTable = dynamoDB.getTable(EXAMPLE_TABLE_NAME);
exampleTable.putItem(new Item()
.withPrimaryKey("customer_id", "ABCD")
.withString("customer_name", "Jim")
.withString("customer_email", "jim#gmail.com"));
System.out.println("After Jim:");
exampleTable.scan()
.forEach(System.out::println);
System.out.println();
try {
exampleTable.putItem(new Item()
.withPrimaryKey("customer_id", "EFGH")
.withString("customer_name", "Garret")
.withString("customer_email", "garret#gmail.com"), new Expected("customer_id").notExist());
} catch (ConditionalCheckFailedException e) {
System.out.println("Conditional check failed!");
}
System.out.println("After Garret:");
exampleTable.scan()
.forEach(System.out::println);
System.out.println();
try {
exampleTable.putItem(new Item()
.withPrimaryKey("customer_id", "ABCD")
.withString("customer_name", "Bob")
.withString("customer_email", "bob#gmail.com"), new Expected("customer_id").notExist());
} catch (ConditionalCheckFailedException e) {
System.out.println("Conditional check failed!");
}
System.out.println("After Bob:");
exampleTable.scan()
.forEach(System.out::println);
}
}
Output:
After Jim:
{ Item: {customer_email=jim#gmail.com, customer_name=Jim, customer_id=ABCD} }
After Garret:
{ Item: {customer_email=garret#gmail.com, customer_name=Garret, customer_id=EFGH} }
{ Item: {customer_email=jim#gmail.com, customer_name=Jim, customer_id=ABCD} }
Conditional check failed!
After Bob:
{ Item: {customer_email=garret#gmail.com, customer_name=Garret, customer_id=EFGH} }
{ Item: {customer_email=jim#gmail.com, customer_name=Jim, customer_id=ABCD} }

Getting started with XMLPullParser

I am trying to use XMLPullParser but I cannot find any useful tutorials. Based off of the instructions on http://xmlpull.org/ I need to download an implementation of XMLPullParser as a jar file and then add it to my class path. However I cannot find any link to any jar file that works. Does anyone know where I might be able to find a jar file I can download.
Thanks
Ok, here it is for you.
From the official doc :
XmlPull API Implementations:
XNI 2 XmlPull
XPP3/MXP1
KXML2
Here i use KXML2.
Steps :
Download KXML2 jar file from here.
Create a new java project
Create a new class
Right click the java project -> Properties -> Java Build path -> Libraries -> Add external jar's -> Add downloaded kxml2 jar file.
Java code
import java.io.IOException;
import java.io.StringReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class XmlPullparserBasic {
public static void main (String args[]) throws XmlPullParserException, IOException
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}
}
Output :
Hope it helps!

Casting java.sql.Connection to oracle.jdbc.OracleConnection results in compilation error

I would like to cast java.sql.Connection to oracle.jdbc.OracleConnection in order to bind data on ARRAY to my query.
When I try the following on scala 2.10, bonecp 0.8.0 and slick 2.0.0:
import com.jolbox.bonecp.ConnectionHandle
import oracle.jdbc.OracleConnection
def failsWithCompilationError() = {
Database.forDataSource(ds).withDynTransaction {
val connection = dynamicSession.conn.asInstanceOf[ConnectionHandle].getInternalConnection
println(connection.unwrap(classOf[OracleConnection]))
// When uncommenting following two lines a compilation error "error while loading AQMessage, class file '.../ojdbc6.jar(oracle/jdbc/aq/AQMessage.class)' is broken" will occur
// val oracleConnection: OracleConnection = connection.unwrap(classOf[OracleConnection])
// println(oracleConnection)
}
}
and uncomment the two lines with assignment to a val of type OracleConnection and printlna compilation failure
[error] error while loading AQMessage, class file '.../ojdbc6.jar(oracle/jdbc/aq/AQMessage.class)' is broken will occur.
I already verified that the ojdbc6.jar should not be corrupted by downloading newer version from Oracle.
It seems that the problem was with the Scala compiler.
As soon as I embedded the functionality that depended on oracle.jdbc.OracleConnection into a plain old Java class, built that into a separate .jar and linked with my Scala code things started to roll.
Here's how I got this to work:
OracleArray.java
package my.application.oracle.collections;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OraclePreparedStatement;
import oracle.sql.ARRAY;
import scala.Long;
import scala.Tuple2;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/*
Wraps usage of Oracle ARRAYs since casting java.sql.Connection to oracle.jdbc.Connection does not compile on Scala.
*/
public class OracleArray {
public static List<Tuple2<Long, Long>> fetchAssetsByIds(List ids, Connection connection) throws SQLException {
OracleConnection oracleConnection = (OracleConnection) connection;
ARRAY oracleArray = oracleConnection.createARRAY("MY_ARRAY_SQL_TYPE", ids.toArray());
String sql = "SELECT a.id, a.value" +
"FROM ASSET a " +
"WHERE a.id IN (SELECT COLUMN_VALUE FROM TABLE(?))";
PreparedStatement statement = oracleConnection.prepareStatement(sql);
try {
OraclePreparedStatement oraclePreparedStatement = (OraclePreparedStatement) statement;
oraclePreparedStatement.setArray(1, oracleArray);
ResultSet resultSet = oraclePreparedStatement.executeQuery();
try {
ArrayList<Tuple2<Long, Long>> resultTuples = new ArrayList<>();
while (resultSet.next()) {
long id = resultSet.getLong(1);
long value = resultSet.getLong(2);
resultTuples.add(new Tuple2(id, value));
}
return resultTuples;
} finally {
resultSet.close();
}
} finally {
statement.close();
}
}
}
DataUser.scala
package my.application
import my.application.oracle.collections.OracleArray
import scala.slick.driver.JdbcDriver.backend.Database
import Database.dynamicSession
import com.jolbox.bonecp.ConnectionHandle
import java.sql.Connection
import collection.JavaConversions._
/*
Uses BoneCP and Slick to connect to database and relays java.sql.Connection to
OracleArray in order to run operations that use Oracle ARRAYs
*/
object DataUser {
def doSomethingWithAssets(ids: Seq[Long]): Unit = {
Database.forDataSource(ds).withDynTransaction {
val connection: Connection = dynamicSession.conn.asInstanceOf[ConnectionHandle].getInternalConnection
val assets: Seq[(Long, Long)] = OracleArray.fetchAssetsByIds(ids, connection)
println(assets)
}
}
}
Not sure if my situation is related, but using the Play framework, this works for me only when logSql=false:
db.withConnection { implicit c =>
val oracleConnection = c.unwrap(classOf[OracleConnection])
}
When I set logSql=true, I get:
com.sun.proxy.$Proxy17 cannot be cast to oracle.jdbc.OracleConnection
java.lang.ClassCastException: com.sun.proxy.$Proxy17 cannot be cast to
oracle.jdbc.OracleConnection
So something about the logSql configuration can actually cause unwrap to fail. No idea why.
I think this may be related to Hikari Connection Pool, but maybe your connection pool configuration is causing a similar problem.

AspectJ - Is is possible to extend an enum's value?

Say I have an enum
public enum E {A,B,C}
Is it possible to add another value, say D, by AspectJ?
After googling around, it seems that there used to be a way to hack the private static field $VALUES, then call the constructor(String, int) by reflection, but seems not working with 1.7 anymore.
Here are several links:
http://www.javaspecialists.eu/archive/Issue161.html (provided by #WimDeblauwe )
and this: http://www.jroller.com/VelkaVrana/entry/modify_enum_with_reflection
Actually, I recommend you to refactor the source code, maybe adding a collection of valid region IDs to each enumeration value. This should be straightforward enough for subsequent merging if you use Git and not some old-school SCM tool like SVN.
Maybe it would even make sense to use a dynamic data structure altogether instead of an enum if it is clear that in the future the list of commands is dynamic. But that should go into the upstream code base. I am sure the devs will accept a good patch or pull request if prepared cleanly.
Remember: Trying to avoid refactoring is usually a bad smell, a symptom of an illness, not a solution. I prefer solutions to symptomatic workarounds. Clean code rules and software craftsmanship attitude demand that.
Having said the above, now here is what you can do. It should work under JDK 7/8 and I found it on Jérôme Kehrli's blog (please be sure to add the bugfix mentioned in one of the comments below the article).
Enum extender utility:
package de.scrum_master.util;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;
public class DynamicEnumExtender {
private static ReflectionFactory reflectionFactory =
ReflectionFactory.getReflectionFactory();
private static void setFailsafeFieldValue(Field field, Object target, Object value)
throws NoSuchFieldException, IllegalAccessException
{
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
private static void blankField(Class<?> enumClass, String fieldName)
throws NoSuchFieldException, IllegalAccessException
{
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass)
throws NoSuchFieldException, IllegalAccessException
{
blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6
blankField(enumClass, "enumConstants"); // IBM JDK
}
private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)
throws NoSuchMethodException
{
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(enumClass .getDeclaredConstructor(parameterTypes));
}
private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes, Object[] additionalValues)
throws Exception
{
Object[] parms = new Object[additionalValues.length + 2];
parms[0] = value;
parms[1] = Integer.valueOf(ordinal);
System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));
}
/**
* Add an enum instance to the enum class given as argument
*
* #param <T> the type of the enum (implicit)
* #param enumType the class of the enum to be modified
* #param enumName the name of the new enum instance to be added to the class
*/
#SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType))
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
// 1. Lookup "$VALUES" holder in enum class and get previous enum
// instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(
enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(), new Class<?>[] {}, // could be used to pass values to the enum constuctor if needed
new Object[] {} // could be used to pass values to the enum constuctor if needed
);
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
}
Sample application & enum:
package de.scrum_master.app;
/** In honour of "The Secret of Monkey Island"... ;-) */
public enum Command {
OPEN, CLOSE, PUSH, PULL, WALK_TO, PICK_UP, TALK_TO, GIVE, USE, LOOK_AT, TURN_ON, TURN_OFF
}
package de.scrum_master.app;
public class Server {
public void executeCommand(Command command) {
System.out.println("Executing command " + command);
}
}
package de.scrum_master.app;
public class Client {
private Server server;
public Client(Server server) {
this.server = server;
}
public void issueCommand(String command) {
server.executeCommand(
Command.valueOf(
command.toUpperCase().replace(' ', '_')
)
);
}
public static void main(String[] args) {
Client client = new Client(new Server());
client.issueCommand("use");
client.issueCommand("walk to");
client.issueCommand("undress");
client.issueCommand("sleep");
}
}
Console output with original enum:
Executing command USE
Executing command WALK_TO
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant de.scrum_master.app.Command.UNDRESS
at java.lang.Enum.valueOf(Enum.java:236)
at de.scrum_master.app.Command.valueOf(Command.java:1)
at de.scrum_master.app.Client.issueCommand(Client.java:12)
at de.scrum_master.app.Client.main(Client.java:22)
Now you can either add an aspect with an advice executed after the enum class was loaded or just call this manually in your application before extended enum values are to be used for the first time. Here I am showing how it can be done in an aspect.
Enum extender aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.Command;
import de.scrum_master.util.DynamicEnumExtender;
public aspect CommandExtender {
after() : staticinitialization(Command) {
System.out.println(thisJoinPoint);
DynamicEnumExtender.addEnum(Command.class, "UNDRESS");
DynamicEnumExtender.addEnum(Command.class, "SLEEP");
DynamicEnumExtender.addEnum(Command.class, "WAKE_UP");
DynamicEnumExtender.addEnum(Command.class, "DRESS");
}
}
Console output with extended enum:
staticinitialization(de.scrum_master.app.Command.<clinit>)
Executing command USE
Executing command WALK_TO
Executing command UNDRESS
Executing command SLEEP
Et voilà! ;-)

Resources