Gray_code_element

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

Saturday, January 30, 2010

Intelligence from outside intelligencia: Garrett Lisi

Garrett Lisi it a theoretical physicist that is not letting himself be encumbered by the security of an academic lifestyle. I hope he has success with his E8 theory about quantum physics.

Check out his deferential geometry personal wiki notebook. If you scroll down to the section called E8 theory summary, you can click on the formulas and actually edit them right on the screen.

It is always a challenge to show formulas on a web page, and he seems to have figured out how to do it elegantly.

Friday, January 29, 2010

Create a Java Program in Eclipse


I have been doing a bunch of Struts and REST development in Eclipse for which there are good wizards to get started, but it was suprizingly difficult figure out how to build just a simple hello world java project.


With the help of Nathan, I can now do the basic java project:



First, select the new button just below File and open a new Java Project





A New Java Project window will open: enter the name of the project then click Finish






You should now see your project listed in the Package Explorer. Expand the project.







Under the project you will see the project’s package (src) and the library it is referencing. You now want to add a class to the project where you can write your program. So right click the package (src), select new -> class.





The New Java Class window opens. Notice the Source Folder. Type the name of the new class and ensure “public static void main(String[] args)” is selected. Click finish to create the class.





Because we selected the option to create the main, the IDE automatically inserts its declaration into the code. Now we can begin to write our basic program right away.





Replace the comment with this text:


String printStr = "This is your conscience speaking..."; System.out.println(printStr);

In the Package Explorer, right click the class and select Run As to run the program. If a message box appears, select yes to save the project. You will see the text printed to the screen.



Sunday, November 29, 2009

What governs your life?

Over the past few weeks I have been reading Jeremy Bentham to provide some bedtime reading. He explains that utilitarianism (making rational decisions that maximize your own long term pleasure) is the best system for making choices. He often criticizes asceticism (abstinence from various sorts of worldly pleasures) so I guess that he must have had significant exposure to a group of people that were highly ascetic.

In the past few weeks I have also heard about Victor Frankl, a psychiatrist and neurologist that survived a German concentration camp. He would have been exposed to these utilitarian theories before entering the concentration camps. When in the camp, he quickly realized that pursuing a life to maximize personal pleasure was meaningless in a concentration camp. When a life is characterized by suffering, what meaning can there be in attempting to maximize pleasure or minimize pain? Here are some quotes from his book called "Man's Search for Meaning"
  • We who lived in concentration camps can remember the men who walked through the huts comforting others, giving away their last piece of bread. They may have been few in number, but they offer sufficient proof that everything can be taken from a man but one thing: the last of the human freedoms—to choose one's attitude in any given set of circumstances, to choose one's own way.
  • Nietzsche's words, 'He who has a why to live can bear with almost any how.'
Frankl was trying to make sense out of his existence in a concentration camp. Pursuing personal pleasure did not make sense for him, but giving of himself to care for others did make sense - and that he could still have control over, even while suffering.

I also think about Immanuel Kant trying to make sense out of ethics. He tried to develop a totally rational system for an absolutely universal ethical framework - one that eliminates all subjectivity. As much as Kant's system seems so different from Bentham's, it is also similar in that it is looking for a universal principal from which all ethical behavior can be decided.

All three of these writers are trying to find the root cause of morals, ethics, what is the best thing to do, and why to do it.

They are all looking for governing principals for their lives. It is funny that even a utilitarian who makes decisions based on the principal of maximizing pleasure is actually "submitting" themselves to the governing principals of utilitarianism. They are not just doing whatever whim floats across their mind at any moment. A true blue utilitarian will make decisions based on maximizing their long term best interest (refered to as enlightened self interest). They are submitting themselves to a governing principal.

It is interesting that we all have this desire to be part of something that make more sense then jumping around from this to that. We long for governing principals.

Why?


Thursday, November 19, 2009

Jeremy Bentham: What is your ethics good for?

