Wednesday, October 21, 2009

JSP - gather, process, store, and use session variables

<!-- 
just a typical html form 
This is the "theform.jsp" page 
--> 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head><title>enter form data</title></head> 
    <body> 
    <form method="post" action="formSaver.jsp"> 
        Username: <input type="text" name="username" /><br /> 
        Cool Factor: <input type="text" name="coolfactor" /><br /> 
        <input type="submit" value="submit" /> 
    </form> 
    </body> 
</html> 
 
 
<!-- 
    this page grabs the form data and 
    and (with the help of the UserFormBean class) 
    places the items as session data. 
--> 
 
<!-- the useBean taq is where this jsp page loops in the real classes --> 
<jsp:useBean id="userform" class="userform.UserFormBean" scope="session"/>
<!-- the setProperty tag sends * (all) the property data to userform --> 
<jsp:setProperty name="userform" property="*"/>
<html> 
    <head><title>Form Saver</title></head> 
    <body> 
        <p>Your data has been placed in a session!</p> 
        <p>Try visiting this <a href="unrelatedPage.jsp">unrelated page!</a></p> 
    </body> 
</html> 
 
 
<!-- this is the unrelated page that will pull 
    and display the session data --> 
<!-- this loops in the session data we'll utilize --> 
<jsp:useBean id="userform" class="userform.UserFormBean" scope="session"/>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head><title>an unrelated page</title></head> 
    <body> 
       <%= userform.getUsername() %> | <%= userform.getCoolfactor() %> 
    </body> 
</html> 

/* 
 * This is the actual java class "UserFormBean" 
 * that processes and stores the data. 
 * 
 * Notice that the set methods use 
 * the same names as the form name data! 
 * 
 * */ 
package userform;
 
public class UserFormBean {
    String username;
    String coolfactor;
 
    public void setUsername(String value) {
        username = value;
    }
    public void setCoolfactor(String value) {
        coolfactor = value;
    }
    public String getUsername() {
        return username;
    }
    public String getCoolfactor() {
        return coolfactor;
    }
}
 
 

Tuesday, October 20, 2009

JSP - list all parameter keys and values

<%@page import="java.util.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd"> 
 
<html> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
        <title>JSP display all parameters</title> 
    </head> 
    <body> 
        <% 
 
            // you can get an enumeratable list 
            // of parameter keys by using request.getParameterNames() 
            Enumeration en = request.getParameterNames();
 
            // enumerate through the keys and extract the values 
            // from the keys! 
            while (en.hasMoreElements()) {
                String parameterName = (String) en.nextElement();
                String parameterValue = request.getParameter(parameterName);
                out.println(parameterName+":"+parameterValue+"<br />");
            }
 
            // now call your jsp file (from a browser and add on some paramters) 
            // file.jsp?a=12341234&b=apple&c=1.21gigawatts 
 
        %> 
    </body> 
</html> 
<!-- 
output: 
    a:12341234 
    b:apple 
    c:1.21gigawatts 
 
--> 
 

JSP - include several differnt files to create content

<!-- This is the file "head.jsp" --> 
<!-- This file just has head type info --> 
<html> 
    <head> 
        <title>the title</title> 
    </head> 
 
 
<!-- this is the file "body.jsp" --> 
<!-- this file contains the content portion of the site --> 
 
<body> 
    <p> 
        Content goes here
    </p> 
</body> 
</html> 
 
<!-- this is the file called main.jsp --> 
<!-- this files purpose is to bring in all the 
 
<%@ include file="head.jsp" %>
<%@ include file="body.jsp" %>
 
    <% 
 
    // When you include files you bring the file's data 
    // (whether its html or jsp code) into the calling 
    // page. 
 
    %> 
 

JSP - use directives to import java libraries

<%@ page import="java.util.*" %>
 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd"> 
 
<html> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
        <title>JSP Page</title> 
    </head> 
    <body> 
 
        <% 
        ArrayList ll = new ArrayList();
 
            for (int i=0; i<100; i++) {
                ll.add(i);
            }
        
        %> 
 
        <h1>ArrayList size: <%= ll.size() %> </h1> 
        <h1>Location of item 77: <%= ll.indexOf(77) %> </h1> 
 
    </body> 
</html> 
 
 

JSP - embedding scriptlets inside and around html

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd"> 
 
<html> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
        <title>JSP Page</title> 
    </head> 
    <body> 
        <% 
        // if you need to accomplish a repetitive task 
        // like creating a list of 1,000 numbers and 
        // putting them in a bulletted list then 
        // keep in mind that scriptlets can be your 
        // friend. 
 
        // You notice below that the for loop spans several 
        // pieces of the scriptlet 
        %> 
        <ul> 
        <% 
        for (int i=0; i<1000; i++) {
        %> 
            <li><%= i %></li> 
        <% 
        }
 
        %> 
        </ul> 
        
    </body> 
