Sunday, June 10, 2012

Pull Most Recent Entry in a Table Using Hibernate

I have a table called 'codesnipets' which has fields that make up a sort of pastebin thing. After posting a new code snipet, I want to show that snipet post immediately. So I simply want to pull the latest record from the table. I can to this two ways: selecting the highest ID in the table (where ID is primary key, integer, auto-inc...) or I could select by the most recent date. My ID name is "idcodesnipets", which is, again, the name of the variable in my bean, NOT the actual name of my table field.

So by ID, one way is with criteria:


 <%
        // Begin transaction as normal
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        s.beginTransaction();

        CodeSnipet snipet = new CodeSnipet(); // new object holder

        Criteria c = s.createCriteria(CodeSnipet.class);
        c.addOrder(Order.asc("idcodesnipets")).setMaxResults(1); //only want one.
        List l = c.list();
        snipet = (CodeSnipet)l.get(0); // just want the first one in the list
      
        %>
        <p>Here is a snipet:</p>
        <p>Title:
            <% out.println(snipet.getCodetitle()); %>
            </p>
        <p>File Name:
            <% out.println(snipet.getCodefilename()); %>
            </p>
        <p>Code:
            <% out.println(snipet.getCodetext()); %>
            </p>


Imports:

<%@page import="java.util.List"%>
<%@page import="org.hibernate.criterion.Order"%>
<%@page import="org.hibernate.Criteria"%>



By the way, I had the wrong dialect set from some stupid copy pasta, so if you get a 'SQL Grammar Error', check that if you are using MySQL you have this:

hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect


Set as your dialect in your hibernate config file. So it will look like:


<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

Saturday, June 9, 2012

Screen Brightness control fix after linux update disaster.

I am running Linux Mint 12 on my thinkpad T410, and apparently when you update something happens with the Nvidia drivers to disable brightness control for the screen.

Here is fix:

Inside of /etc/X11/xorg.conf add this line-

    
Option "RegistryDwords" "EnableBrightnessControl=1"
 

Hello World with Struts 2 in Netbeans 7.1.2 and Tomcat 6

So I think I went over how to get tomcat up and running with Netbeans, so lets get started with Struts 2. First thing, go ahead and download the struts 2 framework here and go ahead and unzip those Jar files from the Struts 2 package somewhere they will be safe.

Then you will want to create a new project (a web project). After you get your project created go to properties->Add Library->Create Now add all of these Jar files into a new Library called Struts 2 (or whatever, who cares).

I started using Struts 2 in Action to get this running so I'm using their Hello World app. Inside of the source packages you need to make a file called struts.xml. This will be the main config for your struts project.

code:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <constant name="struts.devMode" value="true" />

  <package name="default" namespace="/" extends="struts-default"> 
   <action name="Menu">
    <result>/menu/Menu.jsp</result>
   </action>
  </package>  
</struts>

Now that that is taken care of you need to add a Filter and Filter-Mapping tag set to your web.xml file.
Code: (goes inside of the <web-app> tags!!!)
<filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
    
<filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>



It is fine to leave your welcome file as index.jsp. Now we are going to link to the action that we mapped earlier so inside of index.jsp add this:
        <P>
            <a href="Menu.action">menu</a>
        </p>
What this will do is simply trigger the Menu action that we defined in struts.xml. Remember that we defined the filter-mapping url pattern to pick up EVERYTHING ('/*'), so anything at all ending with .action will be intercepted.

So great, but we still need to make a Menu.jsp file for the action to point to. So the way I did this is inside of my 'Web Pages' area I made a folder called 'menu' and inside of it I created the .jsp file Menu.jsp. In Netbeans remember in terms of directories what you see is NOT what you get! The actual directory structure is like this:



So anyway, here is my Menu.jsp file:



<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Struts 2 in Action: Menu</title>
</head>

<body>

  <hr> 
  <ul>
     <li><a href="<s:url action='hello/Name'/>">HelloWorld</a></li>

 </ul>

  <hr>  

</html>



I will add the rest later, with the HelloWorld.java class, and the Name action. But for now I'm just going put what I have up on my server in a zip file so that you can download it and get up and running super fast with Struts 2. One note: the file is sort-of because I included the Hibernate libraries in there when I built my project, but that is OK, because I will use them soon and post those builds also!

Here is something you can deploy to Tomcat.

Here is the entire NetBeans project.

Edit:
So I opened the project on my laptop and there were three references that were broken, but these are easy fixes:
1)- Select a new server. I actually used Glassfish 3 on my laptop and it was fine.
2)- Point to struts 2. Go download struts 2:  http://struts.apache.org/download.cgi#struts234
Then add a custom libraray, point to the place where you extracted Struts 2 and you are good.
3)- Point to the MySQL Connector- download from here: http://dev.mysql.com/usingmysql/java/
Then fix the ref by pointing to the actual JAR file.


