Dec 27 2019

Create a HTTP Server in Java

Here is a quick tutorial on how to create a local embedded HTTP server in Java to serve JSON data. The whole code in less than 30 lines on Java.

package com.juixe.json.server;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;

public class JSONServer implements HttpHandler {

    public static void main(String[] args) throws IOException  {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/data", new JSONServer());
        server.setExecutor(null);
        server.start();
    }

    @Override
    public void handle(HttpExchange he) throws IOException {
        String response = "{\"message\": \"Hello, HTTP Client\"}";

        he.getResponseHeaders().set("Content-Type", "application/json;charset=UTF-8");
        he.sendResponseHeaders(200, response.length());
        he.getResponseBody().write(response.getBytes());
        he.close();
    }
}

The HttpServer and HttpHandler classes are part of the JRE, so no additional libraries are required. Java also includes a HttpsServer which supports SSL. In the HttpHandler, you can return any data but for this example we are returning a simple JSON response.


Feb 1 2011

Copy Data Between Two Database Tables

There are many situations when you need to copy data from one database table to another one. You may want to migrate data from one database table to a new table, sometimes you need to do so to copy data to a backup table, other times to bulk load data from from different databases. To copy date between tables in a SQL Server database you can execute the following.

INSERT INTO Note (Id, Name)
SELECT Id, Name FROM Notes
WHERE name IS NOT NULL

The above state will copy date from a database table Notes to a new table Note where some condition is meet.

A typical database server instance hosts multiple databases, such as production and several test databases. You can copy data not only between tables within a database, but between databases within a database server instance. To copy between databases you need to use the fully qualified database name. For example, the following SQL snippet copies data from a tables called Notes in a database called TestDB.

INSERT INTO Note (Id, Name)
SELECT Id, Name FROM TestDB.dbo.Notes
WHERE name IS NOT NULL