</html> 
<!-- 
0 
1 
2 
3 
... 
[SNIP] 
... 
998 
999 
--> 
 
 

JSP - declare methods and variables from within a jsp page

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd"> 
 
<html> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
        <title>JSP Page</title> 
    </head> 
    <body> 
        <%! 
            // You can do real coding inside of here! 
            // The code in this section is called a scriptlet. 
            // Any functions or variables you create can 
            // be used later in the file with jsp expression 
            // tags or shortcuts 
 
            // You'll notice that the section began with a 
            // <%! ......this allows you to declare methods 
 
            String s = "Declare methods and variables with scriptlets.";
 
            int getNum() {
                if (1>0){
                    return 100;
                }
                return 111;
            }
        %> 
 
        <h1><%= s %></h1> 
        <h2><%= getNum() %></h2> 
 
    </body> 
</html> 
 
 

JSP - print direct to html

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd"> 
 
<html> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
        <title>JSP print straight out example</title> 
    </head> 
    <body> 
        <% 
            out.println("<h1>Print directly example</h1>");
            out.println("Here is the date:<br />");
            out.println(new java.util.Date());
        %> 
    </body> 
</html> 
<!-- 
my output: 
    Print directly example 
 
    Here is the date: 
    Tue Oct 20 11:21:21 MDT 2009 
--> 
 

JSP - insert simple data with jsp expression

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd"> 
 
<html> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
        <title>java expression example</title> 
    </head> 
    <body> 
        <h1>A JSP TimeDate Stamp Example</h1> 
<!-- 
 you can use jsp expressions with the 
 shortcut percent equals or you can use 
 jsp:expression tags 
 
 --> 
 
        <p> Here is the date using the shortcut
        percent equals syntax:<br /> 
        <%= new java.util.Date() %> </p> 
 
        <p> Here is the same date stamp using the
        jsp expression tags: <br /> 
        <jsp:expression>new java.util.Date()</jsp:expression></p> 
 
 
    </body> 
</html> 
<!-- Here is my output: 
 
A JSP TimeDate Stamp Example 
 
Here is the date using the shortcut percent equals syntax: 
Tue Oct 20 10:52:53 MDT 2009 
 
Here is the same date stamp using the jsp expression tags: 
Tue Oct 20 10:52:53 MDT 2009 
 
--> 
 

Tuesday, October 6, 2009

Java - pig latin generator

 
package javasomethingsomething;
 
public class Main {
    public static void main(String[] args) {
        // all the heavy lifting is done in the PigLatin class 
        PigLatin pg = new PigLatin();
        String pigSentence = "";
        String sentence = "This is going to be a pig latin sentence";
        // iterate over the sentence with for-each and split by " " 
        for (String s:sentence.split(" ")) {
            pigSentence += pg.getPigLatinForWord(s) + " ";
        }
        // added the trim to remove the trailing space 
        System.out.println(pigSentence.trim());
    }
 
}
 
class PigLatin{
 
    public String getPigLatinForWord(String word) {
        int firstVowel = word.length();
        // yes, I included y as a vowel!! 
        String[] vowels = {"a", "e", "i", "o", "u", "y"};
        for(String s:vowels){
            // if indexOf() finds no match it returns -1 
            if ((word.indexOf(s) < firstVowel) && (word.indexOf(s) != -1)) {
                firstVowel = word.indexOf(s);
            }
        }
        return  word.substring(firstVowel, word.length()) +
                word.substring(0, firstVowel) +
                "ay";
    }
}
 

Friday, September 25, 2009

Java - a ping example with java's InetAddress.isReachable()

import java.net.*;
public class Main {
 
    public static void main(String[] args) {
        try{
            // a note: 
            // This the isReachable method is problematic 
            // If you are in a coorporate environment 
            // then you are probably (unknown to you) 
            // using proxy servers.  Java needs to know 
            // what the proxy server and port is 
            // DhttpProxy.host=yourproxyhost.com -DhttpProxy.port 
            // 
            // All of testing I've done at home works fine. 
            // You need to configure java to utilize your proxy 
 
            // gather the ip address associated with the host 
            InetAddress[] addresses = InetAddress.getAllByName("yahoo.com");
 
            // iterate through the ip address with for-each 
            for (InetAddress addr:addresses) {
 
                // the timeout is in milliseconds 2 seconds here 
                if (addr.isReachable(2000)){
                    System.out.printf("%s is reachable", addr);
                    System.out.println();
                }
                else{
                    System.out.printf("%s is not reachable", addr);
                    System.out.println();
                }
            }
        }
        catch(Exception e) {
            System.out.println("host is unknown (or unresolvable)");
        }
    }
}
/* 
 *      Output (for me): 
        yahoo.com/69.147.114.224 is reachable 
        yahoo.com/209.131.36.159 is reachable 
        yahoo.com/209.191.93.53 is reachable 
*/ 
 