Jeremy Bentham (1748-1922) wrote on ethics. He proposed the utilitarian framework for developing ethics. In his Introduction to the Principals of Morals and Legislation, he begins by developing a justification for a utilitarian framework. Basically, the justification goes like this: It only makes sense to build ethics based on what will benefit mankind.

He then goes on to assert that utilitarianism is the best ethical framework because it is useful. He goes on to challenge the validity of other ethical principals by asking "what is it that the other principals can be good for?".

What other principals was he challenging? Well, some of the ethical ideas up to that time are:

Virtues ethics promoted by Aristotle and Plato propose you are supposed to nurture the virtues or moral character. Aristotle argues that you should be virtuous because when you really think about it, it is better in the long run. If you are not pursuing virtue, then you are allowing vice to control you, and vices (lying, cheating, drunkenness) will end up destroying you. Interestingly enough, the defense that Aristotle had for virtue ethics is that it is "useful" in the long run.

Divine Command ethics promote obeying the laws that God has given us. The immediately apparent reason to obey these laws is that they are supposed to improve your standing with God (evangelicals would say that it is not obeying the laws that improve your standing with God, but rather it is believing in Jesus, but it is all part of obeying the what God has commanded). However, there is a more subtle underlying reason for obeying these laws. If God created the universe, then He should know best what kind of behaviors result in the most long term benefit for us human (ie: what is the most useful).

It is interesting to think more about Jeremy Bentham challenge to Virtue and Divine Command ethics. His challenge is that they are not useful - or that usefulness is not their primary principal. I have countered that argument by showing that Virtue and Divine Command ethics are useful.

However, something subtle is happening here. I am playing by Jeremy Bentham game. That game is that we will evaluate anything based on its usefulness. Sure I can show that Virtues or Divine Command is useful, but is that the point?

I think that 2000 years ago, when Divine Command ethics were in full force people did not pursue it because of its "usefulness". There was also something about a mystery and fear of God. I also think that with Virtues ethics, they were not pursued because of their usefulness, but there was a value in society of being virtuous.

That fact that Jeremy Bentham can make use feel so convinced about the superiority of Utilitarianism over other ethical frameworks is an indication of how we value "usefulness" above everything else. I am sure as you are reading this you are asking: What is the point? Either it is useful or it is not. But that is exactly the point! Where has gone things like appreciating beauty for the sake of beauty, or appreciating spirituality just for the sake of a connection with the divine, or giving of yourself to someone else just for the sake letting go of your self and helping someone else out. All of these get lost when we strictly look at things based on the usefulness to ourselves.

I am glad that Jeremy Bentham wrote the challenge that he did because it is a wake-up call to myself. Am I going to make decisions based solely on the usefulness to myself, or am I going to dig deeper?

Monday, October 26, 2009

Good Solidworks resources

Lennys SolidWorks

XML Extractor


Sub PullFromInternet()

'The web address at which xml is stored
URL = "http://jjh.virtual.vps-host.net:8080/restdemo/services/customers/0"

Dim HttpReq As Object

'Declare the request for information over the internet
Set HttpReq = New WinHttpRequest

'Specify the type of HTTP request
HttpReq.Open "GET", URL, False
'or use GET instead of POST

'Specify the type of content that can be recieved
HttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"

'Send the actual request
HttpReq.Send
'HttpReq.send postmydata
'Note - if using GET set postmydata to ""

Dim response As String
Dim tag As String
Dim data As String
tag = "address"
response = HttpReq.ResponseText

MsgBox (extractor(tag, response))

End Sub

Function extractor(tag As String, response As String) As String
Dim tagLength As Integer

Dim mypos As Integer
Dim myposEnd As Integer
mypos = InStr(1, response, "<" & tag)
myposEnd = InStr(1, response, "<" &"/" & tag)
tagLength = Len(tag) + 2
Dim address As String
extractor = Mid(response, mypos + tagLength, (myposEnd - mypos - tagLength))

End Function

Just in case you thought that seeing is believing

y bar

y + hold Alt, type 0773