ZengCode.Com (The Thai Php Framework)  


Home   Download   Manual   About us    

Facebook   


MAIN MENU
เขียนโปรแกรมบน iPhone ด้วย MonoTouch
News
Php Tips
Ubuntu
Spring+Strut+Hibernate
Android Programming
Design Pattern By PHP
C# Design Pattern
Linux Quick Tips
C# Tips & Technique
C# using Linq น่าใช้จริงๆ
Java & JavaScript Tips
MAVEN
Database & SQL
ZengCode Framework Guide
Mac OSx
Zeng Code Code
Programming
IPhone (Tips and Trick)

Download เอกสารที่น่าสนใจ

สวัสดีครับแฟนๆ Madoogun.com ยินดีต้อนรับสู่บ้านใหม่ครับ

ZengCode framework ขอฝากเนื้อฝากตัวกับชาว Developer ทุกท่านด้วยนะครับ
ผู้พัฒนาเองไม่ได้หวังว่ามันจะใช้งานได้ดีขนาดไปเทียบกับจ้างยุทธจักรด้านนี้
ไม่ว่าจะเป็น Prado หรือแม้แต่ Cake ซึ่งนั้นเค้าระดับเทพเรียกพี่แล้วครับ
ผมก็เป็นแค่ Developer ธรรมดา ๆ คนนึงครับ
ที่สร้าง framework ตัวนี้ขึ้นมาก็เพื่อศึกษา และพัฒนาทักษะด้าน OOP ของตัวเอง
อีกทั้งปกติตัวผมเองเขียนโค้ดได้มั่วซั่วมาก ไม่มีระเบียบ อยากเขียนอะไรคิดออกก็เขียน
ไม่มีแบบแผน บางทีกลับมาแก้โค้ดตัวเอง บอกได้คำเดียวว่า เซ็งโครต เซ็ง โครต โครต
และนี่จึงเป็นที่มาของชื่อ framework ของผมครับ
และอีกประเด็นก็เพื่อจุดประการให้พี่น้องชาว Developer ทุกท่าน
ช่วยกันคิดพัฒนาสิ่งต่างๆ เพื่อวงการด้าน IT
ของเราได้ทัดเทียมนานาอารยะประเทศเค้านะคร ับผมขอเป็นจุดเล็กๆจุดนึงที่พร้อมจะมุ่งมั่น
พัฒนาผลงานด้านนี้ต่อไปครับ สู้ๆ นะพี่น้องชาว Developer ทุกท่าน

!!!   สดๆร้อนๆ กับ ZengAjax-Client/Server คลิ๊กเลยครับ !!!
!!!   เสร็จแล้วครับ ZengBatis ORM คลิ๊กเลยครับ !!!
!!!
  
ติดจรวดให้เว็บด้วย  ZengCache คลิ๊กเลยครับ !!!

แจกโปรแกรมฝึกท่องศัพท์ภาษาอังกฤษกว่า 4000 คำ โปรแกรมจะรันอยู่ด้านบนสุดของจอภาพ
มันจะ random ศัพท์ทุกๆ 10 วินาทีครับ  
Download

บทความล่าสุด

 HashMap example in Java  (2012-01-31)

HashMap Example in JAVA

เรื่องง่ายๆที่บางครั้งยังต้องถามกูเกิล

import java.util.*;

class HashMapDemo {

public static void main(String args[]) {

// Create a hash map

Map hm = new HashMap();

// Put elements to the map

hm.put("John Doe", new Double(3434.34));

hm.put("Tom Smith", new Double(123.22));

hm.put("Jane Baker", new Double(1378.00));

hm.put("Todd Hall", new Double(99.22));

hm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries

Set set = hm.entrySet();

// Get an iterator

Iterator i = set.iterator();

// Display elements

while(i.hasNext()) {

Map.Entry me = (Map.Entry)i.next();

System.out.print(me.getKey() + ": ");

System.out.println(me.getValue());

}

System.out.println();

// Deposit 1000 into John Doe's account

double balance = ((Double)hm.get("John Doe")).doubleValue();

hm.put("John Doe", new Double(balance + 1000));

System.out.println("John Doe's new balance: " +

hm.get("John Doe"));

}

}

มีต่อนะครับ


อ่านต่อคลิกที่นี้


 Example to implement the HandlerInterceptorAdapter in Spring Framework  (2011-12-09)

org.springframework.web.servlet.handler
public abstract class org.springframework.web.servlet.handler.HandlerInterceptorAdapter
extends java.lang.Object