Java - reverse the word order of a sentence

public class Main {
 
    public static void main(String[] args) {
        Words w = new Words();
        String sentence = "The example sentence is here";
        System.out.println(sentence);
        System.out.println("reversed to:");
        System.out.println(w.reverseWordOrderOfSentence(sentence));
    }
}
 
class Words{
    public String reverseWordOrderOfSentence(String sentence){
        // split up by words 
        String[] words = sentence.split(" ");
        sentence = "";
 
        // iterate backward through the array 
        // rebuilding the sentence from the back forward 
        for (int i=words.length; i>0; i--){
            sentence += words[i-1];
            sentence += " ";
        }
        // remove the trailing white space 
        return sentence.trim();
    }
}
 
/* 
 *      OUTPUT: 
        The example sentence is here 
        reversed to: 
        here is sentence example The 
*/ 
 

Java - extracting rgb values from an image

import javax.imageio.*;
import java.awt.image.*;
import java.io.*;
 
public class Main {
    public static void main(String[] args) {
        BufferedImage bimg = null;
        String input = "test.jpg";
        try{
            bimg = ImageIO.read(new File(input));
        }
        catch (Exception e) {
            // the test.jpg must be in the working dir  
            System.out.println(input + " is not in working dir");
        }
 
        System.out.println("height: " + Integer.toString(bimg.getHeight()));
        System.out.println("width: " + Integer.toString(bimg.getWidth()));
 
        // collect the rgb information 
        // regarding a single pixel 
        int rgb = bimg.getRGB(10, 10);
 
        // for some smart reason (that is beyond me) 
        // getting the rgb gives you a single int 
        // 
        // each component of colr occupies 8 bits 
        // this extracts the actual alpha, red, green, blue 
        int a = (rgb >>> 24) & 0xFF;
        int r = (rgb >>> 16) & 0xFF;
        int g = (rgb >>> 8) & 0xFF;
        int b = (rgb >>> 0) & 0xFF;
 
        // here is the proof 
        System.out.println("a: " + Integer.toString(a));
        System.out.println("r: " + Integer.toString(r));
        System.out.println("g: " + Integer.toString(g));
        System.out.println("b: " + Integer.toString(b));
 
        // this scripts output: 
        /* 
            height: 564 
            width: 634 
            a: 255 
            r: 222 
            g: 128 
            b: 184 
        */ 
    }
 
}
 
 

Java - remove vowels from a sentence String

public class Main {

    public static void main(String[] args) {
      NotStatic g = new NotStatic();
      String sentence = "This is my example sentence.";
      String s = g.RemoveVowelsFromSentence(sentence);
      System.out.println(s);

      // output:

      //    Ths s m xmpl sntnc.

    }
}
class NotStatic {

    public String RemoveVowelsFromSentence(String sentence) {
        String[] vowels = {"a", "e", "i", "o", "u", "y"};
        // iterate through the vowel array with for-each

        for (String s:vowels){
            sentence = sentence.replaceAll(s, "");
        }

        return sentence;

    }

}


Java - Hashtable example - how to create and use

import java.util.*;

public class Main {

    public static void main(String[] args) {
        // a hashtable is like a dictionary

        // to put items into the hashtable you 
        // need a key and a value.  The keys must
        // be unique -- while the values can be
        // anything you like
        Hashtable ht = new Hashtable();

        // put new values into ht

        ht.put("name", "Steve");
        ht.put("warpFactor", 9);

        String s = "";
        // looping add
        for (int i=0; i<20; i++) {
            s = Integer.toString(i);
            s += " is a good number";
            ht.put(i, s);
        }

        // use the values in the hashtable

        System.out.println("I hear that " +
                ht.get("name").toString() +
                " has a Warp Factor of " +
                ht.get("warpFactor").toString());

        // outputs:
        // I hear that Steve has a Warp Factor of 9

    }
}


Java - how to create and use a LinkedList

import java.util.*;

public class Main {
    
    public static void main(String[] args) {
        LinkedList ll = new LinkedList();

        // add to linked list

        ll.add("first String object");

        // total items in the linked list
        System.out.println(ll.size());
        // indicates:  1

        // the list is not type specific
        // Strings and ints can coexist

        ll.add(22);

        // add ten more items
        for (int i=0; i<10; i++){
            ll.add(i);
        }

        String oType = "";
        // iterate through all existing items
        //  with for-each

        for(Object o:ll){
            oType = o.getClass().toString();
            System.out.println(o.toString() + 
                    ", is type: " + oType);
        }

        // remove items from list
        ll.removeFirstOccurrence(3);

        // remove the first item from the list
        ll.remove();

        // remove the last item from the list
        ll.removeLast();
    }
}