Wednesday, June 6, 2012

Returning all the rows of on table in Hibernate

So now I want to return all the rows of a mapped table in Hibernate. Here is the trick: you make a hibernated query using the name of the class mapped to a table, not the actual name of the table in MySQL.


               Session sesh3 = NewHibernateUtil.getSessionFactory().getCurrentSession();
               sesh3.beginTransaction();
               // Interesting thing here: this my select from the mapped class NOT the actual DB table name.
               Query qry = sesh3.createQuery("FROM MyMessages");
               List l = qry.list();
               Iterator i1 = l.iterator();
               MyMessages msgs = null;
              
               out.println("Here are all of the rows from the DB:<br />");
               while(i1.hasNext()) {
                   // again, look @ that, we typecast the result of the iterator.
                   msgs = (MyMessages)i1.next();
                   out.println("Last Message Time: " + msgs.getStamp());
                   long id_msg = msgs.getMessageID();
                   //String.valueOf(id_msg);
                   out.println("Last Message ID: " + String.valueOf(id_msg));
                   out.print("<br />");
               }
 
I know I was wondering, when looking over the examples, so here are the import statements:
    
 
<%@page import="java.util.Iterator"%>
<%@page import="org.hibernate.Query"%>
<%@page import="java.util.List"%>
<%@page import="hibernatemapping.NewHibernateUtil"%>
<%@page import="org.hibernate.hql.ast.util.SessionFactoryHelper"%>
<%@page import="org.hibernate.Session"%>
<%@page import="hibernatemapping.HiberUtil"%>
<%@page import="org.hibernate.Transaction"%>
<%@page import="java.util.Date"%>
<%@page import="dbclasses.MyMessages"%>

All said and done you get something spit out that looks like this:

Date:Wed Jun 06 13:13:46 EDT 2012 Here is a row from the db Message: Derp derpTime:2012-06-06 04:07:50.0 
Here are all of the rows from the DB:
Last Message Time: 2012-06-06 04:07:50.0 Last Message ID: 1 
Last Message Time: 2012-06-06 04:34:29.0 Last Message ID: 2 
Last Message Time: 2012-06-06 04:35:15.0 Last Message ID: 3 
Last Message Time: 2012-06-06 04:36:51.0 Last Message ID: 4 
Last Message Time: 2012-06-06 04:37:09.0 Last Message ID: 5 

Wait I don't know JSP yet. And getting Hibernate working.

So here is a thought: I have actually never used JSP. At all. Turns out it is just like PHP:
you open up tags like so: <% Java code goes here %>

Import statements are special:
<%@page import="java.util.Date"%>

And they go up at the top. And you can just use out.println() to render stuff to the page.

Anyway, lets make a Hibernate session factory util: I'm just using the Netbeans defualt Hibernate util by going to new->other->hibernate->HibernateUtil.java which gives me this:


package hibernatemapping;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class NewHibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

I quickly went into my index.jsp page and tried it out:


            <%
            String derp = "Derp derp";
            MyMessages m = new MyMessages();
            // set message to a string
            m.setMessage(derp);
            // set ip to the request object for it
            m.setIp(request.getRemoteAddr());
            
            //pass some new date:
            Date d = new Date();
            m.setStamp(d);
            
            String mymsg = "message:" + m.getMessage() + " IP:" + m.getIp() + " Date:" + m.getStamp().toString();
            out.println(mymsg);
            
            /*
            *  NOW LETS GIVE HIBERNATE A TRY:
            */
            // this gives null pointer exception
               Session sesh = NewHibernateUtil.getSessionFactory().getCurrentSession();
               sesh.beginTransaction();
               sesh.save(m);
               sesh.getTransaction().commit();
            %>

After I went into MySQL workbench I checked my previously virgin 'Messages' table and saw that it had one entry in it after reloading index.jsp. So far so good. Now, one more thing before bed: I want to pull out a message:

               Session sesh2 = NewHibernateUtil.getSessionFactory().getCurrentSession();
               sesh2.beginTransaction();
               long id = 1; // yeah it has to be a long apparently
               // You typecase the result as an object you want it to be basically:
               msg = (MyMessages) sesh2.get(MyMessages.class, id);
               
               out.println("Here is a row from the db");
               out.println("Message: " + msg.getMessage() + "Time:" + msg.getStamp().toString());
              

So tomorrow I suppose I will try to pull out rows and iterate over them.

Tuesday, June 5, 2012

Trying again on windows: Hibernate, TomCat, Struts- With NetBeans