implements org.springframework.web.servlet.HandlerInterceptor
Abstract adapter class for the HandlerInterceptor interface, for simplified implementation of pre-only/post-only interceptors.

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class DefaultInterceptor extends HandlerInterceptorAdapter {

    private static Logger log = LoggerFactory.getLogger(DefaultInterceptor.class);

 // Spring 3.0 does not support exclusion yet,
    private List<String>excludeList = null;

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
         String requestUri = request.getRequestURI();
        log.debug("RequestUri: " + requestUri);
        HydraPrincipal p = null;
        if (!excludeHandle(requestUri)) {
            if (something) {
                response.sendRedirect("error_page.html");
                return false;
            }

        }
            //request.getSession().setAttribute("something", "somevalue");

        }
        return super.preHandle(request, response, handler);
    }

    private boolean excludeHandle(String requestUri) {
        if (excludeList!=null) {
            for (String exclude : excludeList) {
                if (requestUri.endsWith(exclude)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
    throws Exception { //NOSONAR this is actually an override
        // TODO Auto-generated method stub
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception { //NOSONAR this is actually an override
        if(!excludeHandle(request.getRequestURI())) {
            modelAndView.addObject("buildVersion", properties.getBuildVersion());
        }
        super.postHandle(request, response, handler, modelAndView);
    }

    public List<String> getExcludeList() {
        return excludeList;
    }

    public void setExcludeList(List<String> excludeList) {
        this.excludeList = excludeList;
    }
}

==================================
config.xml
==================================

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path = "/*.html" />
            <bean class="com.XXX.DefaultInterceptor">
                <property name="excludeList">
                    <list>
                        <value>/authtenticated.html</value>
                        <value>/accessdenied.html</value>
                    </list>
                </property>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>
      
    <bean class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver"/>

 

 


อ่านต่อคลิกที่นี้


 Setting up JAVA environment on Ubuntu10.04  (2011-11-23)

Correct java version

Check your java version with:

java -version

If it is not correct, you need to set the "alternatives" correctly:

sudo update-alternatives --list java
sudo update-alternatives --set java /usr/lib/jvm/java-6-sun/jre/bin/java
sudo update-alternatives --set javac /usr/lib/jvm/java-6-sun/bin/javac
sudo update-alternatives --set javaws /usr/lib/jvm/java-6-sun/jre/bin/javaws

Additions to environment file

Add the following to $HOME/.bashrc:

export JDK_HOME=/usr/lib/jvm/java-6-sun/
export JAVA_HOME=$JDK_HOME
export MAVEN_OPTS="-Xms256m -Xmx712m -XX:PermSize=128m -XX:MaxPermSize=256m -XX:NewSize=64m -XX:MaxNewSize=128m -Dfile.encoding=UTF-8 -Denv=dev"

After the change, do:
source $HOME/.bashrc


อ่านต่อคลิกที่นี้


 JAVA : Buffering usually appropriate  (2011-11-10)

Buffering usually appropriate

Buffering input/output มักจำเป็นในการใช้งาน และควรจะหัดให้เป็นนิสัยนะครับ

Unbuffered input/output classes มักจะทำงานกับ 1 byte ต่อหนึ่งช่วงเวลา การใช้ buffer จะช่วยให้ performmance ดีขึ้น

Example runy ตัวอย่างไฟล์ข้างล่าง , ถ้าใช้ buffer จะเร็วขึ้นประมาณ 3 เท่า.
Size -  624 bytes :
With buffering: 10 ms
Without buffering: 30 ms

Size - 10,610 bytes :
With buffering: 30 ms
Without buffering: 80 ms

Size - 742,702 bytes :
With buffering: 180 ms
Without buffering: 741 ms 

.................................


อ่านต่อคลิกที่นี้


 JAVA : Reading and writing binary files  (2011-11-10)

Reading and writing binary files

เมื่อมีการอ่านและเขียน binary files ควรคำนึงถึง
- จะดีมากๆ ถ้าใช้ buffering (default buffer size is 8k)
- ควรจะ references to abstract base classes แทนการ references ไปถึง concrete classes
- อย่าลืมเรียก close method.

 ตัวอย่าง

Classes ที่มักจะใช้  เมื่อต้องการ อ่านและเขียน  binary files :

Input Output
FileInputStream FileOutputStream
BufferedInputStream BufferedOutputStream
ByteArrayInputStream ByteArrayOutputStream

 มีต่อครับ


อ่านต่อคลิกที่นี้


 Copy a file in Java  (2011-11-10)

Copy a file

การสำเนาไฟล์สามารถทำผ่าน FileChannels หรือ basic steams
แต่ดโดยปกติ Multichannel จะทำงานได้ไวกว่า แต่มักจะผิดพลาดมากกว่าถ้าไฟล์มีขนาดใหญ่มากๆ

ตัวอย่างการใช้งานของทั้งสองแบบ

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

/** 
Copy files, using two techniques, FileChannels and streams.
Using FileChannels is usually faster than using streams.
*/
public final class CopyFiles { /* Change these settings before running this class. */ /** The file to be copied. */ public static final String INPUT_FILE = "C:\\TEMP\\cottage.jpg"; /**
The name of the copy to be created by this class.
If this file doesn't exist, it will be created, along with any
needed parent directories.
*/
public static final String COPY_FILE_TO = "C:\\TEMP10\\cottage_2.jpg"; /** Run the example. */ public static void main(String... aArgs) throws IOException{ File source = new File(INPUT_FILE); File target = new File(COPY_FILE_TO); CopyFiles test = new CopyFiles(); test.copyWithChannels(source, target, false); //test.copyWithStreams(source, target, false);
log("Done."); } ........................

อ่านต่อคลิกที่นี้


 Reading and writing text files  (2011-11-10)

Reading and writing text files

When reading and writing text files :
  • it's almost always a good idea to use buffering (default size is 8K)
  • it's often possible to use references to abstract base classes, instead of references to specific concrete classes
  • there is always a need to pay attention to exceptions (in particular, IOException and FileNotFoundException)
The close method :
  • always needs to be called, or else resources will leak
  • will automatically flush the stream, if necessary
  • calling close on a "wrapper" stream will automatically call close on its underlying stream
  • closing a stream a second time has no consequence
  • when called on a Scanner, the close operation only works if the item passed to its constructor implements Closeable. Warning: if you pass a File to a Scanner, you will not be able to close it! Try using a FileReader instead.
Commonly used items : The FileReader and FileWriter classes are a bit tricky, since they implicitly use the system's default character encoding. If this default is not appropriate (for example, when reading an XML file which specifies its own encoding), the recommended alternatives are, for example :

FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader in = new InputStreamReader(fis, "UTF-8");

FileOutputStream fos = new FileOutputStream("test.txt");
OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");

Scanner scanner = new Scanner(file, "UTF-8");

มีต่อครับ.....


อ่านต่อคลิกที่นี้


 How to loop a Map in Java  (2011-11-09)

How to loop a Map in Java 

package com.xxx.common;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
public class LoopAMap{
 
   public static void main(String[] args) {
 
	//initial a Map
	Map<String,String> map = new HashMap<String,String>();
	map.put("1", "Jan");
	map.put("2", "Feb");
	map.put("3", "Mar");
	map.put("4", "Apr");
	map.put("5", "May");
	map.put("6", "Jun");
 
	//Map -> Set -> Iterator -> Map.Entry -> troublesome
        Iterator iterator=map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry mapEntry=(Map.Entry)iterator.next();
            System.out.println("The key is: "+mapEntry.getKey()
            		+ ",value is :"+mapEntry.getValue());
        }
 
        //more elegant way
        for (Map.Entry<String, String> entry : map.entrySet()) {
        	System.out.println("Key : " + entry.getKey() 
       			+ " Value : " + entry.getValue());
        }
 
        //weired way, but work anyway
        for (Object key: map.keySet()) {
        	System.out.println("Key : " + key.toString() 
       			+ " Value : " + map.get(key));
        }
 
   }
 
}

Ref : www.mkyong.com/java/how-to-loop-a-map-in-java/


อ่านต่อคลิกที่นี้


 Camel ActiveMQ route and unit test example  (2011-09-23)

ที่มา http://www.andrejkoelewijn.com/wp/2010/10/13/camel-activemq-route-and-unit-test-example/

เห็นว่าน่าจะมีประโยชน์มากๆ สำหรับการ เทสน Camel Active MQ ครับ

ตัวอย่างนี้เป็นการเทส Apache Camel and ActiveMQ จากตัวอย่าง Camel route จะล็อกทุกแมสเซสที่รับมาจาก EVENTS queue  นะครับ

1
2
3
4
5
6
7
import org.apache.camel.builder.RouteBuilder;
public class DispatcherRouteBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("activemq:queue:EVENTS").to("log:Events?showAll=true");
    }
 


๋Junit test จะทำการ start message broker และจะ start camel แล้วจะทำการส่ง message ไปยัง queue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.apache.activemq.broker.BrokerService;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.BeforeClass;
import org.junit.Test;
 
public class DispatcherRouteBuilderTest extends CamelTestSupport {
    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new DispatcherRouteBuilder();
    }
    @BeforeClass
    public static void setUpClass() throws Exception {
        BrokerService brokerSvc = new BrokerService();
        brokerSvc.setBrokerName("TestBroker");
        brokerSvc.addConnector("tcp://localhost:61616");
        brokerSvc.start();
    }
    @Test
    public void testConfigure() throws Exception {
        template.sendBody("activemq:queue:EVENTS", "HelloWorld!");
        Thread.sleep(3000);
    }
}

 dependencies ที่ใช้ใน Maven:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<dependencies>
  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-core</artifactId>
    <version>2.4.0-fuse-00-00</version>
  </dependency>
  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-test</artifactId>
    <version>2.4.0-fuse-00-00</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-jms</artifactId>
    <version>2.4.0-fuse-00-00</version>
  </dependency>
  <dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-camel</artifactId>
    <version>5.4.0-fuse-00-00</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-core</artifactId>
    <version>5.4.0-fuse-00-00</version>
    <scope>test</scope>
  </dependency>
</dependencies>


อ่านต่อคลิกที่นี้


 ตัวอย่างการใช้ CamelTestSupport ในการเทส Camel Route ว่าทำงานถูกต้องหรือไม่ แบบง่ายๆ  (2011-09-22)

ตัวอย่างการใช้  CamelTestSupport ในการเทส Camel แบบง่ายๆ

import org.apache.camel.ConsumerTemplate;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.CamelTestSupport;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Hashtable;
import java.util.Map;


public class TestCamel1 extends CamelTestSupport {
    private Logger log = LoggerFactory.getLogger(TestCamel1.class);

    @EndpointInject(uri = "mock:result")
    protected MockEndpoint resultEndpoint;

    @Produce(uri = "direct:start")
    protected ProducerTemplate producer;

    protected ConsumerTemplate consumer;

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                from("direct:start")
                    .bean(ChangeAge.class)
                    .to("mock:result");
            }
        };
    }

    @Test
    public void testDummy() throws Exception {
        Exchange exchange = createExchangeWithBody("Hello Camel");
        exchange.getIn().setHeaders(createHeader());
        resultEndpoint.expectedMessageCount(1);
        resultEndpoint.expectedHeaderReceived("NAME", "Pea");
        resultEndpoint.expectedHeaderReceived("AGE", "30");
        resultEndpoint.expectedBodiesReceived("Hello Camel. I Love You");
        producer.send(exchange);
        resultEndpoint.assertIsSatisfied();

    }
    private Map createHeader(){
            Map<String,String> header = new Hashtable<String,String>();
            header.put("NAME","Pea");
            header.put("AGE","25");
            return header;
    }


}

 

