ccwihr.client.t1.HttpUploadClient.java Source code

Java tutorial

Introduction

Here is the source code for ccwihr.client.t1.HttpUploadClient.java

Source

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package ccwihr.client.t1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.QueryStringEncoder;
import io.netty.handler.codec.http.cookie.ClientCookieEncoder;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
//import io.netty.handler.codec.http.multipart.DiskAttribute;
//import io.netty.handler.codec.http.multipart.DiskFileUpload;
import io.netty.handler.codec.http.multipart.HttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

import java.beans.PropertyVetoException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;

import java.sql.*;
//import javax.naming.*;
import javax.net.ssl.SSLException;
//import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import ccwihr.client.biz.SyncEntity;
//import com.mchange.v2.c3p0.DataSources;

/**
 * This class is meant to be run against {@link HttpUploadServer}.
 */
public final class HttpUploadClient extends TimerTask {

    // web?URL
    static final String BASE_URL = System.getProperty("baseUrl", "http://127.0.0.1:8080/");
    static final String uploadURL = "ccwihr_server/get/update/timerecordsdata";
    // static String postSimple;
    static String GET_URL;

    //
    String scheme;
    String host;
    int port;
    // URI
    URI uriSimple = null;

    // Configure the client.
    static EventLoopGroup group = new NioEventLoopGroup();

    // setup the factory: here using a mixed memory/disk based on size
    // threshold
    static HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk
    // if
    // MINSIZE
    // exceed
    // SSL
    static SslContext sslCtx;
    //
    Bootstrap b = new Bootstrap();

    /**
     * ?
     */
    // 
    static ComboPooledDataSource cpds = new ComboPooledDataSource();
    String jdbcDriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    String connectionUrl = "jdbc:sqlserver://192.168.199.143\\inst1:1433;databaseName=SongMeiV8;user=sa;password=1qaz@WSX";

    SyncEntity se1, se2, se3, se4, se5;

    /**
     * ?
     */
    {

        /**
         * 
         */
        // ?

        try {
            cpds.setDriverClass(jdbcDriverName);
            // cpds.setDriverClass( "net.sourceforge.jtds.jdbc.Driver" );
        } catch (PropertyVetoException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // String connectionUrl =
        // "jdbc:jtds:sqlserver://192.168.199.146:1433;databaseName=inst1;user=sa;password=1qaz@WSX";
        cpds.setJdbcUrl(connectionUrl);
        cpds.setUser("sa");
        cpds.setPassword("1qaz@WSX");
        // ??c3p0????
        cpds.setMinPoolSize(2);
        cpds.setAcquireIncrement(2);
        cpds.setMaxPoolSize(6);

        // /**
        // *
        // =====================================================================
        // * =============================================== ?
        // */
        // // Declare the JDBC objects.
        // Connection con = null;
        // Statement stmt = null;
        // ResultSet rs = null;
        //
        // try {
        // // Establish the connection.
        // Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        // // Class.forName("net.sourceforge.jtds.jdbc.Driver");
        // con = DriverManager.getConnection(connectionUrl);
        //
        // // Create and execute an SQL statement that returns some data.
        // String SQL = "SELECT TOP 10 * FROM Person.Contact";
        // stmt = con.createStatement();
        // rs = stmt.executeQuery(SQL);
        //
        // // Iterate through the data in the result set and display it.
        // while (rs.next()) {
        // System.out.println(rs.getString(4) + " " + rs.getString(6));
        // }
        // }
        //
        // // Handle any errors that may have occurred.
        // catch (Exception e) {
        // e.printStackTrace();
        // } finally {
        // if (rs != null)
        // try {
        // rs.close();
        // } catch (Exception e) {
        // }
        // if (stmt != null)
        // try {
        // stmt.close();
        // } catch (Exception e) {
        // }
        // if (con != null)
        // try {
        // con.close();
        // } catch (Exception e) {
        // }
        // }
        // /**
        // *
        // =====================================================================
        // */

        /**
         * =========================== HTTP  =====================
         */
        if (true) {

            // URL?
            if (BASE_URL.endsWith("/")) {
                // postSimple = BASE_URL + "hello/foo";
                GET_URL = BASE_URL + uploadURL;
            } else {
                // postSimple = BASE_URL + "/hello/foo";
                GET_URL = BASE_URL + "/" + uploadURL;
            }

            // URI?
            try {
                uriSimple = new URI(GET_URL);
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // ??https
            scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme();
            host = uriSimple.getHost() == null ? "127.0.0.1" : uriSimple.getHost();
            port = uriSimple.getPort();
            if (port == -1) {
                if ("http".equalsIgnoreCase(scheme)) {
                    port = 80;
                } else if ("https".equalsIgnoreCase(scheme)) {
                    port = 443;
                }
            }

            if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
                System.err.println("Only HTTP(S) is supported.");
                // return;
            }

            // ?httpsssl
            final boolean ssl = "https".equalsIgnoreCase(scheme);
            if (ssl) {
                try {
                    sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                            .build();
                } catch (SSLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                sslCtx = null;
            }

            b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientIntializer(sslCtx));
            /**
             * =========================== HTTP ? =====================
             */
        }

        /**
         * =========================== ? =====================
         */
        se1 = new SyncEntity("select * from ", ""); // 
        se2 = new SyncEntity("", ""); // 
        se3 = new SyncEntity("", ""); // 
        se4 = new SyncEntity("", ""); // 
        se5 = new SyncEntity("", ""); // 

    }

    /**
     * 
     */
    @Override
    public void run() {
        System.out.println("Task Running...");
        /**
         * ??
         */
        Connection conn;
        try {
            conn = cpds.getConnection();
            SyncEntity se = new SyncEntity("", "");
            /**
             * 
             */
            se1.getMore(conn, "");
            Statement state = conn.createStatement();
            ResultSet rs = state.executeQuery("select * from Departs");
            while (rs.next()) {

            }

            /**
             * ?
             */
            // rs.isFirst();
            // rs.first();
            System.out.println("got data.");

            // rs.close();
            // state.close();
            // //?,
            // conn.close();

            /**
             * ????get? 
             */
            // Simple Get form: no factory used (not usable)
            List<Entry<String, String>> headers = null;
            try {
                //            headers = formget(b, host, port, GET_URL, uriSimple);

                HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed

                List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, se1, factory, headers);

                if (bodylist == null) {
                    factory.cleanAllHttpData();
                    return;
                }
                //            headers = formpost(b, host, port, GET_URL, uriSimple);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (headers == null) {
                factory.cleanAllHttpData();
                return;
            }
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        HttpUploadClient huc = new HttpUploadClient();
        try {
            Timer timer = new Timer();
            long delay2 = 5 * 1000;
            long period2 = 2000;
            //  2 ?? 5  job2
            timer.schedule(huc, delay2, period2);

        } finally {
        }
    }

    /**
     * Standard usage of HTTP API in Netty without file Upload (get is not able
     * to achieve File upload due to limitation on request size).
     *
     * @return the list of headers that will be used in every example after
     **/
    private static List<Entry<String, String>> formget(Bootstrap bootstrap, String host, int port, String get,
            URI uriSimple) throws Exception {
        // XXX /formget
        // No use of HttpPostRequestEncoder since not a POST
        Channel channel = bootstrap.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        QueryStringEncoder encoder = new QueryStringEncoder(get);
        // add Form attribute
        encoder.addParam("getform", "GET");
        encoder.addParam("info", "first value");
        encoder.addParam("secondinfo", "secondvalue &");
        // not the big one since it is not compatible with GET size
        // encoder.addParam("thirdinfo", textArea);
        encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
        encoder.addParam("Send", "Send");

        URI uriGet = new URI(encoder.toString());
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
        HttpHeaders headers = request.headers();
        headers.set(HttpHeaderNames.HOST, host);
        headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);

        headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
        headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
        headers.set(HttpHeaderNames.REFERER, uriSimple.toString());
        headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side");
        headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        // connection will not close but needed
        // headers.set("Connection","keep-alive");
        // headers.set("Keep-Alive","300");

        headers.set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(new DefaultCookie("my-cookie", "foo"),
                new DefaultCookie("another-cookie", "bar")));