Thursday, September 24, 2009

Java - how to create and use a Vector

import java.util.*;
public class Main {
 
    public static void main(String[] args) {
        Vector v = new Vector();
        // The Vector class is almost identical to the 
        //  ArrayList class.  The main difference is that 
        //  a Vector is thread safe. 
        v.add("number one is a String");
        v.add(22); // number two is an Integer 
 
        for (int i=0; i<10; i++){
            // add ten integers 
            v.add(i);
        }
 
        // iterate through the vector with a foreach 
        for (Object o:v){
            System.out.println(o);
        }
        // as with ArrayLists you'll notice that 
        //  Vectors are not type specific.  You can 
        //  put in whatever you want 
    }
}
 
 

Java - how to create and use an ArrayList

import java.util.*;
 
// related posts:
// old (but fast) school array
// Thread safe vectors
// 
// 


public class Main {
 
    public static void main(String[] args) {
 
        // arraylists do not require a size definition 
        // when you declare or instantiate. 
        // you can add to your hearts content 
        ArrayList al = new ArrayList();
 
        al.add("number one");
 
        // display the size of the ArrayList 
        System.out.println(al.size());
        // indicates:  1 
 
        // fill up with 10 
        for (int i=0; i<10; i++){
            // you'll notice that it just appends to 
            // the existing list.  "number one" remains 
            // and all the numbers are tacked on after 
            al.add(i);
        }
 
        // display all ten with foreach 
        //for (Object o:al 
        for (int i=0; i<al.size(); i++){
            System.out.println(al.get(i) + " is type " +
                    al.get(i).getClass().toString());
        }
 
        // you'll notice from the output that a Java ArrayList 
        // can have a mixture of object types.  Here we 
        // blend Integer and String 
    }
}
 
 

Java - create and use a String or int array

 
public class Main {
    public static void main(String[] args) {
        // standard, fast, old school array 
        // string array 
        String[] stringArray = new String[10];
        stringArray[0] = "first item in array";
        System.out.println("array length: " + stringArray.length);
        // indicates:  10 
        // even if you've only populated 
        // one of the you allocated room for 10 
 
        // you can also for loop through and populate 
        String tempString = "";
        for (int i=0; i<stringArray.length; i++){
            tempString = Integer.toString(i+1);
            stringArray[i] = "arrayitem " + tempString;
        }
 
        // display contents of array 
        //  with a for each 
        for (String s:stringArray){
            System.out.println(s);
        }
 
 
        // same methodology for an int array 
        int[] intArray = new int[10];
        intArray[0] = 213;
    }
 
}
 
 

Java - find the working directory


import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        // to find out where your application is running 
        //  (sounds easy but its sometimes tricky) 
        System.out.println("This Java applications working directory is:");
        // Java has a list of Properties that it uses for everything 
        // the working directory property is user.dir 
        // you can check it out with: 
        System.out.println(System.getProperty("user.dir"));
 
        // you can see all the properties with this: 
        System.out.println(System.getProperties());
        // it will just dump them all out in a not 
        //  organized way 
 
        // you can also iterate through all of the properties 
        //  and print them out line by linewith: 
        Properties myProps = System.getProperties();
        for (Enumeration e = myProps.keys(); e.hasMoreElements();/**/){
            String key = (String)e.nextElement();
            String value = myProps.getProperty(key);
            System.out.println(key + " = " + value);
        }
    }
}
 
 

Java - open and read text file



/* 
 * To change this template, choose Tools | Templates 
 * and open the template in the editor. 
 */ 
 
package readfile;
 
import java.io.*;
 
 
public class Main {
 
    public static void main(String[] args) {
 
        // this assumes you have 'test.txt' in your working directory 
        String filename = "test.txt";
 
        try {
            // open file 
 
            BufferedReader reader = new BufferedReader(new FileReader(filename));
            String line;
 
            // iterate through file's lines 
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
 
 
        }
 
        catch(Exception e) {
            System.out.println("file not found");
            System.out.println(e.getMessage());
            System.out.println(e.toString());
 
        }
 
 
    }
 
}
 
 
// output (for my test file): 
//  one 
//  two 
//  three 
 
 

Wednesday, September 23, 2009

Java - cast int to string and string to int


public class Main {

    public static void main(String[] args) {
        String s = "23";
        int i = 22;

        // int to string
        String iString = Integer.toString(i);
        System.out.println(iString);
        // output:
        //  22

        // string to int
        int sInt = Integer.parseInt(s);
        System.out.println(sInt);
        // output:
        //  23
    }
}