Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Sunday, September 19, 2010

Initialized servlet on deploy

We have to implements ServletContextListener and add the class into web.xml

example ... servlet class name MyServlet.java




import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet implements ServletContextListener {

...
...


// implement methods

public void contextInitialized(ServletContextEvent sce) {
System.out.println("MyServlet initialized...");
}

public void contextDestroyed(ServletContextEvent sce) {
System.out.println("MyServlet destroyed...");
}

}




in web.xml





MyServlet
MyServlet
1


MyServlet
/MyServlet


MyServlet



30






Tuesday, June 16, 2009

Convert an array to collection

import java.util.Arrays;
import java.util.List;
import java.util.Iterator;

public class ArraysExample
{
public static void main(String[] args)
{
String[] array = {"Happy", "New", "Year", "2006"};
List list = Arrays.asList(array);

Iterator iterator = list.iterator();
while (iterator.hasNext())
{
System.out.println((String) iterator.next());
}
}
}

The result of our code is:

Happy
New
Year
2006

ref: http://www.kodejava.org/examples/25.html

Tuesday, June 9, 2009

Get number of rows in resultset

You can extract the data from the resultset from the top and rs.last() will move you to the end of the resultset.

Then, the method rs.getRow() get the row number of the last row and also shows you the number of rows in the table.

For example:

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
String query = "select [table_field] from [table_name]";
stmt = conn.createStatement();

rs = stmt.executeQuery(query);
while (rs.next()) {
String id = rs.getString(1);
}
rs.last();
int rowCount = rs.getRow();
System.out.println("Number of Rows=" + rowCount);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {}
}


ref: http://www.roseindia.net/java/java-get-example/number-rows-resul.shtml

Thursday, June 4, 2009

java BigDecimal problem

BigDecimal v = new BigDecimal(0.12d);
System.out.println(v);

result: 0.11999999999999999555910790149937383830547332763671875

Because ::: In Java API

public BigDecimal(double val)

Translates a double into a BigDecimal. The scale of the BigDecimal is the smallest value such that (10scale * val) is an integer.

Note: the results of this constructor can be somewhat unpredictable.

---

But ...


BigDecimal v = new BigDecimal("0.12");
System.out.println(v);

result: 0.12

Because:

The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.

ref: http://www.narisa.com/forums/index.php?showtopic=12589&st=15

java decimal using BigDecimal

BigDecimal v = new BigDecimal(0.0d);
BigDecimal av = new BigDecimal(0.1d);
av = av.setScale(2, RoundingMode.HALF_EVEN);
for (int i = 0; i < 10; i++) {
v = v.add(av);
System.out.println(v);
}

ref: http://www.narisa.com/forums/index.php?showtopic=12589&st=0

java decimal format

java.text.DecimalFormat dfm = new java.text.DecimalFormat("0.00");

double d = 0.123d;
System.out.println(dfm.format(d)); // 0.12

d = 0.129d;
System.out.println(dfm.format(d)); // 0.13

d = new Double(dfm.format(d)).doubleValue();
System.out.println(d); // 0.13


OR ...

DecimalFormat changeFormat = new DecimalFormat("#,##0.00");

double a = 20213243;

BigDecimal aa = new BigDecimal(a);

BigDecimal divideA = aa.divide(new BigDecimal(3),4,4);

System.out.println("divideA = "+divideA);
System.out.println("Result = "+changeFormat.format(divideA));


result:
divideA = 6737747.6667
Result = 6,737,747.67

ref: http://www.narisa.com/forums/index.php?showtopic=12589&st=0

Wednesday, June 3, 2009

java double problem

public class HOWCOME
{
public static void main(String[] args) {
double v = 0.0d;
for (int i = 0; i < 10; i++) {
v += 0.1d;
}
System.out.println(v);
}
}

ref: http://www.narisa.com/forums/index.php?showtopic=12589&st=0

MIT Java Wordnet Interface

JWI (the MIT Java Wordnet Interface) is an easy-to-use, easy-to-extend Java library for interfacing with Wordnet. JWI supports access to Wordnet versions 1.6 through 3.0. Wordnet is a freely and publicly available semantic dictionary of English, developed under the direction of George Miller at Princeton University.

here is url: http://projects.csail.mit.edu/jwi/

Wednesday, May 27, 2009

Convert an input String to InputStream

We can use java.io.ByteArrayInputStream and use string.getBytes() like this

String input = "Input Stream";
try {
ByteArrayInputStream ba = new ByteArrayInputStream(input.getBytes());

// TODO Codes //
// ...
// ...
//

} catch (Exception e) {
e.printStackTrace();
}
Somebody use this solution for parser xml ^^, have a fun !!!


Tuesday, May 26, 2009

StringTokenizer how to

StringTokenizer stn = new StringTokenizer(string_text);
while (stn.hasMoreTokens()) {
String s = (String) stn.nextElement();
System.out.println(s);
}

Saturday, May 23, 2009

การ init ค่าใน Array เริ่มต้นของ java

เราทราบกันว่า การสร้าง array เป็นอย่างไรแล้ว ... แต่ ถ้าเราต้องการสร้าง array ขนาด 100 สมาชิก และอยากให้แต่ละสมาชิกมีค่า 0 หรือ 1 ทั้งหมดเราควรทำอย่างไร?

วิธีแรก ... กำปั้นทุบดิน ...

เราก็สร้าง array มา 100 ตัว ... จากนั้นก็วน loop ใส่ค่า 1 ให้กับทุกสมาชิก ดังนี้

int[] ex = new int[100];
for (int i = 0; i < ex.length; i++) {
ex[i] = 1;
}

อืม ... มันก็ง่ายดีครับ ... แต่มันคงไม่ดีแน่ ... ผมเลยหาๆ ดูใน api java (อันที่จริงเคาะ ctrl + space bar ใน ide มากกว่า) ก็ไปเจอ static method ใน Arrays ครับ จึงเป็นที่มาของวิธีที่สอง

วิธีที่สอง ... ใช้ Arrays.fill(Obj[], Obj_value);

ครับ ... เราสามารถใช้คำสั่ง Arrays.fill(ตัวแปรที่เป็น array อยู่แล้ว, ค่าที่ต้องการ) ซึ่งในที่นี้ผมให้เป็น 1

int[] ex = new int[100];
Arrays.fill(ex, 1);

เรียบร้อยครับ ... :) ก็เป็นการใช้สิ่งที่มีอยู่ให้เกิดประโยชน์ครับ :D

Wednesday, May 13, 2009

Reading and Writing from a URL

I didn't like to remember a lot of code in my memory ... so ... sometime I forget it T_T.

Then, I'd like to have some place that I can store my code like this :)

...

import java.net.*;
import java.io.*;

public class URLReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);

in.close();
}
}

ref: http://java.sun.com/docs/books/tutorial/networking/urls/readingURL.html


...

If you'd like to write a file together, use this way ...

...


import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class URLReaderAndWriter {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));

FileOutputStream fout = new FileOutputStream("test.txt");

String inputLine;

while ((inputLine = in.readLine()) != null) {
fout.write(inputLine.getBytes());
fout.write('\n'); // for new line if you want

}

fout.close();
in.close();
}
}

Setting java proxy

I had many problems with internet proxy. And I forgot every time when I want to create a file that access pass proxy.

This code is a method to set proxy:

private static void setProxy() {
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("http.proxyHost", "server_host");
systemSettings.put("http.proxyPort", "server_port");
}

And with the java command, you can use this to pass the proxy
$ java -DproxyHost="server_host" -DproxyPort="server_port" pkg.JavaClass



Have a fun