Bean Component

import org.apache.camel.Exchange;

public class ChangeAge {

    public void changeAge(Exchange exchange) {
        exchange.getIn().setHeader("AGE", "30");
        exchange.getIn().setBody("Hello Camel. I Love You");
    }
}

 ไม่ยากนะครับลองเอาไปใช้กันดู


อ่านต่อคลิกที่นี้


 Associate array to XML and JSON  (2011-09-20)

PHP Associate array data
 

$data = array(
    "hoge" => 123,
    "foo" => 456,
    "bar" => 789,
    "aaa" => array(
        "abc" => 111,
        "bcd" => 222,
        "cde" => 333
    ),
    "bbb" => array(
        "def" => array(
            "efg" => "hoge"
        )
    )
);



to XML

$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('root');

function write(XMLWriter $xml, $data){
    foreach($data as $key => $value){
        if(is_array($value)){
            $xml->startElement($key);
            write($xml, $value);
            $xml->endElement();
            continue;
        }
        $xml->writeElement($key, $value);
    }
}
write($xml, $data);

$xml->endElement();
echo $xml->outputMemory(true);



output XML

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <hoge>123</hoge>
<foo>456<
/foo> <bar>789</bar>
<aaa>
<abc>111<
/abc> <bcd>222</bcd>
<cde>333<
/cde> </aaa>
<bbb>
<def>
<efg>hoge<
/efg> </def>
<
/bbb> </root>