        // send request
        channel.writeAndFlush(request);

        // Wait for the server to close the connection.
        channel.closeFuture().sync();

        // convert headers to list
        return headers.entries();
    }

    /**
     * Standard post without multipart but already support on Factory (memory
     * management)
     * @param se12 
     *
     * @return the list of HttpData object (attribute and file) to be reused on
     *         next post
     */
    private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple,
            SyncEntity se12, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception {
        // XXX /formpost
        // Start the connection attempt.
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        // Wait until the connection attempt succeeds or fails.
        Channel channel = future.sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                uriSimple.toASCIIString());

        // Use the PostBody encoder
        HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false

        // it is legal to add directly header or cookie into the request until
        // finalize
        for (Entry<String, String> entry : headers) {
            request.headers().set(entry.getKey(), entry.getValue());
        }

        // add Form attribute
        bodyRequestEncoder.addBodyAttribute("getform", "POST");
        bodyRequestEncoder.addBodyAttribute("info", "first value");
        bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &");
        bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
        bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
        // bodyRequestEncoder.addBodyFileUpload("myfile", file,
        // "application/x-zip-compressed", false);

        // finalize request
        request = bodyRequestEncoder.finalizeRequest();

        // Create the bodylist to be reused on the last version with Multipart
        // support
        List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

        // send request
        channel.write(request);

        // test if request was chunked and if so, finish the write
        if (bodyRequestEncoder.isChunked()) { // could do either
            // request.isChunked()
            // either do it through ChunkedWriteHandler
            channel.write(bodyRequestEncoder);
        }
        channel.flush();

        // Do not clear here since we will reuse the InterfaceHttpData on the
        // next request
        // for the example (limit action on client side). Take this as a
        // broadcast of the same
        // request on both Post actions.
        //
        // On standard program, it is clearly recommended to clean all files
        // after each request
        // bodyRequestEncoder.cleanFiles();

        // Wait for the server to close the connection.
        channel.closeFuture().sync();
        return bodylist;
    }

    // use to simulate a small TEXTAREA field in a form
    private static final String textArea = "short text";
    // use to simulate a big TEXTAREA field in a form
    private static final String textAreaLong = "lkjlkjlKJLKJLKJLKJLJlkj lklkj\r\n\r\nLKJJJJJJJJKKKKKKKKKKKKKKK &\r\n\r\n";

}