Tuesday, February 16, 2010

Simple Reflection Example

I am working on extracting various pieces of information from different classes of objects. I thought that rather than manually going through and using getters for the fields of each object, I would try using reflection. The code below is a simple use of reflection. I create a Class object of the type of class for the object, then I get the method of that class. Finally, the method of the object is invoked to get the required information out.

package utils;

import java.lang.reflect.Method;

public class ClassSpy
{
public static void main(String[] args) throws Exception
{
//Specify the class that we will do a reflection on
String className = "utils.SampleClass";
//Create a Class object associated with className
Class toRun = Class.forName(className);
//create an instance of the method which we
will later invoke
Method method = findMethod(toRun, "getId");
//create an instance of the class
SampleClass user = new SampleClass();
user.setId(5);
//invoke the method
int id = (Integer)method.invoke(user);
System.out.println("id "+id);
}
private static Method findMethod(Class clazz,
String functionName) throws Exception
{
Method[] methods = clazz.getMethods();
for (int i=0; i<methods.length; i++)
{
System.out.println(methods[i].getName());
if (methods[i].getName().equals(functionName))
return methods[i];
}
return null;
}
}


The code for sample class is as follows:

Sunday, February 14, 2010

Reading a Class using BLOB from a MySQL Database

MySQL does not directly have the capacity to handle java classes. However, an instance of a class can be converted to a BLOB which can then be stored. The following is a sample program doing that:


public class SampleClass {

static final String DataBase_Url =
"jdbc:mysql://localhost:3306/myDatabase";
static final String Driver = "com.mysql.jdbc.Driver";

//note the Driver will always be the same when
connecting to MySQL but the URL is dependent on
your MySQl database: localhost is the Server Host,
3306 is the port and samptable is the name of the schema

public static void main(String[] args) {
String printStr = "This is your concience speaking.";
System.out.println(printStr);

Connection con = null;
Statement stat = null;
ResultSet rSet = null;
try
{
Class.forName(Driver);
con = DriverManager.getConnection(DataBase_Url,
"username", "secretPassword");
stat = con.createStatement();

rSet = stat.executeQuery("SELECT username from user");
System.out.println("\nUsernames");

while (rSet.next()) {
String ferrariprice = rSet.getString("username");
System.out.println(" " + ferrariprice );
}

}

catch (Exception Exc)
{
Exc.printStackTrace();
System.err.println(Exc.getMessage());
}

finally
{
try
{
rSet.close();
stat.close();
con.close();
}
catch (SQLException sqlExc)
{
sqlExc.printStackTrace();
}
}//end finally

//Pull Blob
stat = null;
rSet = null;
con = null;

//Connection conn = DBUtil.getConnection(connectionName);

try {

Class.forName(Driver);
con =
DriverManager.getConnection(DataBase_Url, "username", "secretPassword");
stat = con.createStatement();

rSet = stat.executeQuery("SELECT * FROM savedcasing");
System.out.println("got rSet");

while (rSet.next()) {
try {
com.faneng.workflow.model.SavedCasingVO
vo = new com.faneng.workflow.model.SavedCasingVO();
vo.setId(rSet.getInt("id"));
vo.setSavedCurveId(rSet.getInt("savedCurveId"));
Blob ib = rSet.getBlob("casingInputVO");
ByteArrayInputStream is = null;
ObjectInputStream ins = null;

if (ib != null) {
is = new ByteArrayInputStream(ib.getBytes(1, (int)
ib.length()));
ins = new ObjectInputStream(is);
vo.setCasingInputVO((CasingInputVO)
ins.readObject());
vo.getCasingInputVO().getDiameter());
}

} catch (Exception e) {
throw new SQLException(e.getMessage());
}
}
}
catch (Exception Exc)
{
Exc.printStackTrace();
System.err.println(Exc.getMessage());
}

finally
{
try
{
rSet.close();
stat.close();
con.close();
}
catch (SQLException sqlExc)
{
sqlExc.printStackTrace();
}
}//end finally

}

}

Monday, February 8, 2010

A good resource for REST web services

Jose Sandoval has written an excellent book on developing REST web servers. The whole concept of web servers is quite an abstract area. However, Jose's book clearly explains the technology so that a person with a moderate level of experience with Java and building Java based web applications should be able to make the step into building powerful REST applications.

Jose's many years of experience in a wide range of Java technologies enable him to explain clearly the required concepts to understand REST while not being excessively wordy on peripheral technologies.

Creating a simple Servlet

The following link provides a good basic tutorial for making a servlet: A Hello World Servlet

When making the servlet in MyEclipse, start a new web project (I called mine ServletExample), then create the package: test, add the HelloServlet class to this package, and change the web.xml as required. Then it should work just fine.

For reference, the HelloServlet class is as follows:

package test;

import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

public class HelloServlet extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();

out.println("Hello, world!");
out.close();
}
}



The XML file is as follows:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>test.HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

To run the servlet in MyEclipse, right click on the project and select Run-As MyEclipse Server Application.

You can then access the servlet by entering the following in the command line:
http://localhost:8080/ServletExample/hello

Solidworks macros eith ChatGPT

 Record a simple using thr Solidworks macro recorder, upload it to ChatGPT, and explain to ChatGPT how you want it changed:  https://youtu.b...