to JSON

echo json_encode($data);



output JSON

{
    "hoge":123,
    "foo":456,
    "bar":789,
    "aaa":{
        "abc":111,
        "bcd":222,
        "cde":333
    },
    "bbb":{
        "def":{
            "efg":"hoge"
        }
    }
}



Requires PHP5.2.x or xmlwriter extension, json extension


อ่านต่อคลิกที่นี้


 Camel : [Using Synchronization callbacks]  (2011-09-09)

Use Synchronization callbacks to execute any after-processing you want
done when the Exchange is complete. Don’t worry about throwing exceptions
from your custom Synchronization—Camel will catch those and log them at
WARN level, and will then continue to invoke the next callback. This ensures
that all callbacks are invoked even if one happens to fail.

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.spi.Synchronization;

public class TestTestTest {

    public static void main(String[] args) throws Exception {

        CamelContext context = new DefaultCamelContext();
        context.addRoutes(new RouteBuilder() {

            public void configure() {
                from("direct:start")
                        .process(new Processor() {
                            public void process(Exchange exchange) throws Exception {
                                exchange.getUnitOfWork()
                                        .addSynchronization(new FileRollback());
                            }
                        })
                        .bean(TestInteger.class).log("Finished.........................");
            }
        });

        context.start();

        ProducerTemplate producerTemplate = context.createProducerTemplate();
        Exchange exchange = new DefaultExchange(context);
        exchange.getIn().setHeader("MyInteger", "1");


        producerTemplate.asyncSend("direct:start", exchange);


        Thread.sleep(3000);
        context.stop();
    }

  static  class FileRollback implements Synchronization {
        public void onComplete(Exchange exchange) {
            System.out.println("onComplete!!!!!!!!!!!");
            //do something when complete
        }
        public void onFailure(Exchange exchange) {
            System.out.println("onFailure!!!!!!!!!!!");
            //do somethidn when on failure
        }
}
}

 

