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

Similar Messages

  • 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();

  • Writing a string to a file on a web Server

    Hi all,
    i need to write a string of length say 200 chars in a file located on my local apache web server.
    I have an applet that registers username and password +some other information in a string.
    So i need to write this string to a new file every time a new user logs in with a new file name.
    I have this perl script but i dont know how to modify it
    #c:\perl\bin\perl.exe
    # wdwrite
    # this is the CGI that will take the # applet info and write it to a file
    open(OUT, ">> C:/Program Files/Apache Group/Apache2/giorgi/JCachesim/logs/log.txt");
    print "content-type: text/plain\n\n";
    while (<>) {
    print OUT $_;
    print $_;
    close (OUT);
    exit 0;
    And also what do i need to do to call this script (actually not this,the modified one) from my applet?
    I have some snippets of java code but i dont think they work for my case.
    Can you help me?
    Thank you very much,
    Chris

    If it's a perl script, then you can execute it as a CGI or apparently using mod_perl, which I've never worked with. In either case, it's not really a java question; it's a Perl or Apache admin question and you'd probably get better responses on forums for those.
    You can invoke it by opening an HttpURLConnection to it, at whatever path the script lives on at the server.

  • Setting Up a Java Web Server on Linux

    Greetings,
    After a lot of reading, I've decided to learn Java server-side technologies (I already know Java (desktop)
    but with little experience) in order to develop my database driven dynamic website projects.
    However, I'm completed lost between the hundreds of acronyms related to Java and the "thousands" of technologies involved.
    Google hadn't help me understand what they really are and how they relate with each other.
    Even though is easy to find what they stand for and some faqs/descriptions, it hasn't been enought to clear my mind.
    I want my webserver application to do, among other things, the following:
    Retrieve Data from a database, do generate dynamic html files.
    Story Data on the database, from html forms.
    Send automaticly emails for multiple users. (newsletter for example)
    E-Commerce.
    Html graber/parser (I don't know if this is the right word, I mean a program that for example, goes to a URL with an html
    table, and stores that information in a database table, as long as the format didn't change).
    Real Time Chat feature.
    Database connection pooling, caching, and other important optimizations.
    I'm not asking for how to develop or configure this features nor what components and programs, must be installed.
    At the moment, I only want to know how to set up a Java solution that will support them when they are needed.
    *** Linux ***
    I want to set up my webserver on a linux distribution.
    In that respect, I don't know if I should choose RedHat or Fedora Core.
    I've heard that fedora is better for a webserver (having in mind that Red Hat Enterprise AS/ES aren't free).
    But I've read in several sun turorials/webpages references to RedHat (on a J2EE context).
    So I'm wondering if is better to go for Fedora or RedHat. Are there pros & cons? They equally support Java?
    *** Technologies ***
    Then in starts the acronyms problem.
    What do I need to install, in what order, for what?
    Some aconyms and technologies, I have read about but don't fully understand are the following:
    Apache
    J2EE
    J2EE 1.4 SDK
    SUN Java System Application Server Platform Edition 8
    J2SE 1.4.2 SDK
    SUN Java Enterprise System
    Tomcat
    Struts
    Cocoon
    JBoss
    I already know J2EE is only a specification. What implements that specification? Sun Java System Application Server?
    J2SE SDK? or Tomcat?
    What is the role of each technology, namely Apache, Tomcat, Sun Application Server?
    What is the Sun Java Enterprise System?
    How do Struts, Cocoon, JBoss relate to Java?
    Which of these technologies are mutually exclusive (analogous)?
    *** Doubts ***
    Then, I have some doubts that are keeping me from starting to study seriously the important techonologies, because I don't
    want to lose lot's of time and effort learning them to after a dillusion start everything again with PHP (the language
    which make me think and read a lot before going for Java). To keep this from happening, I would like to know the following:
    I want to use Java for developing websites with commercial/profitable use for my company, in some throught e-commerce,
    and in other by banners. I want to do everything by the book, with required licenses.
    ------ Java is Free?
    Is Java Completely Free or it might be possible that at a certain point, when I need some component or library,
    multi-machine webserver, performance or security for high-traffic I will see "buy now" instead of "download now"?
    For what they may "ask for money"? and what are the disavantages if I can't buy?
    For example, "Java System Application Server Standard Edition 8.1 2005Q1" and
    "Java System Application Server Enterprise Edition 8.1 2005Q1" cost $2.000 and $10.000 respectively. That is money.
    (http://www.sun.com/software/products/appsrvr/index.xml). What are the disavantages if stick to the free edition?
    Features like (from sun site)
    Standard Edition:
    Extends the capabilities of the Platform Edition to provide secure, remote, multi-instance, multi-machine management.
    It is aimed at high-volume applications and Web services.
    Enterprise Edition:
    Further extends the capabilities of the Standard Edition to provide continuous availablity for applications and
    Web services. It is aimed at business critical, high value applications and Web services.
    Suppose I achive lots of traffic and I keep the free platform edition.
    I won't be able to have a multi-machine webserver set up correctly?
    What are the drawbacks? How big are the performance penalties?
    ------ Technologies Availability
    Finnaly, I have the idea (I don't know if it's accurate) that there are Sun versions and Open-Source Free versions
    of doing or supporting the same Java related thing.
    Despite the way I choose to set up a Java webserver, I will always have all J2EE techonolies like:
    Java API for XML-Based RPC (JAX-RPC), JavaServer Pages, Java Servlets, Enterprise JavaBeans components,
    J2EE Connector Architecture, J2EE Management Model, J2EE Deployment API, Java Management Extensions (JMX),
    J2EE Authorization Contract for Containers, Java API for XML Registries (JAXR), Java Message Service (JMS),
    Java Naming and Directory Interface (JNDI), Java Transaction API (JTA), CORBA, and JDBC data access API.
    I really appreciate some help. I could learn the basics of all this "stuff" before asking. But the point why I'm asking
    is precisely not starting to learn something I may won't use. Obviously, I will have to make a lot of reading during maybe
    months before writing the first line of code of my projects, but being certain that it will fit my needs.
    I will be very thankful if you can enlightme in my fedora/redhat, setup, free/cost and technologies avaibility issues.
    Thanks Beforehand,
    Pedro Vaz

    Apache is a free Web-server.
    Tomcat is a servlet (and JSP) container. It can be stand-alone or can be used together with a Web server (like Apache).
    J2EE's scope is much wider than the servlet stuff, but a standalone Tomcat is a good starting point to servlets and JSP.
    One of our "real-world" applications is run by a standalone Tomcat using POI and Velocity. I did not regret this architectural decision.

  • Web Server Filter Based SSO to Non-SAP Apps

    Hi,
    I am following SAP Note 442401 for configuring the Non-SAP App for Web Server Filter based SSO using SAP Logon Ticket. Also, I have downloaded the 5_0_2_8.zip file.
    The Readme doc of this zip file says:
    "<b>Changes in Web server filter plugins
    The Web server filter plug ins and the Ticket Toolkit now were separated.
    See subdirectories for further information:
    "C"          the Ticket Toolkit
    "filter"     the Web server filter plug ins
    This is the last released version (5.0.2.8) on SAPSERV.
    Pleaser refer for newer versions to SAP Service Marketplace (http://service.sap.com/patches)
    Technology Components-> SAP SSOEXT -> SAP SSOEXT</b>"
    Zip file has two folders named "C" and "filter".
    "C" folder has cpp code to varify the ticket.
    "Filter" folder has DLLs for the different web servers.
    So far so good . Now, what I want to know is that is placing the  DLL from the Filter folder onto the respective web server and doing some configs, as per the PDF provided with ZIP file, enough?
    Or do I need to do anything else, like writing any class to read and validate the Ticket?
    Thanks,
    Vivek

    See Web Server Filter Based SSO to Non-SAP Apps

  • Sun Java System Web Server 7.0 available

    I am delighted to announce that Sun Java System Web Server 7.0 is now available for download, purchase, deployment, and more.
    This release builds on the highly scalable and stable heritage of Web Server. It features an entirely re-designed Administration interface designed around clusters, easy access to frequently performed tasks, simplification of frequently performed tasks., and a fully scriptable command line interface featuring functional parity with the browser-based interface.
    In addition to the administration changes this release features:
    o Full 64-bit support for Solaris SPARC and Solaris AMD64 platforms
    o Regular expression pattern matching for URL re-writing and mass hosting
    o If/Then/Else constructs within request processing
    o Advanced sed based input and output filters
    o Dynamic loading of Certificate Revocation Lists (CRLs) without requiring daemon restart
    o Elliptic Curve Cryptography (ECC)
    o Built in request mapping for protection against abnormal load patterns and Denial of Service protection
    o WebDAV ACL support
    o Out-of-box Java support for Servlets 2.4, JSP 2.0, JSF 1.1, JSTL 1.1, JWSDP 2.0 based web services
    o Java session failover and recovery within a cluster of peers
    o Integrated HTTP reverse proxy User-Agent
    o Bundled FastCGI client for use with third party scripting environments such as Perl, PHP, Ruby on Rails, etc
    o Enhancement of perfdump, stats-xml, and SNMP as well as more ability to monitor the Java container and the ACL system
    o Much more
    The software can be downloaded from:
    http://www.sun.com/download/products.xml?id=45ad781d
    The documentation is available at:
    http://docs.sun.com/app/docs/coll/1308.3

    If 7.0 was released, how come http://www.sun.com/webserver still only talks about 6.1?

  • Global data in a servlet using iPlanet Web Server

    Our configuration is an Applet->Servlet->JNI->C/C++ code.
    We have C code that does a number of lengthy mathematical calculations. This C code not only uses its own global variables but, it is also comprised of numerous subroutines that all call each other, reading and writing global C variables as they go. These globals are all isolated to the C code shareable object (.so) library that is included using the LoadLibrary call when the servlet is initialized.
    The problem is that in a multi-user environment (3-5 simultaneous users) we need to have each user have their own "copy" of the servlet (and the C code) so that users will not be accessing each other's global data. We can NOT have only one copy of the C code and define it as synchronized because the calculations that are performed can take a very long time and we can not hold off user requests while the firs user finishes.
    Our hope is that there is a way to configure the iPlanet Web server such that each new user that starts up a copy of the Applet/Servlet combination will get their own "space" so that they can work independently of any other user. We have at most 20 users of this system and only 3-5 simultaneous users so we should not have a problem with memory or CPU speed.
    If anyone has a solution, I would greatly appreciate it!

    The C library is shareable. But you don't want it to be shared. That's your question summarized, isn't it?
    You probably can't prevent it from being shared, so to prevent multiple use of it you would have to queue up the requests to be done one at a time. WynEaston's suggestion of having the servlet implement SingleThreadModel would help, but I believe the servlet spec allows servers to run multiple copies of a servlet that does that (as opposed to running a single copy in multiple threads).
    Your other alternative is to rewrite the math in Java, or at least in some object-oriented language where you don't need global variables (which are the source of your problem). All right, I can already hear you saying "But that wouldn't be as fast!" Maybe not, but that isn't everything. Now you have a problem in queueing theory: do you want a single server that's fast, but jobs have to wait for it, or do you want multiple servers that aren't as fast, but jobs don't have to wait? That's a question you would have to evaluate based on the usage of your site, and it isn't an easy one.

  • Error: java.lang.OutOfMemoryError when uploading CSV files to web server

    Hi experts,
    I have made a JSP page from which clients load csv files to web server. I am using Tomca 4.1 as my web server and JDK 1.3.1_09.
    The system works fine when uploadiing small csv files, but it crashes when uploading large CSV files.
    It gives me the following error:
    java.lang.OutOfMemoryError
         <<no stack trace available>>
    This is the code that I used to load files....
    <%
    String saveFile = "";
    String contentType = request.getContentType();
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
         DataInputStream in = new DataInputStream(request.getInputStream());
         int formDataLength = request.getContentLength();
         byte dataBytes[] = new byte[formDataLength];
         int byteRead = 0;
         int totalBytesRead = 0;
         while (totalBytesRead < formDataLength)
              byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
              totalBytesRead += byteRead;
         String file = new String(dataBytes);
         saveFile = file.substring(file.indexOf("filename=\"") + 10);
         saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
         saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
         int lastIndex = contentType.lastIndexOf("=");
         String boundary = contentType.substring(lastIndex + 1,contentType.length());
         int pos;
         pos = file.indexOf("filename=\"");
         pos = file.indexOf("\n", pos) + 1;
         pos = file.indexOf("\n", pos) + 1;
         pos = file.indexOf("\n", pos) + 1;
         int boundaryLocation = file.indexOf(boundary, pos) - 4;
         int startPos = ((file.substring(0, pos)).getBytes()).length;
         int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
         String folder = "f:/Program Files/Apache Group/Tomcat 4.1/webapps/broadcast/file/";
         //String folder = "10.28.12.58/bulksms/";
         FileOutputStream fileOut = new FileOutputStream(folder + saveFile);
         //out.print("Saved here: " + saveFile);
         //fileOut.write(dataBytes);
         fileOut.write(dataBytes, startPos, (endPos - startPos));
         fileOut.flush();
         fileOut.close();
         out.println("File loaded successfully");
    //f:/Program Files/Apache Group/Tomcat 4.1/webapps/sms/file/
    %>
    Please can anyone help me solve this problem for me...
    Thanx...
    Deepak

    I know it may be hard to throw away all this code, but consider using the jakarta fileupload component.
    I think it would simplify your code down to
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    List /* FileItem */ items = upload.parseRequest(request);
    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            processFormField(item);
        } else {
            // item is a file.  write it
            File saveFolder = application.getRealPath("/file");          
            File uploadedFile = new File(saveFolder, item.getName());
            item.write(uploadedFile);
    }Most of this code was hijacked from http://jakarta.apache.org/commons/fileupload/using.html
    Check it out. It will solve your memory problem by writing the file to disk temporarily if necessary.
    Cheers,
    evnafets

  • Problem while configuring the Apache Web Server as the Intermediary Server

    Hello,
    I want to use Apache 2.0 web-server as a proxy for my SAP EP so that I could access http://portal_server:50000/irj through this Apache external web-server.
    I checked this sap help link as a reference.
    http://help.sap.com/saphelp_nw04/helpdata/en/18/5cea2296190e4cb7faf9468ad793ea/frameset.htm
    But still not clear what exact configuration I need to do in the httpd.conf file. I searched the posted forums on this topic but couldnt get exact steps.
    It would be grateful if anyone can guide me on this configuration (redirecting url etc).
    Thanks in advance.
    -Mandar

    STEPS OF SECURE APACHE-SSL
    1.Install apache version like apache_x_y_z_win32.exe also select the right combination of mod_ssl and Openssl.
    (Like for apache1.3.33 you need mod_ssl_2.8.22 and Openssl_0.9.7f or Openssl_0.9.7g.
                       Or
    Select a mix of all three like [Apache_1.3.33-Mod_SSL_2.8.22-Openssl_0.9.7f-Win32.zip]
    (for this  install apache service also).
    2.    Select   httpd.conf file from (apache\conf) open it for configuration.
    3.   Stop the services of apache from Control panel \ administrative tools \ services.
             Note:--  may be it is possible all files for configuration will not be there in apache2.exe  then extract the 
              Apache_2.0.54-Mod_SSL_2.8.22-Openssl_0.9.7f-Win32.zip  file and copy conf,lib,modules logs
    files in corresponding folder of Apache2.exe.
                                                 HTTPD.CONF   Configuration
    1.     Replace all occurrences of www.my-server.dom with the real domain name!
           (If you have installed apache from .exe file then its doesn’t required but for . Zip archive file you have to replace it)
    2.     Comment port 80 like  # port 80
    3.     Write Listen 80 and Listen 443 in httpd.conf file.
    4.     Extract Openssl in any folder and copy files ssleay32.dll and libeay32.dll into WINNT\SYSTEM32 paste them here.
    5.     Download Openssl.cnf file because you need to configure openssl.exe. a link apear select saveas and save it to bin folder of apache2 directory
    6.     Copy all the *.exe, *.so, *.dll inside your apache\bin directory from extracted Openssl directory.
    7.     Write
                  LoadModule ssl_module modules/ApacheModuleSSL.dll
                      or
                  LoadModule ssl_module modules/ApacheModuleSSL.so
                      or
                  LoadModule ssl_module modules/mod_ssl.so
                 after the LoadModule lines that are already in the httpd.config file
          8.    Write AddModule mod_ssl.c this for apache1 for apache2 it is noy required.
               after the AddModule lines that are already in the httpd.config file.
         9.  Add the following to the end of httpd.conf:
                        SSLMutex sem
                        SSLRandomSeed startup builtin
                        SSLSessionCache none
                        SSLLog logs/SSL.log
                        SSLLogLevel info
                        SSLEngine On
                        SSLCertificateFile conf/ssl/my-server.cert
                        SSLCertificateKeyFile conf/ssl/my-server.key
                        ProxyRequests Off
    <Proxy *>
    Order deny,allow
    Allow from all
    </Proxy>
    ProxyPass / http://ServerName:50000/     // your server name and port number
    ProxyPassReverse / http://ServerName:50000/   // your server name and port number
    ProxyPreserveHost On
    save the Httpd.conf file
                                                     GENERATING CERTIFICATE
    a.     Open Command Prompt
    b.     Reach till bin directory by writing like   cd apache\bin
    c.     Write command     bin> openssl req -config openssl.cnf -new -out my-server.csr and put required detail.
    d.      Write openssl rsa -in privkey.pem -out my-server.key.
    e.     Write openssl x509 -in my-server.csr -out my-server.cert -req -signkey my-server.key -days 365.
    f.     Write openssl x509 -in my-server.cert -out my-server.der.crt -outform DER.
    g.     Create an Apache/conf/ssl directory and move my-server.key and my-server.cert into it.
    10.     Start Apache services from control panel \ Administrative tools \ services.
    11.     Now you have made Apache as SSL enabled open browser and test it by https://localhost

  • How to create web applications with the LabVIEW web server

    Wonderful Forum,
    I've noticed that sometimes it can be tricky for LabVIEW users to learn how to create their own custom web clients using the LabVIEW web server. I created a LabVIEW web development community group and wrote some tutorials to teach the basics of creating web clients using HTML, Javascript, and AJAX. The idea is that LabVIEW users without any web background can quickly look at some tutorials and examples to get started on their own projects.
    https://decibel.ni.com/content/groups/web-services
    What do you think?
    Joey S.
    Software Product Manager
    National Instruments

    Hi Joey,
    A great idea! I recently presented at a local user group meeting about my WebSockets API (see the links in my signature). I've uploaded the presentation and the demo code I gave to our UG here.
    I think the barrier to entry is with needing to know the web languages (e.g. html/css/js) as well as writing your LabVIEW code. I have joined the group and look forward to seeing some interesting content on there! Certainly some demos of using AJAX to make requests to Web Services and do something with the data (e.g. display on a graph) would be a good place to start.
    Certified LabVIEW Architect, Certified TestStand Developer
    NI Days (and A&DF): 2010, 2011, 2013, 2014
    NI Week: 2012, 2014
    Knowledgeable in all things Giant Tetris and WebSockets

  • Publishing .shtml files to web server

    Hi,
    I am evaluating CQ5 to manage my web application having .html and .shtml pages (pages with SSIs, server side includes). I want to manage the web content - htmls, .shtmls, images etc using CQ5.
    I have following questions -
    1. Does CQ5 have any restrictions in publishing pages with extension .shtml?
    2. What are the best ways to manage these .shtml in CQ5?
    3. How do I publish these .shtmls to web server?
    Regards,
    vkp

    As a general rule anything you manage in CQ gets published to the web server via the Dispatcher plugin. Dispatcher functions as a reverse proxy sending request back to the publish servers and caching the result.
    As far as managing the .shtml items I am assuming that you want them to be generated and managed as pages in CQ with traditional component authoring interfaces. You will have two big challenges in this scenario:
    Sling request handling - Sling uses the extension to map a request to script. By default sling would consider .shtml to be different than .html and you'd need to name your JSPs appropariately. This could be problematic if you are reusing components across both page types. I have never tried this, but you could consider using the Sling Default Get servlet's alias configuration to map .shtml to .html which might work, but I have never actually done that.
    Link rewriting - you are going to have to write a layer of code that you use in your components to properly set the right extensions on the URLs when linking to these .shtml pages. By default CQ is just going to add .html. You will need to make sure you have some sort of way to tell in the page's meta-data whether or not it's an .shtml - perhaps based on template and then make sure you take that into account when writing out links. The rich text editor will be a challenge because adds the .html in JavaScript and stores it in the repository. You will have to override this in someway if you want to link to these .shtml pages in a rich text editor.
    In the past when I have needed to leverage SSIs through CQ I have just configured Apache to do do the SSI processing on .html to avoid these challenges. It means a heavier load on the web tier and it has some potential issues but generally is a better option than trying to get CQ to handle the .shtml extension.
    Also the other thing to consider is whether or not you really need .shtml files since CQ is pretty dynamic - usually you can figure out how to handle the dynamic assembly in CQ and not at the web tier (or using AJAX).
    Or did I misunderstand your plan - are you managing these as files in the DAM. If you are managing them as files in the DAM then you just have to make sure that you have a rendering servlet that will set the right mimetype.

  • Using private key installed on Sun One web server in java code.

    Hi,
    I am digitally signing an XML string. I have been able to successfully do this using the .keystore and the JSSE API.
    I need to run this code in the SUN ONE Web server, hence I have installed a self signed cert in the web server, using the web console.
    I need to load the .keystore that is being maintained by the Sun One Web Server in my Java program as a �KeyStore� object
    Presently I am using the following JSSE calls:
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    // Load the keystore contents
    FileInputStream in = new FileInputStream(keystoreFile);
    keystore.load(in, keystorePassword);
    in.close();
    Now how do I access the keystore and the certs that I have added in the web server? Is there any SUN API for this?
    Any help will be appreciated!
    Regards,
    Nandan
    Message was edited by:
    NANDAN

    The global zone should offer no services to the network except services required to administer the system. SSH from known IPs. Put everything in zones for the security of the system. Zones have no performance penalty so there is no advantage to running on the host system in the global zone.
    Sun's Java Enterprise server software webserver, directory server, etc required a full zone due to Solaris Package issues or conflicts; writing stuff in /usr; or both. A whole root for this software should not be a big deal. I create zones 9 at a time numbered in sequence. Zone 8 and 9 are whole root zones for requirements such as this.
    I'll leave to others to alert us if the whole root zone requirement changes for Sun's Java Enterprise Server software.
    Message was edited by:
    jgmarce

  • Web Server on Windows XP?

    I need to write a servlet to provide SQL data for a cell phone. I've written a J2ME app to access text from the web, but I know nothing about the other end. Do I have to install a whole new OS like Linux, or is there software that will run under XP as a web server?

    sultal writes:
    If you wish to go for Webserver + Tomcat option you should opt for Apache + Tomcat as they are produced
    by the same crowd and work well together.
    I would personally go for one peace of software to do the job, rather than 2. Sun's appserver(platform
    edition is free) or webserver would work well - you won't need Tomcat with those.OK, I uninstalled Tomcat and installed the appserver. Then I did a search on "writing servlets" and found:
    http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/servlet.html
    At the top of the page it says you need Tomcat and gives a link for downloading Tomcat.
    So now I'm confused. I guess this is referring to J2SE only and not the Application Server environment?
    chilideveloper writes:
    you might wanna try the Net Beans mobile edition from http://www.netbeans.info/downloads/download.php?type=5
    .0Already got it. But while we're on the subject, is there anything else I need to download to get NetBeans to write an SQL servlet? (Such as the way I had to download the Mobility Pack to write the cell phone client.)
    After this , you can decide any one of the following
    - use Sun Java System Web Server 6.1
    - use tomcat alone OK, so now I'm confused again, do I or don't I need Tomcat? What is the difference between Web Server 6.1 and Application Server 8.2?

  • FW: iPlanet Web Server 4.x Advisory

    All--
    A message from iPlanet about iWS:
    Recommend Immediate Patch/Upgrade
    We are writing to inform you of an important upgrade recommendation. iPlanet
    has identified a security vulnerability in the iPlanet Web Server Enterprise
    Edition 4.x products. This problem does not affect any Web Server releases
    prior to the 4.x versions, however it does affect all iPlanet applications
    operating on the Web Server platform.
    A patch and implementation instructions to address the problem are now
    available on the iPlanet.com Tech Support site at
    http://www.iplanet.com/support/. Without this patch/upgrade, the problem
    will persist and affect your site's data security, potentially leading to a
    data corruption event.
    iPlanet urges all iPlanet Web Server customers to upgrade immediately to
    prevent any potential data security risks, and we apologize for any
    inconvenience that this may cause you.
    If you have additional technical questions, please call your technical
    support contact.
    Sincerely,
    Annelies Habermacher
    Vice President, Worldwide Customer Support
    iPlanet E-Commerce Solutions
    See the following links for more information:
    http://atstake.com/research/advisories/2001/index.html#041601-1
    http://www.kb.cert.org/vuls/id/276767
    The iPlanet JATO Team

    Can you provide the error logs file of the instance which fails to start?
    Thanks

  • Environment property on iPlanet/ Sun web server

    We are migrating an application from tomcat to the Sun Web Server / iPlanet . Earlier in the tomcat server, our applications used context xml files and in them we had a setting as follows
    <Environment name="instanceNum" value="100100"
    type="java.lang.String" override="false"/>
    What is the equivalent of the above in the iPlanet server?
    Thank you

    This would be non-trivial in WS6.0. Additionally, WS6.0 is end-of-lifed, and has known security problems that are NOT going to be fixed. You should consider upgrading.
    URL re-writing (and much more) is a native feature of WS7.0.

Maybe you are looking for