Okay, so after last night's show stopper bugs on my nix system, lets give it a shot on Windows. Again I have NetBeans 7.1.2 and for some reason Tomcat is not coming with it... Even though it said it did? Anyway, got the 32 bit Windows version from the website- 6.0.35 so lets give this a shot.

Went to add server-> tomcat -> navigated to where I unpacked Tomcat 6. Let Netbeans create a default user/pass for the manager script (root/test). Okay great. So I'm NOT going to include the super outdated version of Hibernate that comes with Netbeans (3.2.5)  as they are on 4.1 now. And I'm not including Struts 1.3.10 either (no thanks it isn't 1999).

So right away I'm running the build to see if I can get the TomCat "Hello World" up. Great @ http://localhost:8080/srvrTest/ I can see a nice big "Hello World". Sweet. So lets go ahead and get maybe Hibernate 3.5.X going because the documentation looks to be pretty decent. Yeah I'm talking about this tutorial right here. Wait nope, everyone is using '3.6.1 FINAL' so I better use that. I doubt they are too different. They also have almost the exact same tutorial for 3.6... cool.

Alright so the tutorial is telling to use Maven. Idk what this is so that is pretty fucking awesome. Well okay I'll just go to apache.maven.org and see if that helps. Maven in 5 minutes... So I'm getting Maven 3.0.4- hope that is good. Uh actually that looks like a pain in the ass setting that up. I'll hold off. I think Netbeans already uses ant anyway, but I really have no Idea how this works...

So I'm starting up my MySQL server and getting that running because I need something for Hibernate to mess with. Alright so I forgot I disabled my MySQL service because I thought it was making Battlefield run slower. So went to 'services' to fix that. Oh god I forgot I don't have MySQL workbench installed on this computer. There goes another 5 minutes.

So after some delay here is my DB:

usr: root

pass: test

DB name: messaging

table: messages
    messageID  (integer(10), PK, AI)
    message  (varchar(255))
    ip (varchar(20))
    stamp (DATETIME) 
  
So that is done now. So the hibernate tutorial mentions nothing about actually importing the Hibernate Jars into the project. I guess they just want to leave that to the imagination. But skipping the maven section, I'm supposed to make a class that mirrors the table I'm to interact with. Here goes. I made a new package called 'dbclasses' and a class called 'Messages':


package dbclasses;
import java.util.Date;

public class Messages {
    private long messageID;
    private String message;
    private String ip;
    private Date stamp;
    
    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public long getMessageID() {
        return messageID;
    }

    public void setMessageID(long messageID) {
        this.messageID = messageID;
    }

    public Date getStamp() {
        return stamp;
    }

    public void setStamp(Date stamp) {
        this.stamp = stamp;
    }
}
Alright, so now I suppose I should try to import Hibernate and set up their config file. First though, I'm going to the 'Services' tab in Netbeans and connecting to MySQL. So that looks good.

So wow the official Hibernate tutorial is worthless and complicated. This is from netbeans. And this is even better as well. So I went in to 'Create Library' and I added all the required Jars and the JavaDocs to a library called "Hibernate3.6". Then I set up the mappings and config files as follows:


Mappings file: under a the classpath: srvrTest/src/java/hibernatemappings/hibernate.hbm.xml


<hibernate-mapping>
    
    <class name="srvrTest.src.java.dbclasses.Messages" table="Messages">
        <id column="messageID" name="messageID">
            <generator class="native">
        </generator></id>
        <property name="message" />
        <property name="ip" />
        <property column="stamp" name="stamp" type="timestamp" />
    </class>
</hibernate-mapping>


And the config file under: srvrTest/src/java/hibernatemappings/hibernate.cfg.xml


<hibernate-configuration>
  <session-factory>
      
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/messaging</property>
        <property name="connection.username">root</property>
        <property name="connection.password">test</property>

        
        <property name="connection.pool_size">1</property>

        
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

        
        <property name="current_session_context_class">thread</property>

        
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        
        <property name="show_sql">true</property>

        
        
        <mapping resource="srvrTest/src/java/hibernatemapping/hibernate.hbm.xml">
  </mapping></session-factory>
</hibernate-configuration>
And for tonight.. I'm done.

Tomcat- try again 6.0.35 this time

So now I'm using Tomcat 6.0.35 on Netbeans. Whoops- crashed when I tried to add it to my work environment. Hmm well at least fucking MySQL workbench hasn't crashed yet- but I doubt I will even get around to connecting to the DB tonight.

WTF it just crashed when I tried to connect to the MySQL db in the services tab! There are not error messages! There are no logs? Fuck you Netbeans: it's unistall.sh for you. Well in my experience things only go smoothly on linux if you are running things that are a few years old. Looks like I'm going over to windows tomorrow...