Output :

2011-09-09 12:20:01,088 [INFO ] [org.apache.camel.impl.DefaultCamelContext][start][1318] - Apache Camel 2.8.0 (CamelContext: camel-1) is starting
2011-09-09 12:20:01,091 [INFO ] [org.apache.camel.impl.DefaultCamelContext][createManagementStrategy][2301] - JMX enabled. Using ManagedManagementStrategy.
2011-09-09 12:20:01,316 [INFO ] [org.apache.camel.impl.converter.AnnotationTypeConverterLoader][load][118] - Found 3 packages with 14 @Converter classes to load
2011-09-09 12:20:01,344 [INFO ] [org.apache.camel.impl.converter.DefaultTypeConverter][loadCoreTypeConverters][394] - Loaded 153 core type converters (total 153 type converters)
2011-09-09 12:20:01,355 [INFO ] [org.apache.camel.impl.converter.AnnotationTypeConverterLoader][load][118] - Found 1 packages with 2 @Converter classes to load
2011-09-09 12:20:01,377 [INFO ] [org.apache.camel.impl.converter.DefaultTypeConverter][loadTypeConverters][420] - Loaded additional 3 type converters (total 156 type converters) in 0.030 seconds
2011-09-09 12:20:01,436 [INFO ] [org.mortbay.log][info][67] - Logging to org.slf4j.impl.Log4jLoggerAdapter(org.mortbay.log) via org.mortbay.log.Slf4jLog
2011-09-09 12:20:01,755 [INFO ] [org.apache.camel.impl.DefaultCamelContext][doStartOrResumeRouteConsumers][1906] - Route: route1 started and consuming from: Endpoint[direct://start]
2011-09-09 12:20:01,755 [INFO ] [org.apache.camel.impl.DefaultCamelContext][start][1335] - Total 1 routes, of which 1 is started.
2011-09-09 12:20:01,755 [INFO ] [org.apache.camel.impl.DefaultCamelContext][start][1336] - Apache Camel 2.8.0 (CamelContext: camel-1) started in 0.669 seconds
2011-09-09 12:20:01,792 [INFO ] [route1][log][196] - Finished.........................
onComplete!!!!!!!!!!!
2011-09-09 12:20:04,777 [INFO ] [org.apache.camel.impl.DefaultCamelContext][doStop][1463] - Apache Camel 2.8.0 (CamelContext:camel-1) is shutting down
2011-09-09 12:20:04,778 [INFO ] [org.apache.camel.impl.DefaultShutdownStrategy][doShutdown][120] - Starting to graceful shutdown 1 routes (timeout 300 seconds)
2011-09-09 12:20:04,783 [INFO ] [org.apache.camel.impl.DefaultShutdownStrategy][run][460] - Route: route1 shutdown complete, was consuming from: Endpoint[direct://start]
2011-09-09 12:20:04,783 [INFO ] [org.apache.camel.impl.DefaultShutdownStrategy][doShutdown][158] - Graceful shutdown of 1 routes completed in 0 seconds
2011-09-09 12:20:04,786 [INFO ] [org.apache.camel.impl.DefaultInflightRepository][doStop][89] - Shutting down with no inflight exchanges.
2011-09-09 12:20:04,790 [INFO ] [org.apache.camel.impl.DefaultCamelContext][doStop][1519] - Uptime: 3.703 seconds
2011-09-09 12:20:04,790 [INFO ] [org.apache.camel.impl.DefaultCamelContext][doStop][1520] - Apache Camel 2.8.0 (CamelContext: camel-1) is shutdown in 0.012 seconds
 

 หากแก้ไข Code ส่ง Header ผิดไป ดังข้างล่าง

.....

exchange.getIn().setHeader("MyInteger", "xxx");

.....

 

จะได้ผลลัพธ์ดังข้างล่างนี้ครับ

/usr/lib/jvm/java-6-sun/bin/java -Didea.launcher.port=7538 -Didea.launcher.bin.path=/home/chiwa

    ........
  
onFailure!!!!!!!!!!!
2011-09-09 12:28:44,135 [INFO ] [org.apache.camel.impl.DefaultCamelContext][doStop][1463] - Apache Camel 2.8.0 (CamelContext:camel-1) is shutting down
2011-09-09 12:28:44,136 [INFO ] [org.apache.camel.impl.DefaultShutdownStrategy][doShutdown][120] - Starting to graceful shutdown 1 routes (timeout 300 seconds)
2011-09-09 12:28:44,141 [INFO ] [org.apache.camel.impl.DefaultShutdownStrategy][run][460] - Route: route1 shutdown complete, was consuming from: Endpoint[direct://start]
2011-09-09 12:28:44,141 [INFO ] [org.apache.camel.impl.DefaultShutdownStrategy][doShutdown][158] - Graceful shutdown of 1 routes completed in 0 seconds
2011-09-09 12:28:44,144 [INFO ] [org.apache.camel.impl.DefaultInflightRepository][doStop][89] - Shutting down with no inflight exchanges.
2011-09-09 12:28:44,147 [INFO ] [org.apache.camel.impl.DefaultCamelContext][doStop][1519] - Uptime: 3.687 seconds
2011-09-09 12:28:44,148 [INFO ] [org.apache.camel.impl.DefaultCamelContext][doStop][1520] - Apache Camel 2.8.0 (CamelContext: camel-1) is shutdown in 0.012 seconds

 


อ่านต่อคลิกที่นี้


 Base64 Utility  (2011-09-06)

การ Converst binary to base64 and base 64 to binary

 

public class Base64Utility {

    private static final Logger log = LoggerFactory.getLogger(Base64Utility.class);

    private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();

    private static int[] toInt = new int[128];

    static {
        for (int i = 0; i < ALPHABET.length; i++) {
            toInt[ALPHABET[i]] = i;
        }
    }

    /**
     * Translates the specified byte array into Base64 string.
     *
     * @param file the file to encode (not null)
     * @return the translated Base64 string (not null)
     */
    public static String fileToBase64(File file) throws IOException {

        byte[] buf = getBinaryData(file);

        int size = buf.length;
        char[] ar = new char[((size + 2) / 3) * 4];
        int a = 0;
        int i = 0;
        while (i < size) {
            byte b0 = buf[i++];
            byte b1 = (i < size) ? buf[i++] : 0;
            byte b2 = (i < size) ? buf[i++] : 0;

            int mask = 0x3F;
            ar[a++] = ALPHABET[(b0 >> 2) & mask];
            ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
            ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
            ar[a++] = ALPHABET[b2 & mask];
        }
        switch (size % 3) {
            case 1:
            case 2:
                ar[--a] = '=';
                break;
        }
        return new String(ar);
    }

    /**
     * Translates the specified Base64 string into a byte array.
     *
     * @param str the Base64 string (not null)
     * @return the byte array (not null)
     */
    public static byte[] decode(String str) {
        int delta = str.endsWith("==") ? 2 : str.endsWith("=") ? 1 : 0;
        byte[] buffer = new byte[str.length() * 3 / 4 - delta];
        int mask = 0xFF;
        int index = 0;
        for (int i = 0; i < str.length(); i += 4) {
            int c0 = toInt[str.charAt(i)];
            int c1 = toInt[str.charAt(i + 1)];
            buffer[index++] = (byte) (((c0 << 2) | (c1 >> 4)) & mask);
            if (index >= buffer.length) {
                return buffer;
            }
            int c2 = toInt[str.charAt(i + 2)];
            buffer[index++] = (byte) (((c1 << 4) | (c2 >> 2)) & mask);
            if (index >= buffer.length) {
                return buffer;
            }
            int c3 = toInt[str.charAt(i + 3)];
            buffer[index++] = (byte) (((c2 << 6) | c3) & mask);
        }
        return buffer;
    }


    public static byte[] getBinaryData(File file)  {
        byte[] b = new byte[(int) file.length()];
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            fis.read(b);
        } catch (IOException e) {
               if (fis != null)  {
                     try {
                    fis.close();
                } catch (IOException e1) {
                   log.error("can not close FileOutputStream.");
                }
               }


        }

        return b;
    }

    public static File byteArrayToFile(byte[] bytes, String fileFullPath) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileFullPath);
            fos.write(bytes);
            fos.close();
        } catch (Exception e) {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                   log.error("can not close FileOutputStream.");
                }
            }
        }

        return new File(fileFullPath);
    }

    public static File base64ToFile(String str, String fileFullPath) throws IOException {
        return  byteArrayToFile(decode(str), fileFullPath);
    }

}

 



