Changing Timezon and NTP On Ubuntu server

May 5th, 2008 admin No comments

Timezon Config

dpkg-reconfigure tzdata

Time Synchronisation with NTP

as root, create a file /etc/cron.daily/ntpdate containing:
ntpdate ntp.ubuntu.com
The file /etc/cron.daily/ntpdate must also be executable
sudo chmod 755 /etc/cron.daily/ntpdate

Categories: System Tags: , , ,

SwingWorker not on Java 6.0

April 24th, 2008 admin 4 comments

SwingWorker is useful when a time-consuming task has to be performed following a user-interaction event (for example, parsing a huge XML File, on pressing a Button). The most straightforward way to do it is :

[sourcecode language='java']
private Document doc;

JButton button = new JButton(“Open XML”);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doc = loadXML();
}
});
[/sourcecode]

This will work, but unfortunately, the loadXML() method will be called in the same thread as the main Swing thread, so if the method needs time to perform, the GUI will freeze during this time.

[sourcecode language='java']
package com.wsjoung.demo;
import javax.swing.SwingUtilities;

public abstract class SwingWorker {
// see getValue(), setValue()
private Object value;
private Thread thread;

private static class ThreadVar {
private Thread thread;
ThreadVar(Thread t) { thread = t; }
synchronized Thread get() { return thread; }
synchronized void clear() { thread = null; }
}

private ThreadVar threadVar;

protected synchronized Object getValue() {
return value;
}

private synchronized void setValue(Object x) {
value = x;
}

public abstract Object construct();

public void finished() {
}

public void interrupt() {
Thread t = threadVar.get();
if (t != null) {
t.interrupt();
}
threadVar.clear();
}

public Object get() {
while (true) {
Thread t = threadVar.get();
if (t == null) {
return getValue();
}
try {
t.join();
}
catch (InterruptedException e) {
// propagate
Thread.currentThread().interrupt();
return null;
}
}
}

public SwingWorker() {
final Runnable doFinished = new Runnable() {
public void run() { finished(); }
};

Runnable doConstruct = new Runnable() {
public void run() {
try {
setValue(construct());
}
finally {
threadVar.clear();
}

SwingUtilities.invokeLater(doFinished);
}
};

Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
t.start();
}
}
[/sourcecode]

SwingWorker.java

[sourcecode language='java']
public class Task{
public void go() {
current = 0;
final SwingWorker worker = new SwingWorker() {
public Object construct() {
return new ActualTask();
}
};
}

class ActualTask {
ActualTask() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}
[/sourcecode]

Task.java

Categories: Java, Programming Tags: ,

pure-ftpd-mysql, [ERROR] Home directory not available – aborting

April 15th, 2008 admin 1 comment

groupadd -g 2001 ftpgroup
useradd -u 2001 -s /bin/false -d /bin/null -c “pureftpd user” -g ftpgroup ftpuser

Instead of this dummy ftpuser account setting when they want to create real linux account.
they may get this error “Home directory not available – abort” even if they set CreateHomeDir to yes.

Solution:
the last existing in the home path should be own by root.
for example, we want to create somebody’s home directory when he log in, /home/ftpuser/somebody
then the last existing directory ‘ftpuer’ may look like this,
drwxr-xr-x 2 root ftpgroup 4096 2008-04-15 11:20 ftpuser

[pure-ftpd] CreateHomeDir problem (“[ERROR] Home directory not available – aborting”)
Virtual Hosting With PureFTPd And MySQL (Incl. Quota And Bandwidth Management) On Ubuntu 7.10 (Gutsy Gibbon)

Categories: System Tags: , , , ,

what's static?

April 14th, 2008 admin 1 comment

First of all, the meaning of static in java is embedded or belong to a specific class not to its instance, and therefore there is no such static class.

