Question about writing a web server

I was asked to write a simple Web server that responds to HTTP requests received on port 808
It has the following features:
1.a request for an HTML document or image file should generate a response with the appropriate MIME type
2.a request for a directory name with a trailing / should return the contents of the index.html file in that directory (if it exists) or else a suitably formatted HTML listing of the directory contents, including information about each file
3.a request for a directory name without a trailing / should generate an appropriate Redirect response
4.a request for a non-existent file or directory should generate an appropriate error response
5/the Web server should be multi-threaded so that it can cope with multiple
how to do it?
may anyone help me please?

As a startert for ten, try this that I had lying around form a previous
forum response.
java -cp <whatever> Httpd 808
and connect to http://localhost:808 to get an eye-full.
If you should use this for anything approacing a commercial
purpose, I will, of course, expect sizable sums of money to be
deposited in my Swiss bank account on a regular basis.
Darn it! I'm serious!
import java.io.*;
import java.net.*;
import java.util.*;
public class Httpd
     implements Runnable
     private static String HTTP_400=
          "<HTML><BODY><H2>400 Bad Request</H2></BODY></HTML>";
     private static String HTTP_403=
          "<HTML><BODY><H2>403 Forbidden</H2></BODY></HEAD>";
     private static String HTTP_404=
          "HTML><BODY><H2>404 Not Found</H2></BODY></HTML>";
     public static void main(String[] argv)
          throws Exception
          new Thread(new Httpd(Integer.parseInt(argv[0]))).start();
     private int mPort;
     public Httpd(int port) { mPort= port; }
     public void run()
          try {
               ServerSocket listenSocket= new ServerSocket(mPort);
               System.err.println("HTTPD listening on port " +mPort);
               System.setSecurityManager(new SecurityManager() {
                    public void checkConnect(String host, int p) {};
                    public void checkCreateClassLoader() {};
                    public void checkAccess(Thread g) {};
                    public void checkListen(int p) {};
                    public void checkLink(String lib) {};
                    public void checkPropertyAccess(String key) {};
                    public void checkAccept(String host, int p) {};
                    public void checkAccess(ThreadGroup g) {};
                    public void checkRead(FileDescriptor fd) {};
                    public void checkWrite(String f) {};
                    public void checkWrite(FileDescriptor fd) {};
                    // Make sure the client is not attempting to get behind
                    // the root directory of the server
                    public void checkRead(String filename) {
                         if ((filename.indexOf("..") != -1) || (filename.startsWith("/")))
                              throw new SecurityException("Back off, dude!");
               while (true) {
                    final Socket client= listenSocket.accept();
                    new Thread(new Runnable() {
                         public void run() {
                              try {
                                   handleClientConnect(client);
                              catch (Exception e) {
                                   e.printStackTrace();
                    }).start();
          catch (Exception e) {
               e.printStackTrace();
     private void handleClientConnect(Socket client)
          throws Exception
          BufferedReader is= new BufferedReader(
               new InputStreamReader(client.getInputStream()));
          DataOutputStream os= new DataOutputStream(client.getOutputStream());
          // get a request and parse it.
          String request= is.readLine();
          StringTokenizer st= new StringTokenizer(request);
          if (st.countTokens() >= 2) {
               String szCmd= st.nextToken();
               String szPath= st.nextToken();
               if (szCmd.equals("GET")) {
                    try {
                         handleHttpGet(os, szPath);
                    catch (SecurityException se) {
                         os.writeBytes(HTTP_403);
               else
                    os.writeBytes(HTTP_400);
          else
               os.writeBytes(HTTP_400);
          os.close();
     private void handleHttpGet(DataOutputStream os, String request)
          throws Exception
          if (request.startsWith("/"))
               request= request.substring(1);
          String path= request;
          File f;
          if (request.endsWith("/") || request.equals("")) {
               path= request +"index.html";
               f= new File(path);
               if (!f.exists()) {
                    if (request.endsWith("/"))
                         path= request.substring(0, request.length()-1);
                    else if (request.equals(""))
                         path= ".";
                    f= new File(path);
          else
               f= new File(path);
          if (!f.exists())
               os.writeBytes(HTTP_404);
          else if (f.isFile())
               getFile(os, f);
          else if (f.isDirectory())
               getDirectory(os, f);
     private void getDirectory(DataOutputStream os, File f)
          throws Exception
          getDirectory(os, f, "");
     private void getDirectory(DataOutputStream os, File f, String prefix)
          throws Exception
          StringBuffer szBuf= new StringBuffer();
          String szTitle= "Index of /";
          if (!f.getPath().equals("."))
               szTitle= "Index of " +f.getPath().substring(prefix.length());
          szBuf.append("<HTML><HEAD><TITLE>");
          szBuf.append(szTitle);
          szBuf.append("</TITLE></HEAD><BODY><H1>");
          szBuf.append(szTitle);
          szBuf.append("</H1><BR><PRE>");
          szBuf.append(
               "Name                              Last Modified              Size<HR>");
          String dir= "";
          if (!f.getPath().equals(".")) {
               dir= f.getPath() +"/";
               szBuf.append("<A HREF=\"..\">Parent Directory</A><BR>");
          java.text.SimpleDateFormat fmt=
               new java.text.SimpleDateFormat("EEE MMM d yyyy hh:m:ss");
          String[] list= f.list();
          for (int i= 0; i< list.length; i++) {
               String path= list;
               File d= new File(dir + path);
               if (d.isDirectory())
                    path += "/";
               szBuf.append("<A HREF=\"");
               szBuf.append(path);
               szBuf.append("\">");
               szBuf.append(path);
               szBuf.append("</A>");
               for (int j= path.length(); j< 34; j++)
                    szBuf.append(" ");
               if (d.isDirectory())
                    szBuf.append("[DIR]");
               else {
                    szBuf.append(fmt.format(new java.util.Date(f.lastModified())));
                    szBuf.append(" ");
                    szBuf.append(formatFileSize(d.length()));
               szBuf.append("<BR>");
          szBuf.append("</PRE></BODY></HTML>");
          byte[] buf= szBuf.toString().getBytes();
          os.write(buf,0,buf.length);
     private String formatFileSize(long size)
          if (size < 1024)
               return "" +size;
          if (size < (1024*1024))
               return (new Float(size/1024).intValue()) +"K";
          if (size < (1024*1024*1024))
               return (new Float(size/(1024*1024)).intValue()) +"M";
          if (size < (1024*1024*1024*1024))
               return (new Float(size/(1024*1024*1024)).intValue()) +"G";
          return "Massive!";
     private void getFile(DataOutputStream os, File f)
          throws Exception
          DataInputStream in= new DataInputStream(new FileInputStream(f));
          int len= (int) f.length();
          byte[] buf= new byte[len];
          in.readFully(buf);
          os.write(buf,0,len);
          in.close();

Similar Messages

  • Question about document/literal web service

    Hello every body.
    I have some question about document/literal web service.
    I’ve been working with Axis before.
    Axis has four valid signatures for your message-style service methods:
    public Element [] method(Element [] bodies);
    public SOAPBodyElement [] method (SOAPBodyElement [] bodies);
    public Document method(Document body);
    public void method(SOAPEnvelope req, SOAPEnvelope resp);
    The same I am trying to do with WebLogic API for webservices.
    But when I am trying to test web service (public Document method (Document body); )
    I have serialized exceptions for org.w3c.dom.Document.
    Do I have to write a custom class for org.w3c.dom.Document serialization?
    If yes can you give me some idea or example?
    The all idea behind this web service is. I have just one web service and mane classes for XML processing. Depends what xml document will be during runtime, web service will be using different class for xml processing. It works fine with Axis, but in case of WebLogic I have some problem.
    One more question… How I have to call this web service from java client?
    I have seen this example http://www.manojc.com/?sample31 ,
    but this web service looks like (Document helloDom()). I need to send Document.
    This example works for Dynamic Proxy, but does not work for static call.
    Any ideas?? Thank in advance.

    Hi,
    I am getting a similar issue. I created a Document-style/literal webservice and deployed on Weblogic 9.2 . Then I generated client stubs using clientgen. I get the following exception stack trace:
    java.rmi.RemoteException: web service invoke failed: javax.xml.soap.SOAPException:
    failed to serialize class java.lang.Objectweblogic.xml.schema.binding.SerializationException: type mapping lookup failure on
    class=class com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl TypeMapping=TYPEMAPPING SIZE=3
    ENTRY 1:
    class: java.lang.Object
    xsd_type: ['http://xmlns.ozarkexpress.com/business/sell']:stns:echoDocumentResponse
    ser: weblogic.xml.schema.binding.internal.builtin.XSDAnyCodec@1125127
    deser: weblogic.xml.schema.binding.internal.builtin.XSDAnyCodec@18dfef8
    ENTRY 2:
    class: java.lang.Object
    xsd_type: ['http://xmlns.ozarkexpress.com/business/sell']:stns:echoDocument
    ser: weblogic.xml.schema.binding.internal.builtin.XSDAnyCodec@15e83f9
    deser: weblogic.xml.schema.binding.internal.builtin.XSDAnyCodec@2a5330
    ENTRY 3:
    class: java.lang.Object
    xsd_type: ['http://www.w3.org/2001/XMLSchema']:xsd:anyType
    ser: weblogic.xml.schema.binding.internal.builtin.XSDAnyCodec@bb7465
    deser: weblogic.xml.schema.binding.internal.builtin.XSDAnyCodec@d6c16c

  • Some questions about writing rc.d scripts the right way

    Hello everyone,
    I'm setting up an environment and have a number of server daemons that I would like to automate the startup of, so I'd like to write some rc.d scripts for them. Now, I could just go ahead and roll my own but I thought I should try to learn the correct way of doing this.
    I have already read the wiki page (https://wiki.archlinux.org/index.php/Wr … .d_scripts) and have used the example there as a starting point, I have a working script that starts a daemon. However I have some questions...
    How do I handle the case where the daemon's name differs from the running process? Once case I have is to start up a web server for ruby documentation. The process I need to start is "gem server" but what is listed in ps is "ruby ... gem server". Starting works just fine, but when trying to stop it the rc.d script uses "pidof gem" to locate the daemon which fails because there is no such process (it's ruby) so stopping the daemon fails.
    My second query is how to handle multiple daemons that differ only in their arguments. I don't think the rc.d script can handle this. I would like to run several of these "gem servers" for different trees of development.
    I may be better off in this case just writing my own thing to do it.
    Any help and advice appreciated...

    Yeah, look elsewhere.
    find / -name \*.pid
    Edit:  an example:
    PIDFILE=/var/run/named/named.pid
    It's in a subdirectory, so that the user that BIND runs at, has permission to create and remove the pidfile from that directory.
    One thing to bear in mind, when stopping a daemon, is that it might not stop immediately. E.g. lighttpd, when asked to do an orderly shutdown with:
    kill -TERM $(pidof -s /usr/sbin/lighttpd) 2>/dev/null
    Cannot be immediately checked in the initscript. My erm, workaround for that is to just assume that it got the message
    Last edited by brebs (2012-03-07 13:49:17)

  • Questions about mac mini iTunes server, streaming to macbook pro, ipads, etc.

    I'm thinking about getting a mac mini to work with my NAS as a iTunes server. I have a bunch of questions about this. I will have two iPhones, a few iPads, and a laptop that will be accessing the files. I have iTunes match. This is basically to keep an always on computer for hosting the music/movies. My questions are as follows . . .
    #1 Are there any good, comprehensive guides to show you how to do this?
    #2 Can the movies be accessed when not at home on the shared network?
    #3 Can the iPads or the macbook pro download the shared movies to be stored locally?
    #4 Back to #3, how will it work on my macbook pro with listening to music (I have iTunes match)? Say i go to library and I break out my macbook pro and I don't have internet. What happens if I download music while at home onto my macbook pro to listen to it when I go to the library? Will i start a new library on my macbook pro? How will that mesh with the home server when I come back.
    #5 Is there a way to mirror files or folders? So something that I have on my macbook pro will also mirror on the home server.
    Thanks for your help on this. I'll post any follow up questions.

    seanfenton wrote:
    1. I want to replace the Optical drive with a 2TB SATA. can I use this 2.5 inch?
    I do not know if it is the same model number, but this one will work in your MBP:
    http://eshop.macsales.com/item/SEAGATE%20OWC/ST2000LM003M/
    2. I want to replace the HD with a 128GB SSD 840. When I replace these drives, will my OS still be in tact? I have never done this job before.
    No. You will have to format the drives in Disk Utility>Erase to Mac OS Extended (Journaled) and then install the OSX by using the original install disks.
    3.) I want to replace the ram sticks to max capacity. This is 2 2GB sticks, Correct?
    No.  An early 17" 2008 MBP will accept 6GB RAM with the following specifications:  200-pin PC2-5300 (667MHz) DDR2 SO-DIMM.  The best sources of Mac compatible RAM are OWC and Crucial.
    4.) Most difficult...
    I want to extend the monitor wirelessly to a projector. I thought about using Apple TV and Airplay. However, support for airplay is for MacBooks 2011 and newer. I thought of using a PS3 and the media server, but I think this brings on a format compatibility issue. (my library is so large I could not afford to convert all my movies to MP4.) So, how would you recommend I put my extended monitor with VLC player onto a projector?
    Could I possibly connect the MBP to a Mac Mini as an extension? would this work natively? I would rather use a VGA cord than F with 3rd party app BS.
    Cannot help you there.
    5..) I want to Bypass iTunes this time around. I would prefer to use Finder and VLC to manage all of my music. I mostly play all my music on shuffle, so, could I create a playlist on VLC with all of my music and play it randomly? (im sure this is possible but i'd like to organize all my plans with confirmation.)
    You are not obligated to use iTunes.
    6.) Can i upgrade the keyboard to backlit? i've read that this is possible.
    All MBPs have back lighted keyboards.  Your either needs a NVRAM reset or a repair.
    Ciao.

  • Basic questions about PL/SQL web services and datasource names

    Hi there,
    I successfully generated a web service for a PL/SQL packaged procedure in JDeveloper 11.1.1.3.0).
    In the web service base class the following code was generated:
    __dataSource = (javax.sql.DataSource) __initCtx.lookup("java:comp/env/jdbc/dbconnectionDS");However in the weblogic server the datasource name is jdbc/somethingelse so the deployment fails at first.
    What is the recommended procedure to solve this issue? The obvious solution is to manually edit the source -- that is what I did and it worked fine. However if I re-generate the web service I will lose my change. Is there a better way to do this?
    Another question -- in the generated web.xml file, there is a resource-ref for the datasource. I was hoping that changing the datasource name there would help but it didn't work. What is it used for in this context?
    Thanks
    Luis

    Hi Vishal,
    I did as you suggested but it didn't work... see below more details.
    Thanks
    Luis
    1 - I re-generated the web service from the PL/SQL package. The constructor in CFBTestWSBase class looks likes this:
    public CFBTestWSBase() throws SQLException
      {  try {
    javax.naming.InitialContext __initCtx = new javax.naming.InitialContext();
    __dataSource = (javax.sql.DataSource) __initCtx.lookup("java:comp/env/jdbc/custfeedbackDS");
    } catch (Exception __jndie) {
    throw new java.sql.SQLException("Error looking up <java:comp/env/jdbc/custfeedbackDS>: " + __jndie.getMessage());
    }2 - I added the following section to weblogic.xml:
      <resource-description>
        <res-ref-name>comp/env/jdbc/custfeedbackDS</res-ref-name>
        <jndi-name>jdbc/DataSource</jndi-name>
      </resource-description>3 - I got the following error when during deployment to weblogic server:
    [HTTP:101216]Servlet: "CFBTestWSPort" failed to preload on startup in Web application: "CustFeedbackTestWS.war".
    java.sql.SQLException: Error looking up <java:comp/env/jdbc/custfeedbackDS>: While trying to look up comp/env/jdbc/custfeedbackDS in /app/webapp/CustFeedbackTestWS.war/346617503.
    at cfbtestws.CFBTestWSBase.<init>(CFBTestWSBase.java:33)
    at cfbtestws.CFBTestWSUser.<init>(CFBTestWSUser.java:11)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    ...

  • Question: crossdomain.xml without web server

    Hi, Flex Gurus,
    In case where I want to use Flex to communicate with a
    non-web server machine, e.g. mysql, where should the
    crossdomain.xml reside on the non-web server machine?
    thanks,
    sw

    Well at that point you would put it where ever Flex can load
    the file locally and do Security.loadPolicyFile("url"). However if
    you are going to be using a socket for the connection I'm pretty
    sure crossdomain.xml isn't what you're looking for, with the recent
    security changes to the Flash Player I think you are looking more
    for a Socket Policy File. You can read up on what I'm talking about
    here at the following link.
    Policy
    File

  • Question about Using PAPI Web Service in PowerBuilder 9

    Hi, all.
    I Have a simple question about using papiws in power builder 9.
    In pb9, I created a new Web Service Proxy Wizard and I input a url for papiws(ex. http://seraphpernote:7001/papiws/PapiWebService) and click next.
    But I couldn't get any Service List.
    In Eclipse, I used this url for using papiws well.
    Does anybody know about this case??
    help me plz.

    IIRC you must activate PAPI-WS for the engine. In Studio you do it by right-clicking on the project, then "engine preferences". In enterprise/standalone you must activate PAPI-WS in the Admin Center.

  • Writing a web server.

    i am trying to write a tiny web server, with a gui, and want the gui to be a able to stop and start the server, the server is in a separate class called web server, and i need some code to destroy the instance of the class. thx in advance.

    web server code
    package tinywebserver;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class WebServer implements HttpConstants {
        /* static class data/methods */
        /* print to stdout */
        protected static void p(String s) {
            GUI.main.append(s + "\n");
            System.out.println(s);
        /* our server's configuration information is stored
         * in these properties
        protected static Properties props = new Properties();
        /* Where worker threads stand idle */
        static Vector threads = new Vector();
        /* the web server's virtual root */
        static File root;
        /* timeout on client connections */
        static int timeout = 0;
        /* max # worker threads */
        static int workers = 5;
        //port to serve from
        static int port = 8080;
        /* load www-server.properties from java.home */
        static void loadProps() throws IOException {
            File f = new File("server.properties");
            if (f.exists()) {
                InputStream is =new BufferedInputStream(new
                               FileInputStream(f));
                props.load(is);
                is.close();
                String r = props.getProperty("root");
                if (r != null) {
                    root = new File(r);
                    if (!root.exists()) {
                        throw new Error(root + " doesn't exist as server root");
                r = props.getProperty("timeout");
                if (r != null) {
                    timeout = Integer.parseInt(r);
                r = props.getProperty("workers");
                if (r != null) {
                    workers = Integer.parseInt(r);
                r = props.getProperty("serverPort");
                if (r != null) {
                    port = Integer.parseInt(r);
            /* if no properties were specified, choose defaults */
            if (root == null) {
                root = new File(System.getProperty("user.dir")+File.separator+"html");
            if (timeout <= 1000) {
                timeout = 5000;
            if (workers < 25) {
                workers = 5;
        static void printProps() {
            p("Tiny Web Server Starting on " + System.getProperty("os.name") +" "+System.getProperty("os.arch"));
            p("root="+root);
            p("timeout="+timeout);
            p("workers="+workers);
            p("port="+port);
        public static void start() throws Exception{
            loadProps();
            printProps();
            /* start worker threads */
            for (int i = 0; i < workers; ++i) {
                Worker w = new Worker();
                (new Thread(w, "worker #"+i)).start();
                 threads.addElement(w);
            ServerSocket ss = new ServerSocket(port);
            while (true) {
                Socket s = ss.accept();
                Worker w = null;
                synchronized (threads) {
                    if (threads.isEmpty()) {
                        Worker ws = new Worker();
                        ws.setSocket(s);
                        (new Thread(ws, "additional worker")).start();
                    }else {
                        w = (Worker) threads.elementAt(0);
                        threads.removeElementAt(0);
                        w.setSocket(s);
    class Worker extends WebServer implements HttpConstants, Runnable {
        final static int BUF_SIZE = 2048;
        static final byte[] EOL = {(byte)'\r', (byte)'\n' };
        /* buffer to use for requests */
        byte[] buf;
        /* Socket to client we're handling */
        private Socket s;
        Worker() {
            buf = new byte[BUF_SIZE];
            s = null;
        synchronized void setSocket(Socket s) {
            this.s = s;
            notify();
        public synchronized void run() {
            while(true) {
                if (s == null) {
                    /* nothing to do */
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        /* should not happen */
                        continue;
                try {
                    handleClient();
                } catch (Exception e) {
                    e.printStackTrace();
                /* go back in wait queue if there's fewer
                 * than numHandler connections.
                s = null;
                Vector pool = WebServer.threads;
                synchronized (pool) {
                    if (pool.size() >= WebServer.workers) {
                        /* too many threads, exit this one */
                        return;
                    } else {
                        pool.addElement(this);
        void handleClient() throws IOException {
            InputStream is = new BufferedInputStream(s.getInputStream());
            PrintStream ps = new PrintStream(s.getOutputStream());
            /* we will only block in read for this many milliseconds
             * before we fail with java.io.InterruptedIOException,
             * at which point we will abandon the connection.
            s.setSoTimeout(WebServer.timeout);
            s.setTcpNoDelay(true);
            /* zero out the buffer from last time */
            for (int i = 0; i < BUF_SIZE; i++) {
                buf[i] = 0;
            try {
                /* We only support HTTP GET/HEAD, and don't
                 * support any fancy HTTP options,
                 * so we're only interested really in
                 * the first line.
                int nread = 0, r = 0;
    outerloop:
                while (nread < BUF_SIZE) {
                    r = is.read(buf, nread, BUF_SIZE - nread);
                    if (r == -1) {
                        /* EOF */
                        return;
                    int i = nread;
                    nread += r;
                    for (; i < nread; i++) {
                        if (buf[i] == (byte)'\n' || buf[i] == (byte)'\r') {
                            /* read one line */
                            break outerloop;
                /* are we doing a GET or just a HEAD */
                boolean doingGet;
                /* beginning of file name */
                int index;
                if (buf[0] == (byte)'G' &&
                    buf[1] == (byte)'E' &&
                    buf[2] == (byte)'T' &&
                    buf[3] == (byte)' ') {
                    doingGet = true;
                    index = 4;
                } else if (buf[0] == (byte)'H' &&
                           buf[1] == (byte)'E' &&
                           buf[2] == (byte)'A' &&
                           buf[3] == (byte)'D' &&
                           buf[4] == (byte)' ') {
                    doingGet = false;
                    index = 5;
                } else {
                    /* we don't support this method */
                    ps.print("HTTP/1.0 " + HTTP_BAD_METHOD +
                               " unsupported method type: ");
                    ps.write(buf, 0, 5);
                    ps.write(EOL);
                    ps.flush();
                    s.close();
                    return;
                int i = 0;
                /* find the file name, from:
                 * GET /foo/bar.html HTTP/1.0
                 * extract "/foo/bar.html"
                for (i = index; i < nread; i++) {
                    if (buf[i] == (byte)' ') {
                        break;
                String fname = (new String(buf, 0, index,
                          i-index)).replace('/', File.separatorChar);
                if (fname.startsWith(File.separator)) {
                    fname = fname.substring(1);
                File targ = new File(WebServer.root, fname);
                if (targ.isDirectory()) {
                    File ind = new File(targ, "index.html");
                    if (ind.exists()) {
                        targ = ind;
                boolean OK = printHeaders(targ, ps);
                if (doingGet) {
                    if (OK) {
                        sendFile(targ, ps);
                    } else {
                        send404(targ, ps);
            } finally {
                s.close();
        boolean printHeaders(File targ, PrintStream ps) throws IOException {
            boolean ret = false;
            int rCode = 0;
            if (!targ.exists()) {
                rCode = HTTP_NOT_FOUND;
                ps.print("HTTP/1.0 " + HTTP_NOT_FOUND + " not found");
                ps.write(EOL);
                ret = false;
            }  else {
                rCode = HTTP_OK;
                ps.print("HTTP/1.0 " + HTTP_OK+" OK");
                ps.write(EOL);
                ret = true;
            p("\nRequest from " +s.getInetAddress().getHostAddress()+": GET " + targ.getAbsolutePath()+"-->"+rCode);
            ps.print("Server: Simple java, Tiny Web Server");
            ps.write(EOL);
            ps.print("Date: " + (new Date()));
            ps.write(EOL);
            if (ret) {
                if (!targ.isDirectory()) {
                    ps.print("Content-length: "+targ.length());
                    ps.write(EOL);
                    ps.print("Last Modified: " + (new
                                  Date(targ.lastModified())));
                    ps.write(EOL);
                    String name = targ.getName();
                    int ind = name.lastIndexOf('.');
                    String ct = null;
                    if (ind > 0) {
                        ct = (String) map.get(name.substring(ind));
                    if (ct == null) {
                        ct = "unknown/unknown";
                    ps.print("Content-type: " + ct);
                    ps.write(EOL);
                } else {
                    ps.print("Content-type: text/html");
                    ps.write(EOL);
            return ret;
        void send404(File targ, PrintStream ps) throws IOException {
            ps.write(EOL);
            ps.write(EOL);
            ps.println("404 error, the requested object was not found\n\n"+
                       "The requested resource was not found.\n\n\nTiny Web Server has encountered an error.");
        void sendFile(File targ, PrintStream ps) throws IOException {
            InputStream is = null;
            ps.write(EOL);
            if (targ.isDirectory()) {
                listDirectory(targ, ps);
                return;
            } else {
                is = new FileInputStream(targ.getAbsolutePath());
            try {
                int n;
                while ((n = is.read(buf)) > 0) {
                    ps.write(buf, 0, n);
            } finally {
                is.close();
        /* mapping of file extensions to content-types */
        static java.util.Hashtable map = new java.util.Hashtable();
        static {
            fillMap();
        static void setSuffix(String k, String v) {
            map.put(k, v);
        static void fillMap() {
            setSuffix("", "content/unknown");
            setSuffix(".uu", "application/octet-stream");
            setSuffix(".exe", "application/octet-stream");
            setSuffix(".ps", "application/postscript");
            setSuffix(".zip", "application/zip");
            setSuffix(".sh", "application/x-shar");
            setSuffix(".tar", "application/x-tar");
            setSuffix(".snd", "audio/basic");
            setSuffix(".au", "audio/basic");
            setSuffix(".wav", "audio/x-wav");
            setSuffix(".gif", "image/gif");
            setSuffix(".jpg", "image/jpeg");
            setSuffix(".jpeg", "image/jpeg");
            setSuffix(".htm", "text/html");
            setSuffix(".html", "text/html");
            setSuffix(".text", "text/plain");
            setSuffix(".c", "text/plain");
            setSuffix(".cc", "text/plain");
            setSuffix(".c++", "text/plain");
            setSuffix(".h", "text/plain");
            setSuffix(".pl", "text/plain");
            setSuffix(".txt", "text/plain");
            setSuffix(".java", "text/plain");
        void listDirectory(File dir, PrintStream ps) throws IOException {
            ps.println("<TITLE>Directory listing</TITLE><P>\n");
            ps.println("<A HREF=\"..\">Parent Directory</A><BR>\n");
            String[] list = dir.list();
            for (int i = 0; list != null && i < list.length; i++) {
                File f = new File(dir, list);
    if (f.isDirectory()) {
    ps.println("<A HREF=\""+list[i]+"/\">"+list[i]+"/</A><BR>");
    } else {
    ps.println("<A HREF=\""+list[i]+"\">"+list[i]+"</A><BR");
    ps.println("<P><HR><BR><I>Tiny Web Server on "+ port + " at " + (new Date()) + "</I>");
    interface HttpConstants {
    /** 2XX: generally "OK" */
    public static final int HTTP_OK = 200;
    public static final int HTTP_CREATED = 201;
    public static final int HTTP_ACCEPTED = 202;
    public static final int HTTP_NOT_AUTHORITATIVE = 203;
    public static final int HTTP_NO_CONTENT = 204;
    public static final int HTTP_RESET = 205;
    public static final int HTTP_PARTIAL = 206;
    /** 3XX: relocation/redirect */
    public static final int HTTP_MULT_CHOICE = 300;
    public static final int HTTP_MOVED_PERM = 301;
    public static final int HTTP_MOVED_TEMP = 302;
    public static final int HTTP_SEE_OTHER = 303;
    public static final int HTTP_NOT_MODIFIED = 304;
    public static final int HTTP_USE_PROXY = 305;
    /** 4XX: client error */
    public static final int HTTP_BAD_REQUEST = 400;
    public static final int HTTP_UNAUTHORIZED = 401;
    public static final int HTTP_PAYMENT_REQUIRED = 402;
    public static final int HTTP_FORBIDDEN = 403;
    public static final int HTTP_NOT_FOUND = 404;
    public static final int HTTP_BAD_METHOD = 405;
    public static final int HTTP_NOT_ACCEPTABLE = 406;
    public static final int HTTP_PROXY_AUTH = 407;
    public static final int HTTP_CLIENT_TIMEOUT = 408;
    public static final int HTTP_CONFLICT = 409;
    public static final int HTTP_GONE = 410;
    public static final int HTTP_LENGTH_REQUIRED = 411;
    public static final int HTTP_PRECON_FAILED = 412;
    public static final int HTTP_ENTITY_TOO_LARGE = 413;
    public static final int HTTP_REQ_TOO_LONG = 414;
    public static final int HTTP_UNSUPPORTED_TYPE = 415;
    /** 5XX: server error */
    public static final int HTTP_SERVER_ERROR = 500;
    public static final int HTTP_INTERNAL_ERROR = 501;
    public static final int HTTP_BAD_GATEWAY = 502;
    public static final int HTTP_UNAVAILABLE = 503;
    public static final int HTTP_GATEWAY_TIMEOUT = 504;
    public static final int HTTP_VERSION = 505;
    the gui is just normal gui stuff, it contains the main method

  • Question about Sun Java Calendar Server 7

    You downloadable forum, at [http://www.sun.com/software/products/calendar_srvr/get_it.jsp|http://www.sun.com/software/products/calendar_srvr/get_it.jsp],
    leaves one with two questions.
    -What databases are needed/supported by this MessageBoard System for backend storage?
    -What are the licensing details? May the MessageBoard/Communications Suite 7
    be installed and used in a commercial environment, free?
    -May Sun Java Calendar Server 7 be downloaded without the Communications suite?
    -Can it be run off an Apache Tomcat Server with J2SE,J2EE codebases?

    Although... at the top of this forum it says
    This is a forum for new Java developers to get acquainted with the technologies and tools associated with the Java Platform.It doesn't actually say anything about programming, not there nor in what follows. So it isn't surprising that the OP thought this was a suitable forum to ask about that server, which looks as if it might be a "tool associated with the Java platform".

  • Beginner's questions about WCF and web services

    For the purpose of this forum let me just say that I got my certs back in Dot Net 2.0.  I know how to write simple web services.  Now someone has dumped a huge package of code on my desk that (I think) contains a WCF project (without documentation
    of course).  Contains references to System.ServiceModel.
    So my questions...
    1.  What (if anything) is the difference between WCF and Web API?
    2.  If there is a difference,  how do you decide which one to use?
     3.  Assuming that this project on my desk is a WCF project, where can I find some hints on how to run it in VS2013 Community? 

    WEB API is restricted to ASP.NET and HTTP. 
    http://captechconsulting.com/blog/john-nein/aspnet-web-api-vs-windows-communication-foundation-wcf
    WCF uses more communication protocols than just HTTP, there are more ways to host a WCF service other than IIS, like a selfhosting exe type WCF server,   and WCF is a SOA solution.
    WCF is a more robust solution in a whole lot of ways is the bottom line.
    http://en.wikipedia.org/wiki/Service-oriented_architecture
    http://www.codeproject.com/Articles/515253/Service-Oriented-Architecture-and-WCF

  • Question about RAC 10g on server running AIX and domain name changes

    We have several 10g clusters running on IBM p-Series AIX servers, and our company is changing the domain name for our network. I am concerned that if we do not change the domain names in the TNSNAMES.ora file and also the /etc/hosts file on each server, the cluster will no longer function. We are using CRS (version 10.2.0.3) and ASM within each cluster.
    Does anyone know where I can find information about changing the domain name that was set up as part of the CRS and database installs for RAC? Does anyone have experience doing this, and would be willing to share a few insights? Thanks in advance for any advice you can give!

    You may be able to use the VIPCA utility for RAC to change or modify the public and private settings for your domain names on AIX. Also, the Oracle 10g DBCA "Database Configuration Assistant" should be of use to change your settings for your RAC environment.
    Also, see here for a good IBM Redbook that covers Oracle 10g RAC on AIX platforms:
    http://www.redbooks.ibm.com/redbooks/pdfs/sg247541.pdf
    Regards,
    Ben Prusinski
    http://oracle-magician.blogspot.com/
    Regards,
    Ben Prusinski
    http://oracle-magician.blogspot.com/

  • Question about configurations in Old Server

    Dear All,,
    I have a Question !
    How will you find what are the configuration are in a server.. for example..
    Is the DB configured RAC or DATA guard ?
    Is RMAN configured or not ?
    because at any time we have to face this request for Client who they don't have details regarding their Server,, (in Old Support Projects).
    if i have a plan for a upgradation of database what are the documents i have to prepare and what are the steps i have to take at initial stage !
    Regards
    HAMEED

    Hameed,
    This should be documented and those documents should be provided by the clients.
    You could do some investigation but again this will not be correct or complete without the documentation. For example, for RAC you could query the dynamic views (gv$instance, v$instance on each node) but this assume you already know what servers are configured. Or, you could refer to the RAC/DataGuard/RMAN configuration MOS docs for Oracle E-Business Suite and go through the steps to verify if those configurations are presented or not.
    Thanks,
    Hussein

  • Question about configuring REST web service in EBS instance

    I am from EBS SCM team. From one wiki page, it says OA Framework provides REST framework to expose OAF BC4J objects as web services. Can you provide more details about how to configure REST web service for one EBS instance? Any related information is also helpful.
    Edited by: 936859 on Sep 7, 2012 5:45 PM

    IIRC you must activate PAPI-WS for the engine. In Studio you do it by right-clicking on the project, then "engine preferences". In enterprise/standalone you must activate PAPI-WS in the Admin Center.

  • Question about MBeans for web service metrics and configuration

    Hi,
    I'm new to JMX and trying to figure out how to create a MBean structure that captures a tree similar to the following for some web services I'm working on. All the operations will have the same set of metrics I'm collecting, so I'd like to reuse as much of the MBean structure as possible. In addition, the service will have various config parameters that need to be able to be modified during runtime via JMX. Below is an example of something similar to what I'd like to be able to do:
    user
    +-com.example.ws.CalculatorService
      +-Attributes
        +-ServiceName
        +-ServiceVersion
        +ServiceConfigParam1
        +ServiceConfigParam2
      +Operations
        +-SetServiceConfigParam1()
        +-SetServiceConfigParam2()
      +-AddOperationMethod
        +-Attributes
          +-RequestCounter
          +-ResponseCounter
        +-Operations
          +-ResetAllCounters()
          +-ResetRequestCounter()
          +-ResetResponseCounter()
      +-SubtractOperationMethod
        +Attributes
          +-RequestCounter
          +-ResponseCounter
        +-Operations
          +-ResetAllCounters()
          +-ResetRequestCounter()
          +-ResetResponseCounter()Where the counters are a variety of metrics to collect for each web service operation. Is there a standard/commonly accepted way to implement this? What type of MBean is best suited, standard, or do I need to use dynamic MBeans? Thank you for any pointers to useful references.
    /Paul Kuykendall

    I ended up finding the answer after more digging. The page [http://java.sun.com/developer/technicalArticles/J2SE/mxbeans|http://java.sun.com/developer/technicalArticles/J2SE/mxbeans] had a section about handling inter-MXBean references that turned out to be exactly what I was looking for.
    This reply is just to help anyone else that stumbles through with a similar problem to mine and point them in the right direction.
    /Paul

  • Question about 3750 as dhcp server

    hi,
    With two c3750 switches stacked one customer is  plannig to configure those switches to act as dhcp server for about three thousand clients.
    Can this configuration affect to the normal behaviour of the stack?
    Could come up some problems with this amount of clients?
    Thanks in advance

    uosambela wrote:hi,With two c3750 switches stacked one customer is  plannig to configure those switches to act as dhcp server for about three thousand clients.Can this configuration affect to the normal behaviour of the stack?Could come up some problems with this amount of clients?Thanks in advance
    Personally with that many clients i would look to use something like Microsoft Windows DHCP server. Using switches/routers as DHCP servers is fine for a few vlans or clients but for 3000 it is much easier to manage with a dedicated server.
    Jon

Maybe you are looking for

  • Add the Z report to the Navigation Link

    We are working on the SAP CRM 4.0 with Web client as a interaction center. As per our requirement we need to add custom report to the navigation link.When the user clicks on this link the report should appear in Web client. At present i am trying wit

  • Is there a script for this?

    Hello, I have a 176 page pdf that has black type throughout, a lot of those pages also have boxes filled with black. I need to change the boxes to rich black but leave the type black only. I tried using actions but it changes both since they have the

  • Start Routine / Update Rule ABAP

    Hello Gurus I am trying to write the code to do the following but I am not getting very far: Two parts: Load from DSO1 to Cube1 Only when DSO1-Product also exists in DSO2 Also lookup a field, FIELD1, from DSO2 which is not in DSO1, but is in DSO2 (ba

  • Camera Default not working

    I have Aperture 3 and set up a Camera Default in the Raw settings. The problem is that Aperture picks the Apple settings everytime I import and NOT my Camera Default settings. What can I do to fix this? Kevin

  • What is the volume 'ldap_bk' that Mounted and Unmounted every hour or two?

    What is the volume 'ldap_bk' that do Mounted and after 5 to 10 secs Unmounted ? This happen every hour or two.