อ่านต่อคลิกที่นี้


 การใช้ Future Framework ร่วมกัน Apache Camel เพื่อรอรับ Exchange จาก Endpoint สุดท้าย  (2011-09-06)

บางครั้งเราต้องการทำงานกับ Camel มีการส่ง Message ไปยัง Endpoint ต่างๆ ตาม Route ที่เราสร้างขึ้น
และต้องการรอรับ Message จาก Enpoint สุดท้ายจาก Route เพื่อติดตามการทำงานของเราว่าสำเร็จลุล่วงหรือไม่
โดยใช้วิธีการส่งแบบ Asyncronize ดูได้จากตัวอย่างข้างล่างครับ ง่ายจริงๆ ผมรัก Camel ที่สุดในโลก

package com.zencode.camel;


import com.abctech.transition.webapp.camel.CamelBeanHelper;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultExchange;

import java.util.concurrent.Future;

public class TestFuture {
    public static void main(String[] args) throws Exception {
        CamelContext context = new DefaultCamelContext();
        context.addRoutes(new RouteBuilder() {

            public void configure() {
                from("direct:start").bean(TestFutureBean.class).bean(TestFutureBean2.class).log("Finished.........................");
            }
        });

        context.start();

        ProducerTemplate producerTemplate = context.createProducerTemplate();
        Exchange exchange = new DefaultExchange(context);
        exchange.getIn().setHeader("MyName", "pea");
        exchange.getIn().setBody("Hello Pea");
        CamelBeanHelper.dumpCamelHeaders(exchange);

        Future<Exchange> future = producerTemplate.asyncSend("direct:start", exchange);

        Exchange exchange2 = future.get();

        CamelBeanHelper.dumpCamelHeaders(exchange2);
        System.out.println(">>>>>>> "+ exchange2.getIn().getBody().toString() + "   " + exchange2.getIn().getHeader("myHeader").toString() + " " + exchange2.getIn().getHeader("myHeader2").toString());
        Thread.sleep(3000);
        context.stop();
    }
}

 

 Bean Enpoint