  • There is no such static class
  • Embedded or belong to a specific class
  • Global variable
  • No need to load and create its instance

Most of methods and variables in Math class are static, because those are not need to be instanced in most of cases. we just use return value of PI or max(int a, int b).

class Bicycle {

private static int numberOfBicycles = 0;
private int id;

public Bicycle() {
id = ++numberOfBicycles;
}

public static int getNumberOfBicycles() {
return numberOfBicycles;
}
public int getID() {
return id;
}

public static void main(String[] args) {
Bicycle b1 = new Bicycle();
Bicycle b2 = new Bicycle();

System.out.println(“static result : “+getNumberOfBicycles());
System.out.println(“static result : “+numberOfBicycles);
System.out.println(“instance result : “+b1.getID());
System.out.println(“instance result : “+b2.getID());
}
}

Another characteristic of static is that even if we create instance of a class, jvm does not create instance variables for static resources. in above source code, there is no difference calling b1.getNumberOfBicycles(), b2.getNumberOfBicycles() and just getNumberOfBicycles() or directly numberOfBicycles
that mean we should call static variable with its class name because it’s belong to it. just like Bicycle.numberOfBicycles or in this example, getNumberOfBicycles() because we have a getter.
otherwise get confused.

Categories: Programming Tags: , ,

SQL Style, Theta vs. ANSI

April 11th, 2008 admin No comments

Theta Style:
SELECT i.order_id, p.product_id, p.name, p.desc
FROM CustomerItem i, Product p
WHERE i.product_id = p.product_id
AND i.order_id = 84463;

ANSI Style:
SELECT i.order_id, p.product_id, p.name, p.desc
FROM CustomerItem i
INNER JOIN Product p ON i.product_id = p.product_id
WHERE i.order_id = 84463;

Sometimes, it’s hard to realized whether there is other style of SQL. Obviously there are two different SQL style. theta is older and more obscure but many people still use it.

Categories: Database Tags: ,

Interview questions

February 6th, 2008 admin 2 comments
  • what’s difference C++ and java
  • explain about java static
  • is java use call by reference or call by value
  • get the algorithm to fine nth value from the last element in single linked list, and write code

all questions look pretty easy though,

anyway, the last algorithm question. because it’s just one direction single linked list, we should travelĀ from the start node to the last node. then we figure it out how many elements in that linked list when we reached the last element. then we can simply travel again from the start node to (m-n)th element. complexity is O(n).
I was trying to bring up some other data structure like stack or hash table but, all those are not good in terms of space efficiency. we do not have to wast precious resource which doesn’t increase the performance that much.

DataSource setup on Tomcat

September 21st, 2007 admin Comments off

1. create META-INF/context.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<Context docBase=”e-sports” path=”/e-sports” debug=”0″ reloadable=”true”
source=”org.eclipse.jst.j2ee.server:e-sports”>
<Logger className=”org.apache.catalina.logger.FileLogger”
prefix=”e-sports_log.” suffix=”.txt” timestamp=”true” />
<Resource name=”jdbc/myoracle”
auth=”Container”
type=”javax.sql.DataSource”
driverClassName=”oracle.jdbc.driver.OracleDriver”
factory=”org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory”
url=”jdbc:oracle:thin:@127.0.0.1:1521:ORA92″
username=”scott”
password=”tiger”
maxActive=”20″
maxIdle=”10″
maxWait=”-1″ />
</Context>

2. test.jsp
<%@ page import=”java.sql.Connection” %>
<%@ page import=”java.sql.ResultSet” %>
<%@ page import=”java.sql.SQLException” %>
<%@ page import=”java.sql.Statement” %>
<%@ page import=”javax.naming.Context” %>
<%@ page import=”javax.naming.InitialContext” %>
<%@ page import=”javax.naming.NamingException” %>
<%@ page import=”javax.sql.DataSource” %>

<%
Context ctx = null;
DataSource source = null;
Connection con = null;

try {
ctx = new InitialContext();
ctx = (Context) ctx.lookup(“java:comp/env”);
source = (DataSource) ctx.lookup(“jdbc/myoracle”);

System.out.println(“DataSource ===========================”+ source);

con = source.getConnection();
System.out.println(“Connection ============================”+ con);
} catch (NamingException ne) {
ne.printStackTrace();
}
%>

Categories: Server Tags: , , ,

javamail smtp with Gmail

August 3rd, 2007 admin Comments off

package com.mycompany.emailsender;

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

import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
* Servlet implementation class for Servlet: GmailSender
*
*/
public class GmailSender extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public GmailSender() {
super();
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
final String SMTP_HOST_NAME = “smtp.gmail.com”;
final int SMTP_HOST_PORT = 465;
final String SMTP_AUTH_USER = “XXXXXX@gmail.com”;
final String SMTP_AUTH_PWD = “XXXXXX”;
final String SSL_FACTORY = “javax.net.ssl.SSLSocketFactory”;

String emailFromAddress = null;
String[] sendTo = null;
String subject = null;
String content = null;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

String address = request.getParameter(“address”);
sendTo = address.split(“;”);

emailFromAddress = request.getParameter(“sender”);
this.subject = request.getParameter(“title”);
this.content = request.getParameter(“content”);

try {
for (int i=0; i<sendTo.length; i++) {
sendSSLMessage(sendTo[i]);
}
System.out.println(“Sucessfully Sent mail to All Users”);

} catch (Exception e) {System.out.println(e);}
}

public void sendSSLMessage(String dest) throws MessagingException {

Properties props = new Properties();

props.put(“mail.transport.protocol”, “smtps”);
props.put(“mail.smtps.host”, SMTP_HOST_NAME);
props.put(“mail.smtps.auth”, “true”);
props.put(“mail.smtps.quitwait”, “false”);

Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(false);
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setSubject(subject);
InternetAddress addressFrom = new InternetAddress(emailFromAddress);
message.setFrom(addressFrom);
message.setContent(content, “text/html”);

message.addRecipient(Message.RecipientType.TO,new InternetAddress(dest));

transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}

reference: http://www.rgagnon.com/javadetails/java-0083.html

Signed java applet

May 15th, 2007 admin No comments

Applet Security Basics

Below are the basic facts regarding applet security and Java Plug-in. More detail can be found in the next chapter, How RSA Signed Applet Verification Works in Java Plug-in.

  • All unsigned applets are run under the standard applet security model.
  • If usePolicy IS NOT DEFINED in the java.policy file, then a signed applet has the AllPermission permission if:
    Java Plug-in can verify the signers, and the user, when prompted, agrees to granting the AllPermission permission.
  • If usePolicy IS DEFINED, then a signed applet has only the permissions defined in java.policy and no prompting occurs.

Moreover, note that Java Plug-in now handles certificate management; i.e., the certificate verification task is no longer passed off to the browser.

keytool -genkey -keyalg rsa -alias MyCert
keytool -certreq -alias MyCert
keytool -import -alias MyCert -file VSSStanleyNew.cer

or

keytool -selfcert

and

jarsigner AppletName.jar MyCert
jarsigner -verify -verbose -certs AppletName.jar

Categories: Programming Tags: , , ,

Eclipse web.xml validation problem

February 7th, 2007 admin No comments

The problem is because of “http://java.sun.com/xml/ns/j2ee/j2ee_1_4.xsd” fil, it points ibm’s schema instead of Sun’s

Window -> Preferences… -> Web and XML -> XML Catalog

URI : http://java.sun.com/xml/ns/j2ee/j2ee_web_services_client_1_1.xsd
Key Type : Schema Location
Key : http://www.ibm.com/webservices/xsd/j2ee_web_services_client_1_1.xsd

Thanks Carey Evans

Categories: Software Tags: , , ,