provisioningserver.java.svn-base

来自「cqME :java framework for TCK test.」· SVN-BASE 代码 · 共 257 行

SVN-BASE
257
字号
/* * $Id$ * * Copyright 1996-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. * */package com.sun.cldc.communication.midp;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.PrintWriter;import java.net.InetAddress;import java.net.URL;import java.net.UnknownHostException;import java.util.Date;import java.util.ResourceBundle;/** * Simple OTA Provisioning sever. */public class ProvisioningServer extends BaseServer {        public static void main(String[] args) {        ProvisioningServer server = new ProvisioningServer();        server.init(args);        server.start();    }        private String serverRoot;    private String extraURI;    private ContentTypeHandler ctHandler;    private static final String SERVER_ROOT = "server.root=";    private static final String EXTRA_CONTENT_TYPES = "extraContentTypes=";    public ProvisioningServer() {        port = 80;        serverRoot = new File(".").getAbsolutePath();        extraURI = "getNextApp.jad";        done = true;        ctHandler = new ContentTypeHandler();        ctHandler.registerExtension("html","text/html");        ctHandler.registerExtension("htm","text/html");        ctHandler.registerExtension("jad","text/vnd.sun.j2me.app-descriptor");        ctHandler.registerExtension("jar","application/java-archive");        try {            host = InetAddress.getLocalHost().getHostName();        } catch (UnknownHostException uhe) {            host = "localhost";        }    }        /**     * Initialize the server with necessary parameters.     * "test.root=bar"     * "http.port=42"     */    public void init(String[] arg) {        String [] strArgs = null;        for (int i = 0; arg != null && i < arg.length; i++) {            if (arg[i].startsWith(SERVER_ROOT)                     && arg[i].length() > SERVER_ROOT.length()) {                serverRoot = arg[i].substring(SERVER_ROOT.length());                continue;            } else if (arg[i].startsWith(EXTRA_CONTENT_TYPES)) {                 if (arg[i].length() > EXTRA_CONTENT_TYPES.length()) {                    try {                        ctHandler.registerExtensions(                                arg[i].substring(EXTRA_CONTENT_TYPES.length()));                    } catch (IllegalArgumentException e) {                        throw new IllegalArgumentException(                                i18n.getString("error.invalidContentTypes")                                + e.getMessage());                    }                }            } else {                super.processArg(arg[i]);            }        }        handlerCount = 1;        runners = new RequestHandler[handlerCount];        for (int i = 0; i < handlerCount; i++) {            runners[i] = new RequestHandler();            runners[i].setName("OTARequestHandler_"+i);            ((BaseHttpServer) runners[i]).setParams(verbose, host, port, retry);        }    }    class RequestHandler extends BaseHttpServer {        protected void handleHead(URL request) throws IOException {            String path = request.getFile();                        handleFileRequest(HEAD, path);        }        protected void handleGet(URL request, DataInputStream in)                 throws IOException {            String path = request.getFile();            handleFileRequest(GET, path);        }        /**         * Handles <code>GET</code> and <code>HEAD</code> requests for files.         *         * @param path         *                Path to the file, relative to the server root.         * @throws IOException         *                 if I/O error occurs.         */        private void handleFileRequest(String httpMethod, String path)                throws IOException {            assert (GET.equals(httpMethod) || HEAD.equals(httpMethod)) :                "invalid HTTP method: " + httpMethod;            File file = new File(serverRoot, path);            if (file.isFile() && file.canRead()) {                try {                    byte[] buf = getFileContent(file);                    setResponseProperty("Content-Length", "" + buf.length);                    setResponseProperty("Content-Type",                            ctHandler.getContentType(file));                    sendDiagnostics(HTTP_OK);                    if (GET.equals(httpMethod)) {                        flushRawBuffer(buf);                    }                } catch (IOException ioe) {                    verboseln("ProvisioningServer: " + "path=" + path                            + ", httpMethod=" + httpMethod);                    verboseln("ProvisioningServer: Error while processing "                            + "file request: " + ioe.getMessage());                    sendDiagnostics(HTTP_SERVER_ERROR);                }            } else if (file.isDirectory()) {                sendDirectoryIndex(file, path);            } else {                sendDiagnostics(HTTP_NOT_FOUND);            }        }                protected byte[] getFileContent(File file) throws IOException {            FileInputStream fis = new FileInputStream(file);            DataInputStream fin = new DataInputStream(fis);            byte[] buf = new byte[(int) file.length()];            try {                fin.readFully(buf);            } finally {                fin.close();            }            return buf;        }        protected void sendDirectoryIndex(File dir, String path)                throws IOException {            try {                ByteArrayOutputStream baos = new ByteArrayOutputStream();                PrintWriter pw = new PrintWriter(baos);                pw.println("<html><head><title>" + path + "</title>");                pw.println("<style type=\"text/css\">");                pw.println("img { border: 0; padding: 0 2px; vertical-align:"                        + " text-bottom; }");                pw.println("td  { font-family: monospace; padding: 2px 3px;"                        + " text-align: right; vertical-align: bottom;"                        + " white-space: pre; }");                pw.println(" td:first-child { text-align: left; padding: "                        + "2px 10px 2px 3px; }");                pw.println("table { border: 0; }");                pw.println("a.symlink { font-style: italic; }");                pw.println("</style></head><body>");                pw.println("<h1>Index of " + path + "</h1>");                pw.println("<hr/>");                pw.println("<table>");                File[] files = dir.listFiles();                for (int i = 0; i < files.length; i++) {                    String link = new File(path,files[i].getName()).getPath()                            .replace(File.separatorChar, '/');                    pw.println("<tr>");                    pw.print("<td><a href=\"" + link + "\">");                    pw.println("<img src=\""                             + (files[i].isDirectory() ? DIR_ICON : FILE_ICON)                            + "\" alt=\""                            + (files[i].isDirectory() ? "Directory: " : "File: ")                            + "\"/>" + files[i].getName() + "</a></td>");                    pw.println("<td>" +                             (files[i].isFile()                                 ? (files[i].length() / 1024) + " KB"                                : "") + "</td>");                    pw.println("<td>"                             + new Date(files[i].lastModified()).toString()                            + "</td>");                    pw.println("</tr>");                }                pw.println("</table>");                pw.println("</html>");                pw.flush();                pw.close();                baos.close();                setResponseProperty("Content-Length", "" + baos.size());                setResponseProperty("Content-Type", "text/html");                flushRawBuffer(baos.toByteArray());            } catch (IOException e) {                verboseln("ProvisioningServer: " + "path=" + path);                verboseln("ProvisioningServer: Error while processing "                        + "media file request: " + e.getMessage());                sendDiagnostics(HTTP_SERVER_ERROR);            }        }                protected void handlePost(URL request, DataInputStream in)                 throws IOException {            sendDiagnostics(HTTP_NOT_FOUND);        }        protected boolean isDone() {            return ProvisioningServer.this.isDone();        }    }    private static final ResourceBundle i18n =         ResourceBundle.getBundle("com.sun.cldc.communication.midp.i18n");        private static final String DIR_ICON =             "resource://gre/res/html/gopher-menu.gif";        private static final String FILE_ICON =            "resource://gre/res/html/gopher-unknown.gif";}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?