public class TestFutureBean {

    public void handleMessage(Exchange received) {
        received.getIn().setHeader("myHeader", "111");
        String body = received.getIn().getBody().toString() + ", 111";
        received.getIn().setBody(body);
    }
}
====================================================================== public class TestFutureBean2 {
public void handleMessage(Exchange received) {
received.getIn().setHeader("myHeader2", "222");
String body = received.getIn().getBody().toString() + ", 222";
received.getIn().setBody(body);
}
}

ผลลัพธ์

>>>>>>> Hello Pea, 111, 222   111 222


 


อ่านต่อคลิกที่นี้


 Java Concurrency / Multithreading - Tutorial  (2011-07-12)

มีบทความดีๆ มาฝากครับ Ref : http://www.vogella.de/articles/JavaConcurrency/article.html

Android Threads, Handlers AsyncTask

This tutorial describes the usage of Threads, Handlers and AsynTask in your application. It also covers how to handle the application lifecycle together with threads. It also describes Traceview to trace an application for performance problems. It is based on Eclipse 3.7, Java 1.6 and Android 2.3.3 (Gingerbread).


อ่านต่อคลิกที่นี้


 Unzipping a file from InputStream and returning another InputStream in Java  (2011-06-14)

ตัวอย่างนี้เป็นการอ่านไฟล์เป็น FileInputStream แล้วแปลงเป็น ZipInputStream แล้ว unzip Entry ใน zip file ออกมา

import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


public class Main {
   
public static void main(String[] args) throws Exception
   
{
       
FileInputStream fis = new FileInputStream("c:/zeng.zip");
       
ZipInputStream zis = new ZipInputStream(fis);
       
ZipEntry entry;
           
// while there are entries I process them
       
while ((entry = zis.getNextEntry()) != null)
       
{
           
System.out.println("entry: " + entry.getName() + ", " + entry.getSize());
                   
// consume all the data from this entry
           
while (zis.available() > 0)
                zis
.read();
                   
// I could close the entry, but getNextEntry does it automatically
                   
// zis.closeEntry()
       
}
   
}
}

 ไม่ยากเลยโค้ดไม่มีอะไรซับซ้อนเลยนะครับ ขอให้สนุกกับจาวานะครับ


อ่านต่อคลิกที่นี้


 How do I convert InputStream to String?  (2011-06-09)

ตัวอย่างแบบง่ายๆ นะครับ

       URL url = new URL("http://www.google.com");
       InputStream is = url.openStream();
       Writer writer = new StringWriter();

                   char[] buffer = new char[1024];
                   try {
                       Reader reader = new BufferedReader(
                               new InputStreamReader(is, "UTF-8"));
                       int n;
                       while ((n = reader.read(buffer)) != -1) {
                           writer.write(buffer, 0, n);
                       }
                   } finally {
                       is.close();
                   }

        log.debug(writer.toString());

 ไม่ยากนะครับลองเอาไปใช้กันดู


 


อ่านต่อคลิกที่นี้


 วิธี Embbed Jetty Server ให้ run website ใน application ของเรา  (2011-05-20)

วิธี Embbed Jetty Server  ให้ run website ใน application ของเรา
ซึ่งเอาจะเอาไว้ใช้ในการเทส หรือทำ Editor ให้สามารถรัน Embbed Web Server เหมือน Eclipse หรือ NetBean
และผมว่าก็สามารถเอาไปประยุกต์ใช้งานได้มากมายเลยนะครับ ลองเอาไปประยุกต์ใช้กันดูนะครับ โอ๊ยๆๆๆๆๆๆๆๆ ผมรัก JAVA

.......
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.webapp.WebAppContext;


public class MyJettyTest {
    private Log log = LogFactory.getLog(MyJettyTest.class);

        private Server server;

        @Before
        public void setUp() throws Exception {

         server = new Server();
         SocketConnector connector = new SocketConnector();
         connector.setPort(8089); //ระบุ port ที่ต้องการ
         server.setConnectors(new Connector[] { connector });
         WebAppContext context = new WebAppContext();
         context.setServer(server);
         context.setContextPath("/zeng");
         context.setWar("xxxxxx/webapp/zeng.war"); //ตัวนี้ คือ webapp ที่เราพัฒนาและต้องการ deploy นะครับ
         server.addHandler(context);
         server.start();

        }

   @After
   public void tearDown() throws Exception {
            server.stop();
   }

     @Test
    public void testPresenceOfIndexPage() throws Exception {
         URL url = new URL("http://localhost:8089/zeng/");
         URLConnection yc = url.openConnection();
         BufferedReader in = new BufferedReader(
                                 new InputStreamReader(
                                 yc.getInputStream()));
         String inputLine;
         while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine); //ตรงนี้ก็จะ loop content ที่ webapp response กลับมานะครับ
         in.close();
    }


}

 


 


อ่านต่อคลิกที่นี้


 How to start/stop Camel Router at Runtime.  (2011-05-09)

ตามตัวอย่างเลยครับ

public class StartStopRouteTest {

    @Test
    public void testPass() throws Exception {
        CamelContext context = new DefaultCamelContext();
         context.addRoutes(new RouteBuilder() {
          public void configure() {
                 from("direct:start").noAutoStartup().routeId("route1").log(">>> I GOD THE MESSAGE.");
            }
         });

       context.start();
       context.startRoute("route1");   //because of this
       ProducerTemplate producerTemplate = context.createProducerTemplate();
        producerTemplate.sendBody("direct:start" , "Hello");
    }

    @Test
    public void testFail() throws Exception {
        CamelContext context = new DefaultCamelContext();
         context.addRoutes(new RouteBuilder() {
          public void configure() {
                 from("direct:start").noAutoStartup().routeId("route1").log(">>> I GOD THE MESSAGE.");
            }
         });

       context.start();
       //context.startRoute("route1");      //because of this
       ProducerTemplate producerTemplate = context.createProducerTemplate();
       producerTemplate.sendBody("direct:start" , "Hello");
    }
}
 

 noAutoStartup() = ไม่ให้ Router นี้  Start อัตโนมัติ
 routeId("route1") = ระบุชื่อให้กับ Router เพื่อจะไ้ด้ควบคุมมันได้
จากนั้นก็ควบคุมมันผ่าน CamelContext เช่น startRoute(routeId), stopRoute(routeId) เป็นต้น

ไม่ยากนะครับลองเอาไปใช้กันดู


 


อ่านต่อคลิกที่นี้


 Apache CAMEL Dynamic Recipient List  (2011-04-26)

Usually one of the main reasons for using the Recipient List pattern is that the list of recipients is dynamic and calculated at runtime. The following example demonstrates how to create a dynamic recipient list using an Expression (which in this case it extracts a named header value dynamically) to calculate the list of endpoints which are either of type Endpoint or are converted to a String and then resolved using the endpoint URIs.

ตัวอย่างนี้เป็นการใช้  CamelTestSupport

public class RecipientListTest extends CamelTestSupport {
    private Logger log = LoggerFactory.getLogger(RecipientListTest.class);

    @EndpointInject(uri = "mock:result")
    protected MockEndpoint resultEndpoint;

    @Produce(uri = "direct:start")
    protected ProducerTemplate template;

    @Produce(uri = "direct:start2")
    protected ProducerTemplate template2;

    protected ConsumerTemplate consumerTemplate;

    @EndpointInject(uri = "mock:result2")
    protected MockEndpoint resultEndpoint2;

    @EndpointInject(uri = "mock:result3")
    protected MockEndpoint resultEndpoint3;

    @EndpointInject(uri = "mock:result4")
    protected MockEndpoint resultEndpoint4;

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
                from("direct:start2").log("=====>>>>>>>  send ${body} ").recipientList(simple("mock:result2, mock:result3, mock:result4")).parallelProcessing();


            }
        };
    }

    public void testMulticast() throws InterruptedException {
        resultEndpoint2.expectedBodiesReceived("testMulticast");
        resultEndpoint3.expectedBodiesReceived("testMulticast");
        resultEndpoint4.expectedBodiesReceived("testMulticast");
        template2.sendBody("testMulticast");
        resultEndpoint2.assertIsSatisfied();
        resultEndpoint3.assertIsSatisfied();
        resultEndpoint4.assertIsSatisfied();
    }

}

 ไม่ยากนะครับลองเอาไปใช้กันดู มีประโยชน์ในการทำ Multicast ไปยัง enpoint หลายๆ ตัว

Tip อีกนิดใน RouteBuilder สามารถกำหนด DSL เป็น from("direct:start2").multicast().to("mock:b", "mock:c", "mock:d"); ก็ได้นะครับ


 


อ่านต่อคลิกที่นี้


web hit counter

This page took 0.013350 seconds to load.